trueppm-api 0.4.0b2__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 (759) hide show
  1. trueppm_api/__init__.py +14 -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 +164 -0
  8. trueppm_api/apps/access/management/commands/migrate_locked.py +96 -0
  9. trueppm_api/apps/access/management/commands/revoke_api_tokens.py +209 -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 +167 -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_userdefinedmentiongroup.py +82 -0
  24. trueppm_api/apps/access/migrations/0014_programmembership_progm_serverver_idx.py +19 -0
  25. trueppm_api/apps/access/migrations/0015_programuserdefinedmentiongroup.py +86 -0
  26. trueppm_api/apps/access/migrations/0016_externalstakeholder.py +67 -0
  27. trueppm_api/apps/access/migrations/0017_viewer_ordinal_one.py +132 -0
  28. trueppm_api/apps/access/migrations/0018_programmembership_sync_seq_and_more.py +52 -0
  29. trueppm_api/apps/access/migrations/0019_programmembership_reinstated_at_and_more.py +22 -0
  30. trueppm_api/apps/access/migrations/__init__.py +0 -0
  31. trueppm_api/apps/access/models.py +588 -0
  32. trueppm_api/apps/access/permissions.py +2837 -0
  33. trueppm_api/apps/access/serializers.py +946 -0
  34. trueppm_api/apps/access/services.py +667 -0
  35. trueppm_api/apps/access/signals.py +103 -0
  36. trueppm_api/apps/access/tasks.py +50 -0
  37. trueppm_api/apps/access/throttles.py +95 -0
  38. trueppm_api/apps/access/urls.py +191 -0
  39. trueppm_api/apps/access/views.py +1931 -0
  40. trueppm_api/apps/agents/__init__.py +6 -0
  41. trueppm_api/apps/agents/apps.py +11 -0
  42. trueppm_api/apps/agents/canonical.py +73 -0
  43. trueppm_api/apps/agents/deferred.py +108 -0
  44. trueppm_api/apps/agents/management/__init__.py +0 -0
  45. trueppm_api/apps/agents/management/commands/__init__.py +0 -0
  46. trueppm_api/apps/agents/management/commands/audit_prune.py +137 -0
  47. trueppm_api/apps/agents/management/commands/audit_verify.py +101 -0
  48. trueppm_api/apps/agents/middleware.py +44 -0
  49. trueppm_api/apps/agents/migrations/0001_initial.py +231 -0
  50. trueppm_api/apps/agents/migrations/0002_agentactioncheckpoint.py +71 -0
  51. trueppm_api/apps/agents/migrations/0003_agentactionrefusaldetail.py +58 -0
  52. trueppm_api/apps/agents/migrations/__init__.py +0 -0
  53. trueppm_api/apps/agents/models.py +371 -0
  54. trueppm_api/apps/agents/refusal.py +103 -0
  55. trueppm_api/apps/agents/serializers.py +85 -0
  56. trueppm_api/apps/agents/services.py +397 -0
  57. trueppm_api/apps/agents/signals.py +30 -0
  58. trueppm_api/apps/agents/urls.py +15 -0
  59. trueppm_api/apps/agents/views.py +108 -0
  60. trueppm_api/apps/csvimport/__init__.py +12 -0
  61. trueppm_api/apps/csvimport/apps.py +11 -0
  62. trueppm_api/apps/csvimport/mapping.py +363 -0
  63. trueppm_api/apps/csvimport/migrations/0001_initial.py +74 -0
  64. trueppm_api/apps/csvimport/migrations/0002_schedule_outline_batch_operations.py +37 -0
  65. trueppm_api/apps/csvimport/migrations/0003_csvimportrequest_date_order_and_more.py +26 -0
  66. trueppm_api/apps/csvimport/migrations/__init__.py +0 -0
  67. trueppm_api/apps/csvimport/models.py +111 -0
  68. trueppm_api/apps/csvimport/parser.py +1825 -0
  69. trueppm_api/apps/csvimport/services.py +48 -0
  70. trueppm_api/apps/csvimport/tasks.py +418 -0
  71. trueppm_api/apps/csvimport/template.py +37 -0
  72. trueppm_api/apps/csvimport/urls.py +50 -0
  73. trueppm_api/apps/csvimport/views.py +793 -0
  74. trueppm_api/apps/history/__init__.py +0 -0
  75. trueppm_api/apps/history/apps.py +12 -0
  76. trueppm_api/apps/history/changelog.py +359 -0
  77. trueppm_api/apps/history/diff_policy.py +177 -0
  78. trueppm_api/apps/history/serializers.py +104 -0
  79. trueppm_api/apps/history/signals.py +82 -0
  80. trueppm_api/apps/history/tasks.py +105 -0
  81. trueppm_api/apps/history/urls.py +38 -0
  82. trueppm_api/apps/history/views.py +443 -0
  83. trueppm_api/apps/idempotency/__init__.py +0 -0
  84. trueppm_api/apps/idempotency/apps.py +11 -0
  85. trueppm_api/apps/idempotency/migrations/0001_initial.py +71 -0
  86. trueppm_api/apps/idempotency/migrations/__init__.py +0 -0
  87. trueppm_api/apps/idempotency/mixins.py +226 -0
  88. trueppm_api/apps/idempotency/models.py +75 -0
  89. trueppm_api/apps/idempotency/tasks.py +61 -0
  90. trueppm_api/apps/integrations/__init__.py +13 -0
  91. trueppm_api/apps/integrations/apps.py +59 -0
  92. trueppm_api/apps/integrations/connections.py +806 -0
  93. trueppm_api/apps/integrations/encryption.py +92 -0
  94. trueppm_api/apps/integrations/external_sources.py +837 -0
  95. trueppm_api/apps/integrations/git_automation_services.py +231 -0
  96. trueppm_api/apps/integrations/git_webhook_auth.py +243 -0
  97. trueppm_api/apps/integrations/http.py +403 -0
  98. trueppm_api/apps/integrations/me_work.py +218 -0
  99. trueppm_api/apps/integrations/migrations/0001_initial.py +64 -0
  100. trueppm_api/apps/integrations/migrations/0001_squashed_0006_tasklink_description_tasklink_preview_type_and_more.py +187 -0
  101. trueppm_api/apps/integrations/migrations/0002_tasklink.py +67 -0
  102. trueppm_api/apps/integrations/migrations/0003_tasklink_tasklink_serverver_idx.py +17 -0
  103. trueppm_api/apps/integrations/migrations/0004_tasklink_custom_title_tasklink_labels.py +25 -0
  104. trueppm_api/apps/integrations/migrations/0005_boardautomation.py +56 -0
  105. trueppm_api/apps/integrations/migrations/0006_tasklink_description_tasklink_preview_type_and_more.py +40 -0
  106. trueppm_api/apps/integrations/migrations/0007_tasklink_created_at.py +23 -0
  107. trueppm_api/apps/integrations/migrations/0008_integrationcredential_config_externalworkitem.py +66 -0
  108. trueppm_api/apps/integrations/migrations/0009_externalsyncrequest_and_more.py +96 -0
  109. trueppm_api/apps/integrations/migrations/0010_externalworkitem_due_date.py +17 -0
  110. trueppm_api/apps/integrations/migrations/0011_tasklink_sync_seq_tasklink_tasklink_syncseq_idx.py +22 -0
  111. trueppm_api/apps/integrations/migrations/0012_boardautomation_last_delivery_at_and_more.py +42 -0
  112. trueppm_api/apps/integrations/migrations/0013_externalsyncrequest_attempt_count_and_more.py +26 -0
  113. trueppm_api/apps/integrations/migrations/__init__.py +0 -0
  114. trueppm_api/apps/integrations/models.py +622 -0
  115. trueppm_api/apps/integrations/notification_channels.py +57 -0
  116. trueppm_api/apps/integrations/opengraph.py +229 -0
  117. trueppm_api/apps/integrations/outgoing.py +201 -0
  118. trueppm_api/apps/integrations/providers.py +519 -0
  119. trueppm_api/apps/integrations/registry.py +345 -0
  120. trueppm_api/apps/integrations/serializers.py +453 -0
  121. trueppm_api/apps/integrations/services.py +171 -0
  122. trueppm_api/apps/integrations/tasks.py +731 -0
  123. trueppm_api/apps/integrations/throttles.py +165 -0
  124. trueppm_api/apps/integrations/urls.py +77 -0
  125. trueppm_api/apps/integrations/views.py +1106 -0
  126. trueppm_api/apps/jiraimport/__init__.py +8 -0
  127. trueppm_api/apps/jiraimport/apps.py +11 -0
  128. trueppm_api/apps/jiraimport/migrations/0001_initial.py +72 -0
  129. trueppm_api/apps/jiraimport/migrations/__init__.py +0 -0
  130. trueppm_api/apps/jiraimport/models.py +70 -0
  131. trueppm_api/apps/jiraimport/parser.py +350 -0
  132. trueppm_api/apps/jiraimport/services.py +46 -0
  133. trueppm_api/apps/jiraimport/tasks.py +277 -0
  134. trueppm_api/apps/jiraimport/urls.py +15 -0
  135. trueppm_api/apps/jiraimport/views.py +153 -0
  136. trueppm_api/apps/msproject/__init__.py +0 -0
  137. trueppm_api/apps/msproject/apps.py +11 -0
  138. trueppm_api/apps/msproject/dataclasses.py +153 -0
  139. trueppm_api/apps/msproject/exporter.py +500 -0
  140. trueppm_api/apps/msproject/extended_attributes.py +77 -0
  141. trueppm_api/apps/msproject/importer.py +1095 -0
  142. trueppm_api/apps/msproject/migrations/0001_import_request.py +77 -0
  143. trueppm_api/apps/msproject/migrations/0001_squashed_0002_importrequest_creates_project.py +80 -0
  144. trueppm_api/apps/msproject/migrations/0002_importrequest_creates_project.py +15 -0
  145. trueppm_api/apps/msproject/migrations/__init__.py +0 -0
  146. trueppm_api/apps/msproject/models.py +81 -0
  147. trueppm_api/apps/msproject/parser.py +1231 -0
  148. trueppm_api/apps/msproject/serializers.py +136 -0
  149. trueppm_api/apps/msproject/services.py +58 -0
  150. trueppm_api/apps/msproject/tasks.py +436 -0
  151. trueppm_api/apps/msproject/urls.py +39 -0
  152. trueppm_api/apps/msproject/views.py +531 -0
  153. trueppm_api/apps/notifications/__init__.py +7 -0
  154. trueppm_api/apps/notifications/apps.py +15 -0
  155. trueppm_api/apps/notifications/backfill.py +79 -0
  156. trueppm_api/apps/notifications/categories.py +112 -0
  157. trueppm_api/apps/notifications/delivery_limits.py +258 -0
  158. trueppm_api/apps/notifications/digests.py +447 -0
  159. trueppm_api/apps/notifications/email_backend.py +330 -0
  160. trueppm_api/apps/notifications/email_health.py +128 -0
  161. trueppm_api/apps/notifications/migrations/0001_initial.py +207 -0
  162. trueppm_api/apps/notifications/migrations/0001_squashed_0006_notification_task.py +294 -0
  163. trueppm_api/apps/notifications/migrations/0002_project_notification_preference.py +67 -0
  164. trueppm_api/apps/notifications/migrations/0003_projectnotificationpreference_paused.py +17 -0
  165. trueppm_api/apps/notifications/migrations/0004_clean_unknown_matrix_keys.py +30 -0
  166. trueppm_api/apps/notifications/migrations/0005_notification_body_notification_event_type_and_more.py +27 -0
  167. trueppm_api/apps/notifications/migrations/0006_notification_task.py +25 -0
  168. trueppm_api/apps/notifications/migrations/0007_workspaceemailsettings.py +80 -0
  169. trueppm_api/apps/notifications/migrations/0008_notification_snoozed_until.py +17 -0
  170. trueppm_api/apps/notifications/migrations/0009_usernotificationsettings.py +43 -0
  171. trueppm_api/apps/notifications/migrations/0010_projectnotificationpreference_schema_version.py +20 -0
  172. trueppm_api/apps/notifications/migrations/0011_usernotificationsettings_digest_hour_and_more.py +96 -0
  173. trueppm_api/apps/notifications/migrations/__init__.py +0 -0
  174. trueppm_api/apps/notifications/models.py +1197 -0
  175. trueppm_api/apps/notifications/receivers.py +155 -0
  176. trueppm_api/apps/notifications/schema_migrations.py +56 -0
  177. trueppm_api/apps/notifications/serializers.py +961 -0
  178. trueppm_api/apps/notifications/services.py +1451 -0
  179. trueppm_api/apps/notifications/tasks.py +711 -0
  180. trueppm_api/apps/notifications/throttles.py +98 -0
  181. trueppm_api/apps/notifications/urls.py +97 -0
  182. trueppm_api/apps/notifications/views.py +904 -0
  183. trueppm_api/apps/observability/__init__.py +0 -0
  184. trueppm_api/apps/observability/apps.py +31 -0
  185. trueppm_api/apps/observability/logging.py +213 -0
  186. trueppm_api/apps/observability/migrations/0001_initial.py +35 -0
  187. trueppm_api/apps/observability/migrations/0001_squashed_0003_alter_purgerun_trigger.py +154 -0
  188. trueppm_api/apps/observability/migrations/0002_purgerun_retentionpolicy_retentionschedule.py +131 -0
  189. trueppm_api/apps/observability/migrations/0003_alter_purgerun_trigger.py +21 -0
  190. trueppm_api/apps/observability/migrations/0004_alter_retentionpolicy_key.py +28 -0
  191. trueppm_api/apps/observability/migrations/__init__.py +0 -0
  192. trueppm_api/apps/observability/models.py +141 -0
  193. trueppm_api/apps/observability/otel/__init__.py +45 -0
  194. trueppm_api/apps/observability/otel/attributes.py +247 -0
  195. trueppm_api/apps/observability/otel/export_health.py +533 -0
  196. trueppm_api/apps/observability/otel/instrumentation.py +351 -0
  197. trueppm_api/apps/observability/otel/metrics.py +551 -0
  198. trueppm_api/apps/observability/otel/provider.py +511 -0
  199. trueppm_api/apps/observability/otel/request_attributes.py +204 -0
  200. trueppm_api/apps/observability/purge_registry.py +124 -0
  201. trueppm_api/apps/observability/retention.py +139 -0
  202. trueppm_api/apps/observability/selectors.py +969 -0
  203. trueppm_api/apps/observability/serializers.py +142 -0
  204. trueppm_api/apps/observability/services.py +407 -0
  205. trueppm_api/apps/observability/tasks.py +266 -0
  206. trueppm_api/apps/observability/urls.py +27 -0
  207. trueppm_api/apps/observability/views.py +523 -0
  208. trueppm_api/apps/profiles/__init__.py +0 -0
  209. trueppm_api/apps/profiles/apps.py +15 -0
  210. trueppm_api/apps/profiles/constants.py +54 -0
  211. trueppm_api/apps/profiles/migrations/0001_initial.py +55 -0
  212. trueppm_api/apps/profiles/migrations/0001_squashed_0004_userprofile_role_context.py +125 -0
  213. trueppm_api/apps/profiles/migrations/0002_userprofile_hidden_views.py +17 -0
  214. trueppm_api/apps/profiles/migrations/0003_projectvisit.py +63 -0
  215. trueppm_api/apps/profiles/migrations/0004_userprofile_role_context.py +26 -0
  216. trueppm_api/apps/profiles/migrations/0005_userprofile_schedule_in_deliver.py +20 -0
  217. trueppm_api/apps/profiles/migrations/0006_userprofile_date_format_userprofile_timezone.py +36 -0
  218. trueppm_api/apps/profiles/migrations/0007_userpin.py +91 -0
  219. trueppm_api/apps/profiles/migrations/0008_remove_userprofile_schedule_in_deliver.py +71 -0
  220. trueppm_api/apps/profiles/migrations/0009_auth_user_email_upper_idx.py +81 -0
  221. trueppm_api/apps/profiles/migrations/__init__.py +0 -0
  222. trueppm_api/apps/profiles/models.py +276 -0
  223. trueppm_api/apps/profiles/serializers.py +199 -0
  224. trueppm_api/apps/profiles/services.py +466 -0
  225. trueppm_api/apps/profiles/views.py +124 -0
  226. trueppm_api/apps/projects/__init__.py +0 -0
  227. trueppm_api/apps/projects/actual_date_rules.py +163 -0
  228. trueppm_api/apps/projects/amend.py +133 -0
  229. trueppm_api/apps/projects/apps.py +38 -0
  230. trueppm_api/apps/projects/asset_feed.py +459 -0
  231. trueppm_api/apps/projects/asset_views.py +317 -0
  232. trueppm_api/apps/projects/attachment_policy.py +278 -0
  233. trueppm_api/apps/projects/authentication.py +449 -0
  234. trueppm_api/apps/projects/backfill.py +287 -0
  235. trueppm_api/apps/projects/backlog_services.py +324 -0
  236. trueppm_api/apps/projects/backlog_views.py +302 -0
  237. trueppm_api/apps/projects/batch_operation_views.py +264 -0
  238. trueppm_api/apps/projects/blocker_services.py +510 -0
  239. trueppm_api/apps/projects/board_activity.py +462 -0
  240. trueppm_api/apps/projects/board_activity_views.py +186 -0
  241. trueppm_api/apps/projects/board_lanes.py +134 -0
  242. trueppm_api/apps/projects/bulk_settings.py +194 -0
  243. trueppm_api/apps/projects/bundled_templates.py +215 -0
  244. trueppm_api/apps/projects/calendar_settings.py +180 -0
  245. trueppm_api/apps/projects/ceremony_views.py +244 -0
  246. trueppm_api/apps/projects/commit_moment.py +204 -0
  247. trueppm_api/apps/projects/config_notice.py +1325 -0
  248. trueppm_api/apps/projects/custom_field_values.py +266 -0
  249. trueppm_api/apps/projects/decisions_services.py +93 -0
  250. trueppm_api/apps/projects/decisions_views.py +94 -0
  251. trueppm_api/apps/projects/estimation_scale.py +126 -0
  252. trueppm_api/apps/projects/export_bundle.py +353 -0
  253. trueppm_api/apps/projects/fixtures/seeds/atlas-platform-launch.json +4256 -0
  254. trueppm_api/apps/projects/fixtures/seeds/aurora-mobile-app.json +2000 -0
  255. trueppm_api/apps/projects/fixtures/seeds/bayside-civic-center.json +1825 -0
  256. trueppm_api/apps/projects/fixtures/seeds/ga-launch.json +1905 -0
  257. trueppm_api/apps/projects/fixtures/seeds/helios-crm-replacement.json +1409 -0
  258. trueppm_api/apps/projects/guardrail_policy_source.py +269 -0
  259. trueppm_api/apps/projects/inbound_sync.py +555 -0
  260. trueppm_api/apps/projects/iteration_label.py +85 -0
  261. trueppm_api/apps/projects/lifecycle.py +191 -0
  262. trueppm_api/apps/projects/management/__init__.py +0 -0
  263. trueppm_api/apps/projects/management/commands/__init__.py +0 -0
  264. trueppm_api/apps/projects/management/commands/backfill_in_progress_status.py +92 -0
  265. trueppm_api/apps/projects/management/commands/create_demo_share_link.py +368 -0
  266. trueppm_api/apps/projects/management/commands/export_program.py +50 -0
  267. trueppm_api/apps/projects/management/commands/import_seed.py +165 -0
  268. trueppm_api/apps/projects/management/commands/load_sample_project.py +247 -0
  269. trueppm_api/apps/projects/management/commands/seed_capacity.py +405 -0
  270. trueppm_api/apps/projects/management/commands/seed_integration_fixtures.py +178 -0
  271. trueppm_api/apps/projects/management/commands/shift_sample_dates.py +120 -0
  272. trueppm_api/apps/projects/mcp_settings.py +305 -0
  273. trueppm_api/apps/projects/methodology.py +178 -0
  274. trueppm_api/apps/projects/migrations/0001_initial.py +208 -0
  275. trueppm_api/apps/projects/migrations/0001_squashed_0094_project_decisions_policy.py +5595 -0
  276. trueppm_api/apps/projects/migrations/0002_alter_uuid_pk_serialize_false.py +57 -0
  277. trueppm_api/apps/projects/migrations/0003_rename_task_project_index.py +25 -0
  278. trueppm_api/apps/projects/migrations/0004_soft_delete_and_dependency_versioned.py +70 -0
  279. trueppm_api/apps/projects/migrations/0005_task_assignee.py +33 -0
  280. trueppm_api/apps/projects/migrations/0006_task_utilization_index.py +31 -0
  281. trueppm_api/apps/projects/migrations/0007_task_is_milestone.py +28 -0
  282. trueppm_api/apps/projects/migrations/0008_baseline.py +119 -0
  283. trueppm_api/apps/projects/migrations/0009_historicaldependency_historicalproject_and_more.py +210 -0
  284. trueppm_api/apps/projects/migrations/0010_risk.py +229 -0
  285. trueppm_api/apps/projects/migrations/0011_task_status.py +27 -0
  286. trueppm_api/apps/projects/migrations/0012_task_status.py +27 -0
  287. trueppm_api/apps/projects/migrations/0013_task_planned_start.py +24 -0
  288. trueppm_api/apps/projects/migrations/0014_short_hex_ids.py +74 -0
  289. trueppm_api/apps/projects/migrations/0015_backfill_short_ids.py +48 -0
  290. trueppm_api/apps/projects/migrations/0016_task_actual_dates.py +42 -0
  291. trueppm_api/apps/projects/migrations/0017_boardcolumnconfig.py +43 -0
  292. trueppm_api/apps/projects/migrations/0018_estimation_governance.py +62 -0
  293. trueppm_api/apps/projects/migrations/0019_backfill_wbs_paths.py +28 -0
  294. trueppm_api/apps/projects/migrations/0020_task_status_5col.py +65 -0
  295. trueppm_api/apps/projects/migrations/0021_boardsavedview.py +64 -0
  296. trueppm_api/apps/projects/migrations/0022_task_status_changed_at_priority_rank.py +35 -0
  297. trueppm_api/apps/projects/migrations/0023_risk_framework_fields.py +96 -0
  298. trueppm_api/apps/projects/migrations/0024_riskcomment.py +52 -0
  299. trueppm_api/apps/projects/migrations/0025_sprint.py +352 -0
  300. trueppm_api/apps/projects/migrations/0026_project_methodology.py +30 -0
  301. trueppm_api/apps/projects/migrations/0027_sprint_retro.py +89 -0
  302. trueppm_api/apps/projects/migrations/0028_normalize_notes_field.py +42 -0
  303. trueppm_api/apps/projects/migrations/0029_complete_implies_full_progress.py +38 -0
  304. trueppm_api/apps/projects/migrations/0030_review_implies_full_progress.py +37 -0
  305. trueppm_api/apps/projects/migrations/0031_task_remaining_points.py +22 -0
  306. trueppm_api/apps/projects/migrations/0032_task_is_subtask_and_sprint_scope_change.py +90 -0
  307. trueppm_api/apps/projects/migrations/0033_task_my_work_index.py +38 -0
  308. trueppm_api/apps/projects/migrations/0034_inbound_task_sync.py +313 -0
  309. trueppm_api/apps/projects/migrations/0035_retro_versioned_and_suggested_assignee.py +173 -0
  310. trueppm_api/apps/projects/migrations/0036_program_entity_and_membership.py +157 -0
  311. trueppm_api/apps/projects/migrations/0037_sprint_capacity_points.py +20 -0
  312. trueppm_api/apps/projects/migrations/0038_taskcomment_commentreaction_commentacknowledgement_and_more.py +233 -0
  313. trueppm_api/apps/projects/migrations/0039_apitoken_and_more.py +88 -0
  314. trueppm_api/apps/projects/migrations/0040_program_general_fields.py +119 -0
  315. trueppm_api/apps/projects/migrations/0041_ceremony_template_and_phase_gate_config.py +210 -0
  316. trueppm_api/apps/projects/migrations/0041_project_general_fields.py +106 -0
  317. trueppm_api/apps/projects/migrations/0042_merge_20260522_0410.py +12 -0
  318. trueppm_api/apps/projects/migrations/0042_program_rollup_config.py +95 -0
  319. trueppm_api/apps/projects/migrations/0042_workflow_color_and_custom_fields.py +94 -0
  320. trueppm_api/apps/projects/migrations/0043_merge_20260522_1118.py +10 -0
  321. trueppm_api/apps/projects/migrations/0044_merge_20260522_rollup.py +10 -0
  322. trueppm_api/apps/projects/migrations/0044_project_archive_program_close.py +119 -0
  323. trueppm_api/apps/projects/migrations/0045_program_risk_policy.py +78 -0
  324. trueppm_api/apps/projects/migrations/0046_merge_20260523_2248.py +12 -0
  325. trueppm_api/apps/projects/migrations/0047_apitokenauditentry_program_and_more.py +55 -0
  326. trueppm_api/apps/projects/migrations/0048_historicalprogram_color_program_color.py +32 -0
  327. trueppm_api/apps/projects/migrations/0049_backlog_item.py +112 -0
  328. trueppm_api/apps/projects/migrations/0050_backlog_item_trgm_search.py +26 -0
  329. trueppm_api/apps/projects/migrations/0051_alter_calendar_working_days_alter_dependency_lag_and_more.py +144 -0
  330. trueppm_api/apps/projects/migrations/0052_recurring_tasks.py +278 -0
  331. trueppm_api/apps/projects/migrations/0053_dependency_dep_pred_serverver_idx_and_more.py +56 -0
  332. trueppm_api/apps/projects/migrations/0054_sprintscopechange_goal_impact_and_more.py +117 -0
  333. trueppm_api/apps/projects/migrations/0055_historicaltask_sprint_pending_and_more.py +51 -0
  334. trueppm_api/apps/projects/migrations/0056_historicalproject_prioritization_model_and_more.py +276 -0
  335. trueppm_api/apps/projects/migrations/0057_historicalsprint_binding_committed_snapshot_and_more.py +58 -0
  336. trueppm_api/apps/projects/migrations/0058_historicaltask_delivery_mode_and_more.py +72 -0
  337. trueppm_api/apps/projects/migrations/0059_forecastsnapshot.py +80 -0
  338. trueppm_api/apps/projects/migrations/0060_historicalprojectsignalprivacypolicy_and_more.py +90 -0
  339. trueppm_api/apps/projects/migrations/0061_baselinetask_story_points.py +17 -0
  340. trueppm_api/apps/projects/migrations/0062_project_is_sample.py +22 -0
  341. trueppm_api/apps/projects/migrations/0063_historicalsprint_wip_limit_sprint_wip_limit.py +22 -0
  342. trueppm_api/apps/projects/migrations/0064_sprinttaskoutcome.py +97 -0
  343. trueppm_api/apps/projects/migrations/0065_historicalsprint_goal_outcome_sprint_goal_outcome.py +32 -0
  344. trueppm_api/apps/projects/migrations/0066_historicalproject_lead_project_lead.py +38 -0
  345. trueppm_api/apps/projects/migrations/0067_sprint_exclude_from_velocity.py +22 -0
  346. trueppm_api/apps/projects/migrations/0068_project_recalculated_at.py +23 -0
  347. trueppm_api/apps/projects/migrations/0069_iteration_label.py +22 -0
  348. trueppm_api/apps/projects/migrations/0070_historicalprogram_iteration_label_and_more.py +32 -0
  349. trueppm_api/apps/projects/migrations/0071_backfill_iteration_label_inherit.py +35 -0
  350. trueppm_api/apps/projects/migrations/0072_pulseresponse_retroboarditem.py +129 -0
  351. trueppm_api/apps/projects/migrations/0073_sprinttaskoutcome_demo_ready.py +17 -0
  352. trueppm_api/apps/projects/migrations/0074_historicaltask_blocked_reason_task_blocked_reason.py +30 -0
  353. trueppm_api/apps/projects/migrations/0075_risk_decimal_short_id.py +42 -0
  354. trueppm_api/apps/projects/migrations/0076_sprinttaskoutcome_review_polish.py +45 -0
  355. trueppm_api/apps/projects/migrations/0077_task_blocker_fields.py +111 -0
  356. trueppm_api/apps/projects/migrations/0078_alter_risktask_unique_together_and_more.py +22 -0
  357. trueppm_api/apps/projects/migrations/0079_historicalproject_status_date_project_status_date.py +22 -0
  358. trueppm_api/apps/projects/migrations/0080_alter_historicaltask_type_alter_task_type.py +46 -0
  359. trueppm_api/apps/projects/migrations/0081_historicalprogram_allow_guests_and_more.py +52 -0
  360. trueppm_api/apps/projects/migrations/0082_project_last_sync_version.py +90 -0
  361. trueppm_api/apps/projects/migrations/0083_historicalprogram_mc_history_attribution_audience_and_more.py +108 -0
  362. trueppm_api/apps/projects/migrations/0084_tasknote.py +71 -0
  363. trueppm_api/apps/projects/migrations/0085_sprint_ix_sprint_velocity.py +33 -0
  364. trueppm_api/apps/projects/migrations/0086_board_card_search_trgm.py +33 -0
  365. trueppm_api/apps/projects/migrations/0087_historicalprogram_task_duration_change_percent_policy_and_more.py +155 -0
  366. trueppm_api/apps/projects/migrations/0088_historicalprogram_allowed_attachment_types_and_more.py +61 -0
  367. trueppm_api/apps/projects/migrations/0089_signalceilingraiseproposal_signalceilingraisevote_and_more.py +157 -0
  368. trueppm_api/apps/projects/migrations/0090_historicaltask_proj_histdate_index.py +44 -0
  369. trueppm_api/apps/projects/migrations/0091_project_board_cadence.py +39 -0
  370. trueppm_api/apps/projects/migrations/0092_program_target_date.py +22 -0
  371. trueppm_api/apps/projects/migrations/0093_cross_project_dependency_consent.py +58 -0
  372. trueppm_api/apps/projects/migrations/0094_project_decisions_policy.py +90 -0
  373. trueppm_api/apps/projects/migrations/0095_poker_session_vote.py +127 -0
  374. trueppm_api/apps/projects/migrations/0095_squashed_0097_release_0_3.py +225 -0
  375. trueppm_api/apps/projects/migrations/0096_crossprojectslipconflict.py +91 -0
  376. trueppm_api/apps/projects/migrations/0097_backlogitem_backlogitem_tags_gin_and_more.py +32 -0
  377. trueppm_api/apps/projects/migrations/0098_historicalproject_show_baselines_and_more.py +52 -0
  378. trueppm_api/apps/projects/migrations/0099_apitoken_scopes.py +48 -0
  379. trueppm_api/apps/projects/migrations/0100_task_dep_serverver_idx_concurrent.py +61 -0
  380. trueppm_api/apps/projects/migrations/0101_dependency_deleted_at_task_deleted_at.py +22 -0
  381. trueppm_api/apps/projects/migrations/0102_project_deleted_at_project_proj_isdel_deletedat_idx.py +25 -0
  382. trueppm_api/apps/projects/migrations/0103_taskdurationchangeevent_task_dur_evt_sprint_idx.py +18 -0
  383. trueppm_api/apps/projects/migrations/0104_historicalproject_stale_task_threshold_days_and_more.py +32 -0
  384. trueppm_api/apps/projects/migrations/0104_trash_restore_1113.py +38 -0
  385. trueppm_api/apps/projects/migrations/0105_historical_changelog_indexes.py +62 -0
  386. trueppm_api/apps/projects/migrations/0106_boardsavedview_schema_version.py +20 -0
  387. trueppm_api/apps/projects/migrations/0107_task_activity_event.py +70 -0
  388. trueppm_api/apps/projects/migrations/0108_remove_apitoken_api_token_scope_xor_and_more.py +117 -0
  389. trueppm_api/apps/projects/migrations/0109_projectexportjob.py +82 -0
  390. trueppm_api/apps/projects/migrations/0110_sharelink.py +123 -0
  391. trueppm_api/apps/projects/migrations/0111_projectcalendarlayer.py +67 -0
  392. trueppm_api/apps/projects/migrations/0112_sharelink_expires_at_alter_sharelink_content_kind.py +31 -0
  393. trueppm_api/apps/projects/migrations/0113_alter_historicaltask_percent_complete_and_more.py +35 -0
  394. trueppm_api/apps/projects/migrations/0114_historicalproject_default_member_role_and_more.py +28 -0
  395. trueppm_api/apps/projects/migrations/0115_historicalproject_end_date_shift_threshold_days_and_more.py +22 -0
  396. trueppm_api/apps/projects/migrations/0116_alter_taskactivityevent_event_type.py +28 -0
  397. trueppm_api/apps/projects/migrations/0117_label_tasklabel_label_tasks_and_more.py +126 -0
  398. trueppm_api/apps/projects/migrations/0118_programexportjob.py +82 -0
  399. trueppm_api/apps/projects/migrations/0119_historicalprogram_calendar_program_calendar.py +36 -0
  400. trueppm_api/apps/projects/migrations/0120_alter_backlogitem_item_type.py +29 -0
  401. trueppm_api/apps/projects/migrations/0121_task_three_point_estimate_ordered.py +64 -0
  402. trueppm_api/apps/projects/migrations/0122_task_relation.py +173 -0
  403. trueppm_api/apps/projects/migrations/0123_remove_historicalproject_agile_features_and_more.py +20 -0
  404. trueppm_api/apps/projects/migrations/0124_dependency_is_driving.py +17 -0
  405. trueppm_api/apps/projects/migrations/0125_historicalprogram_estimation_scale_and_more.py +68 -0
  406. trueppm_api/apps/projects/migrations/0126_projectcustomfield_show_on_card_taskcustomfieldvalue.py +80 -0
  407. trueppm_api/apps/projects/migrations/0127_historicalprogram_mcp_enabled_and_more.py +32 -0
  408. trueppm_api/apps/projects/migrations/0128_acceptancecriterion_sync_seq_apitoken_sync_seq_and_more.py +192 -0
  409. trueppm_api/apps/projects/migrations/0129_sharelink_show_milestone_dates.py +20 -0
  410. trueppm_api/apps/projects/migrations/0130_programimportjob.py +85 -0
  411. trueppm_api/apps/projects/migrations/0131_historicalprogram_sprint_picker_ready_only_default_and_more.py +32 -0
  412. trueppm_api/apps/projects/migrations/0132_task_scheduled_start.py +17 -0
  413. trueppm_api/apps/projects/migrations/0133_project_status_date_floor_armed_at.py +17 -0
  414. trueppm_api/apps/projects/migrations/0134_task_edited_at_task_seeded_at_task_source_id_and_more.py +65 -0
  415. trueppm_api/apps/projects/migrations/0135_projecttemplate_templateapplication_and_more.py +175 -0
  416. trueppm_api/apps/projects/migrations/0136_schedule_outline_batch_operations.py +118 -0
  417. trueppm_api/apps/projects/migrations/0137_collapse_dual_scope_api_tokens.py +54 -0
  418. trueppm_api/apps/projects/migrations/0138_apitokenauditentry_api_token_audit_owner_idx.py +18 -0
  419. trueppm_api/apps/projects/migrations/0139_historicaltask_duration_unit_task_duration_unit.py +32 -0
  420. trueppm_api/apps/projects/migrations/0140_historicaltask_auto_container_and_more.py +113 -0
  421. trueppm_api/apps/projects/migrations/0141_historicalproject_draft_started_at_and_more.py +44 -0
  422. trueppm_api/apps/projects/migrations/0142_baseline_calendar_hours_per_day_and_more.py +31 -0
  423. trueppm_api/apps/projects/migrations/0143_sprintcloserequest_failure_reason_and_more.py +42 -0
  424. trueppm_api/apps/projects/migrations/0144_projecttemplate_source_project_and_more.py +35 -0
  425. trueppm_api/apps/projects/migrations/0145_seed_bundled_templates.py +65 -0
  426. trueppm_api/apps/projects/migrations/0146_historicaltask_board_lane_task_board_lane.py +32 -0
  427. trueppm_api/apps/projects/migrations/0147_structuraloperation.py +128 -0
  428. trueppm_api/apps/projects/migrations/0148_task_unique_task_wbs_path_per_project_live.py +76 -0
  429. trueppm_api/apps/projects/migrations/0149_drop_workshops_tables.py +42 -0
  430. trueppm_api/apps/projects/migrations/0150_clear_uncommitted_cpm_output.py +130 -0
  431. trueppm_api/apps/projects/migrations/0151_config_notice_request.py +70 -0
  432. trueppm_api/apps/projects/migrations/0152_aggregate_task_wbs_name_idx.py +20 -0
  433. trueppm_api/apps/projects/migrations/0153_program_sample_anchor_date.py +22 -0
  434. trueppm_api/apps/projects/migrations/__init__.py +0 -0
  435. trueppm_api/apps/projects/models.py +8946 -0
  436. trueppm_api/apps/projects/poker_services.py +154 -0
  437. trueppm_api/apps/projects/poker_views.py +398 -0
  438. trueppm_api/apps/projects/product_backlog_services.py +450 -0
  439. trueppm_api/apps/projects/program_label_services.py +94 -0
  440. trueppm_api/apps/projects/program_label_views.py +189 -0
  441. trueppm_api/apps/projects/program_rollup.py +575 -0
  442. trueppm_api/apps/projects/program_schedule.py +745 -0
  443. trueppm_api/apps/projects/program_views.py +3220 -0
  444. trueppm_api/apps/projects/project_templates.py +422 -0
  445. trueppm_api/apps/projects/receivers.py +234 -0
  446. trueppm_api/apps/projects/refusal_codes.py +140 -0
  447. trueppm_api/apps/projects/reorder_services.py +145 -0
  448. trueppm_api/apps/projects/restructure_hooks.py +54 -0
  449. trueppm_api/apps/projects/retro_board_services.py +368 -0
  450. trueppm_api/apps/projects/retro_services.py +285 -0
  451. trueppm_api/apps/projects/risk_import.py +396 -0
  452. trueppm_api/apps/projects/row_identity.py +113 -0
  453. trueppm_api/apps/projects/schema_migrations.py +228 -0
  454. trueppm_api/apps/projects/schemas/seed_v1.json +493 -0
  455. trueppm_api/apps/projects/schemas/seed_v2.json +892 -0
  456. trueppm_api/apps/projects/seed/__init__.py +61 -0
  457. trueppm_api/apps/projects/seed/exporter.py +1644 -0
  458. trueppm_api/apps/projects/seed/forecast_backfill.py +247 -0
  459. trueppm_api/apps/projects/seed/importer.py +2390 -0
  460. trueppm_api/apps/projects/seed/reanchor.py +551 -0
  461. trueppm_api/apps/projects/seed/reldates.py +126 -0
  462. trueppm_api/apps/projects/seed/replace.py +126 -0
  463. trueppm_api/apps/projects/seed/replay.py +1691 -0
  464. trueppm_api/apps/projects/seed/replay_ctx.py +41 -0
  465. trueppm_api/apps/projects/seed/samples.py +427 -0
  466. trueppm_api/apps/projects/seed/validation.py +1149 -0
  467. trueppm_api/apps/projects/serializers.py +12310 -0
  468. trueppm_api/apps/projects/services.py +6966 -0
  469. trueppm_api/apps/projects/share_serializers.py +132 -0
  470. trueppm_api/apps/projects/share_services.py +325 -0
  471. trueppm_api/apps/projects/share_views.py +374 -0
  472. trueppm_api/apps/projects/sharing_settings.py +187 -0
  473. trueppm_api/apps/projects/signal_privacy_services.py +909 -0
  474. trueppm_api/apps/projects/signal_privacy_views.py +476 -0
  475. trueppm_api/apps/projects/signals.py +132 -0
  476. trueppm_api/apps/projects/slip_conflict.py +266 -0
  477. trueppm_api/apps/projects/sprint_cadence.py +453 -0
  478. trueppm_api/apps/projects/sprint_picker_settings.py +132 -0
  479. trueppm_api/apps/projects/standup.py +304 -0
  480. trueppm_api/apps/projects/standup_views.py +99 -0
  481. trueppm_api/apps/projects/structural_operation_services.py +727 -0
  482. trueppm_api/apps/projects/structural_operation_views.py +311 -0
  483. trueppm_api/apps/projects/surface_visibility.py +126 -0
  484. trueppm_api/apps/projects/task_batch_services.py +379 -0
  485. trueppm_api/apps/projects/task_bulk.py +1152 -0
  486. trueppm_api/apps/projects/task_classification.py +561 -0
  487. trueppm_api/apps/projects/task_classification_defaults.py +95 -0
  488. trueppm_api/apps/projects/task_duration_settings.py +142 -0
  489. trueppm_api/apps/projects/task_grouping.py +754 -0
  490. trueppm_api/apps/projects/tasks.py +1917 -0
  491. trueppm_api/apps/projects/template_divergence.py +168 -0
  492. trueppm_api/apps/projects/template_services.py +160 -0
  493. trueppm_api/apps/projects/template_tasks.py +258 -0
  494. trueppm_api/apps/projects/template_views.py +799 -0
  495. trueppm_api/apps/projects/throttles.py +311 -0
  496. trueppm_api/apps/projects/urls.py +1011 -0
  497. trueppm_api/apps/projects/utilization.py +885 -0
  498. trueppm_api/apps/projects/views.py +20572 -0
  499. trueppm_api/apps/projects/wbs_paths.py +119 -0
  500. trueppm_api/apps/resources/__init__.py +0 -0
  501. trueppm_api/apps/resources/apps.py +8 -0
  502. trueppm_api/apps/resources/capacity.py +121 -0
  503. trueppm_api/apps/resources/migrations/0001_initial.py +68 -0
  504. trueppm_api/apps/resources/migrations/0001_squashed_0013_alter_projectresource_unique_together_and_more.py +281 -0
  505. trueppm_api/apps/resources/migrations/0002_alter_uuid_pk_serialize_false.py +36 -0
  506. trueppm_api/apps/resources/migrations/0003_resource_soft_delete.py +30 -0
  507. trueppm_api/apps/resources/migrations/0004_add_taskresource_resource_index.py +25 -0
  508. trueppm_api/apps/resources/migrations/0005_resource_job_role.py +20 -0
  509. trueppm_api/apps/resources/migrations/0006_skill.py +34 -0
  510. trueppm_api/apps/resources/migrations/0007_resource_skill.py +63 -0
  511. trueppm_api/apps/resources/migrations/0008_project_resource.py +63 -0
  512. trueppm_api/apps/resources/migrations/0009_task_skill_requirement.py +60 -0
  513. trueppm_api/apps/resources/migrations/0010_alter_resourceskill_options_and_more.py +20 -0
  514. trueppm_api/apps/resources/migrations/0011_alter_projectresource_notes.py +17 -0
  515. trueppm_api/apps/resources/migrations/0012_add_resource_user_fk.py +26 -0
  516. trueppm_api/apps/resources/migrations/0013_alter_projectresource_unique_together_and_more.py +53 -0
  517. trueppm_api/apps/resources/migrations/0014_projectresource_sync_seq_resource_sync_seq_and_more.py +37 -0
  518. trueppm_api/apps/resources/migrations/0015_projectresource_deactivated_with_resource.py +17 -0
  519. trueppm_api/apps/resources/migrations/__init__.py +0 -0
  520. trueppm_api/apps/resources/models.py +298 -0
  521. trueppm_api/apps/resources/serializers.py +426 -0
  522. trueppm_api/apps/resources/services.py +465 -0
  523. trueppm_api/apps/resources/urls.py +28 -0
  524. trueppm_api/apps/resources/views.py +1749 -0
  525. trueppm_api/apps/scheduling/__init__.py +0 -0
  526. trueppm_api/apps/scheduling/apps.py +153 -0
  527. trueppm_api/apps/scheduling/calendars.py +119 -0
  528. trueppm_api/apps/scheduling/deadletter.py +91 -0
  529. trueppm_api/apps/scheduling/forecast_history_settings.py +215 -0
  530. trueppm_api/apps/scheduling/forecast_staleness.py +313 -0
  531. trueppm_api/apps/scheduling/graph_guard.py +263 -0
  532. trueppm_api/apps/scheduling/management/__init__.py +0 -0
  533. trueppm_api/apps/scheduling/management/commands/__init__.py +0 -0
  534. trueppm_api/apps/scheduling/management/commands/prune_forecast_snapshots.py +53 -0
  535. trueppm_api/apps/scheduling/migrations/0001_failed_task.py +62 -0
  536. trueppm_api/apps/scheduling/migrations/0001_squashed_0007_projectforecastsnapshot.py +309 -0
  537. trueppm_api/apps/scheduling/migrations/0002_schedulerequest.py +78 -0
  538. trueppm_api/apps/scheduling/migrations/0003_add_schedule_request_reason.py +27 -0
  539. trueppm_api/apps/scheduling/migrations/0004_velocity_suggestion.py +94 -0
  540. trueppm_api/apps/scheduling/migrations/0005_montecarlorun.py +61 -0
  541. trueppm_api/apps/scheduling/migrations/0006_montecarlorun_distribution.py +17 -0
  542. trueppm_api/apps/scheduling/migrations/0007_projectforecastsnapshot.py +65 -0
  543. trueppm_api/apps/scheduling/migrations/0008_alter_schedulerequest_reason.py +28 -0
  544. trueppm_api/apps/scheduling/migrations/0008_folded_schedulerequest_reason.py +34 -0
  545. trueppm_api/apps/scheduling/migrations/0009_alter_schedulerequest_reason.py +29 -0
  546. trueppm_api/apps/scheduling/migrations/0010_failedtask_resolution_note_failedtask_resolved_at_and_more.py +43 -0
  547. trueppm_api/apps/scheduling/migrations/0011_failedtask_project.py +26 -0
  548. trueppm_api/apps/scheduling/migrations/0012_montecarlorun_diagnostic.py +17 -0
  549. trueppm_api/apps/scheduling/migrations/0013_montecarlorun_status_date.py +17 -0
  550. trueppm_api/apps/scheduling/migrations/0014_montecarlorun_plan_version.py +17 -0
  551. trueppm_api/apps/scheduling/migrations/__init__.py +0 -0
  552. trueppm_api/apps/scheduling/models.py +516 -0
  553. trueppm_api/apps/scheduling/receivers.py +160 -0
  554. trueppm_api/apps/scheduling/risk_premium.py +283 -0
  555. trueppm_api/apps/scheduling/serializers.py +564 -0
  556. trueppm_api/apps/scheduling/services.py +1182 -0
  557. trueppm_api/apps/scheduling/signals.py +56 -0
  558. trueppm_api/apps/scheduling/tasks.py +1984 -0
  559. trueppm_api/apps/scheduling/telemetry.py +80 -0
  560. trueppm_api/apps/scheduling/units.py +35 -0
  561. trueppm_api/apps/scheduling/urls.py +57 -0
  562. trueppm_api/apps/scheduling/views.py +2564 -0
  563. trueppm_api/apps/sso/__init__.py +0 -0
  564. trueppm_api/apps/sso/apps.py +19 -0
  565. trueppm_api/apps/sso/extensions.py +130 -0
  566. trueppm_api/apps/sso/management/__init__.py +0 -0
  567. trueppm_api/apps/sso/management/commands/__init__.py +0 -0
  568. trueppm_api/apps/sso/management/commands/seed_sso_keycloak.py +172 -0
  569. trueppm_api/apps/sso/migrations/0001_initial.py +119 -0
  570. trueppm_api/apps/sso/migrations/0002_remove_oidcprovider_workspace_ssoproviderpolicy_and_more.py +169 -0
  571. trueppm_api/apps/sso/migrations/__init__.py +0 -0
  572. trueppm_api/apps/sso/models.py +148 -0
  573. trueppm_api/apps/sso/serializers.py +437 -0
  574. trueppm_api/apps/sso/services.py +1385 -0
  575. trueppm_api/apps/sso/urls.py +47 -0
  576. trueppm_api/apps/sso/views.py +935 -0
  577. trueppm_api/apps/sync/__init__.py +0 -0
  578. trueppm_api/apps/sync/apps.py +15 -0
  579. trueppm_api/apps/sync/backfill.py +208 -0
  580. trueppm_api/apps/sync/broadcast.py +320 -0
  581. trueppm_api/apps/sync/conflict.py +262 -0
  582. trueppm_api/apps/sync/consumers.py +471 -0
  583. trueppm_api/apps/sync/migrations/0001_initial.py +59 -0
  584. trueppm_api/apps/sync/migrations/0001_squashed_0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +77 -0
  585. trueppm_api/apps/sync/migrations/0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +41 -0
  586. trueppm_api/apps/sync/migrations/0003_boardevent.py +46 -0
  587. trueppm_api/apps/sync/migrations/0004_seed_sync_seq.py +24 -0
  588. trueppm_api/apps/sync/migrations/0005_program_sync_sequence.py +35 -0
  589. trueppm_api/apps/sync/migrations/__init__.py +0 -0
  590. trueppm_api/apps/sync/models.py +225 -0
  591. trueppm_api/apps/sync/pagination.py +231 -0
  592. trueppm_api/apps/sync/sequence.py +371 -0
  593. trueppm_api/apps/sync/serializers.py +687 -0
  594. trueppm_api/apps/sync/tasks.py +260 -0
  595. trueppm_api/apps/sync/throttles.py +175 -0
  596. trueppm_api/apps/sync/upload.py +501 -0
  597. trueppm_api/apps/sync/urls.py +17 -0
  598. trueppm_api/apps/sync/views.py +930 -0
  599. trueppm_api/apps/sync/ws_auth.py +193 -0
  600. trueppm_api/apps/taskruns/__init__.py +0 -0
  601. trueppm_api/apps/taskruns/apps.py +11 -0
  602. trueppm_api/apps/taskruns/migrations/0001_initial.py +92 -0
  603. trueppm_api/apps/taskruns/migrations/__init__.py +0 -0
  604. trueppm_api/apps/taskruns/models.py +68 -0
  605. trueppm_api/apps/taskruns/serializers.py +92 -0
  606. trueppm_api/apps/taskruns/tasks.py +60 -0
  607. trueppm_api/apps/taskruns/tracker.py +286 -0
  608. trueppm_api/apps/taskruns/urls.py +46 -0
  609. trueppm_api/apps/taskruns/views.py +195 -0
  610. trueppm_api/apps/teams/__init__.py +8 -0
  611. trueppm_api/apps/teams/apps.py +16 -0
  612. trueppm_api/apps/teams/migrations/0001_initial.py +139 -0
  613. trueppm_api/apps/teams/migrations/0001_squashed_0002_default_teams.py +142 -0
  614. trueppm_api/apps/teams/migrations/0002_default_teams.py +62 -0
  615. trueppm_api/apps/teams/migrations/0003_team_sync_seq_teammembership_sync_seq.py +22 -0
  616. trueppm_api/apps/teams/migrations/__init__.py +0 -0
  617. trueppm_api/apps/teams/models.py +145 -0
  618. trueppm_api/apps/teams/permissions.py +149 -0
  619. trueppm_api/apps/teams/serializers.py +95 -0
  620. trueppm_api/apps/teams/services.py +434 -0
  621. trueppm_api/apps/teams/signals.py +61 -0
  622. trueppm_api/apps/teams/urls.py +34 -0
  623. trueppm_api/apps/teams/views.py +201 -0
  624. trueppm_api/apps/timetracking/__init__.py +0 -0
  625. trueppm_api/apps/timetracking/apps.py +9 -0
  626. trueppm_api/apps/timetracking/migrations/0001_initial.py +117 -0
  627. trueppm_api/apps/timetracking/migrations/0002_timesheetsubmission.py +46 -0
  628. trueppm_api/apps/timetracking/migrations/0003_timeentry_deleted_at_timeentry_deleted_by.py +31 -0
  629. trueppm_api/apps/timetracking/migrations/0004_timeentry_sync_seq_and_more.py +24 -0
  630. trueppm_api/apps/timetracking/migrations/__init__.py +0 -0
  631. trueppm_api/apps/timetracking/models.py +178 -0
  632. trueppm_api/apps/timetracking/serializers.py +175 -0
  633. trueppm_api/apps/timetracking/services.py +117 -0
  634. trueppm_api/apps/timetracking/urls.py +47 -0
  635. trueppm_api/apps/timetracking/views.py +526 -0
  636. trueppm_api/apps/webhooks/__init__.py +0 -0
  637. trueppm_api/apps/webhooks/apps.py +8 -0
  638. trueppm_api/apps/webhooks/backfill.py +90 -0
  639. trueppm_api/apps/webhooks/dispatch.py +144 -0
  640. trueppm_api/apps/webhooks/migrations/0001_initial.py +146 -0
  641. trueppm_api/apps/webhooks/migrations/0001_squashed_0007_sprint_lifecycle_events.py +243 -0
  642. trueppm_api/apps/webhooks/migrations/0002_alter_webhook_events.py +32 -0
  643. trueppm_api/apps/webhooks/migrations/0003_delivery_status_created_idx.py +17 -0
  644. trueppm_api/apps/webhooks/migrations/0004_webhook_program_alter_webhook_project_and_more.py +64 -0
  645. trueppm_api/apps/webhooks/migrations/0005_webhook_delivery_sequence_numbers.py +30 -0
  646. trueppm_api/apps/webhooks/migrations/0006_webhook_format_alter_webhook_events_and_more.py +61 -0
  647. trueppm_api/apps/webhooks/migrations/0007_sprint_lifecycle_events.py +63 -0
  648. trueppm_api/apps/webhooks/migrations/0008_risk_baseline_comment_events.py +73 -0
  649. trueppm_api/apps/webhooks/migrations/0009_encrypt_webhook_secret_and_failure_counters.py +90 -0
  650. trueppm_api/apps/webhooks/migrations/__init__.py +0 -0
  651. trueppm_api/apps/webhooks/models.py +372 -0
  652. trueppm_api/apps/webhooks/serializers.py +318 -0
  653. trueppm_api/apps/webhooks/tasks.py +663 -0
  654. trueppm_api/apps/webhooks/urls.py +22 -0
  655. trueppm_api/apps/webhooks/views.py +383 -0
  656. trueppm_api/apps/workflow_engine/__init__.py +0 -0
  657. trueppm_api/apps/workflow_engine/apps.py +23 -0
  658. trueppm_api/apps/workflow_engine/migrations/0001_initial.py +230 -0
  659. trueppm_api/apps/workflow_engine/migrations/0001_squashed_0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +234 -0
  660. trueppm_api/apps/workflow_engine/migrations/0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +16 -0
  661. trueppm_api/apps/workflow_engine/migrations/0003_workflowoutboxrow_workflow_outbox_recovery_idx.py +21 -0
  662. trueppm_api/apps/workflow_engine/migrations/__init__.py +0 -0
  663. trueppm_api/apps/workflow_engine/models.py +265 -0
  664. trueppm_api/apps/workflow_engine/tasks.py +368 -0
  665. trueppm_api/apps/workspace/__init__.py +0 -0
  666. trueppm_api/apps/workspace/apps.py +10 -0
  667. trueppm_api/apps/workspace/backfill.py +111 -0
  668. trueppm_api/apps/workspace/export.py +242 -0
  669. trueppm_api/apps/workspace/migrations/0001_initial.py +326 -0
  670. trueppm_api/apps/workspace/migrations/0001_squashed_0014_workspacemembership_availability_effective_from_and_more.py +829 -0
  671. trueppm_api/apps/workspace/migrations/0002_remove_workspace_fiscal_year_start_and_more.py +85 -0
  672. trueppm_api/apps/workspace/migrations/0003_workspaceexportjob.py +73 -0
  673. trueppm_api/apps/workspace/migrations/0004_alter_workspaceinvite_status.py +27 -0
  674. trueppm_api/apps/workspace/migrations/0005_workspace_iteration_label_and_more.py +26 -0
  675. trueppm_api/apps/workspace/migrations/0006_alter_groupmembership_unique_together_and_more.py +45 -0
  676. trueppm_api/apps/workspace/migrations/0007_workspace_public_sharing_override_policy.py +21 -0
  677. trueppm_api/apps/workspace/migrations/0008_workspace_mc_history_attribution_audience_and_more.py +44 -0
  678. trueppm_api/apps/workspace/migrations/0009_workspace_methodology_and_more.py +186 -0
  679. trueppm_api/apps/workspace/migrations/0010_workspace_logo.py +38 -0
  680. trueppm_api/apps/workspace/migrations/0011_historicalworkspace_task_duration_change_percent_override_policy_and_more.py +56 -0
  681. trueppm_api/apps/workspace/migrations/0012_historicalworkspace_allowed_attachment_types_and_more.py +64 -0
  682. trueppm_api/apps/workspace/migrations/0013_auditevent.py +70 -0
  683. trueppm_api/apps/workspace/migrations/0014_workspacemembership_availability_effective_from_and_more.py +39 -0
  684. trueppm_api/apps/workspace/migrations/0015_trash_restore_1113.py +34 -0
  685. trueppm_api/apps/workspace/migrations/0016_historicalworkspace_calendar_and_more.py +55 -0
  686. trueppm_api/apps/workspace/migrations/0017_historicalworkspace_estimation_scale_and_more.py +38 -0
  687. trueppm_api/apps/workspace/migrations/0018_historicalworkspace_feedback_enabled_and_more.py +32 -0
  688. trueppm_api/apps/workspace/migrations/0019_historicalworkspace_mcp_enabled_and_more.py +22 -0
  689. trueppm_api/apps/workspace/migrations/0020_viewer_ordinal_one.py +34 -0
  690. trueppm_api/apps/workspace/migrations/0021_group_sync_seq_groupmembership_sync_seq_and_more.py +27 -0
  691. trueppm_api/apps/workspace/migrations/0022_historicalworkspace_sprint_picker_ready_only_default_and_more.py +22 -0
  692. trueppm_api/apps/workspace/migrations/0023_alter_auditevent_event_type.py +32 -0
  693. trueppm_api/apps/workspace/migrations/0024_alter_auditevent_event_type.py +33 -0
  694. trueppm_api/apps/workspace/migrations/0025_alter_auditevent_event_type.py +36 -0
  695. trueppm_api/apps/workspace/migrations/0026_alter_auditevent_event_type.py +37 -0
  696. trueppm_api/apps/workspace/migrations/0027_alter_auditevent_event_type.py +42 -0
  697. trueppm_api/apps/workspace/migrations/__init__.py +0 -0
  698. trueppm_api/apps/workspace/models.py +857 -0
  699. trueppm_api/apps/workspace/permissions.py +187 -0
  700. trueppm_api/apps/workspace/serializers.py +590 -0
  701. trueppm_api/apps/workspace/services.py +919 -0
  702. trueppm_api/apps/workspace/signals.py +37 -0
  703. trueppm_api/apps/workspace/tasks.py +555 -0
  704. trueppm_api/apps/workspace/urls.py +113 -0
  705. trueppm_api/apps/workspace/views.py +1502 -0
  706. trueppm_api/asgi.py +42 -0
  707. trueppm_api/celery.py +31 -0
  708. trueppm_api/core/__init__.py +0 -0
  709. trueppm_api/core/admin_site.py +206 -0
  710. trueppm_api/core/auth_views.py +916 -0
  711. trueppm_api/core/constant_time.py +51 -0
  712. trueppm_api/core/csp.py +54 -0
  713. trueppm_api/core/db.py +87 -0
  714. trueppm_api/core/db_session.py +37 -0
  715. trueppm_api/core/exception_handlers.py +157 -0
  716. trueppm_api/core/export_downloads.py +56 -0
  717. trueppm_api/core/extension_providers.py +56 -0
  718. trueppm_api/core/extension_signals.py +147 -0
  719. trueppm_api/core/idempotent.py +260 -0
  720. trueppm_api/core/metadata.py +42 -0
  721. trueppm_api/core/middleware.py +51 -0
  722. trueppm_api/core/openapi.py +949 -0
  723. trueppm_api/core/password_reset.py +500 -0
  724. trueppm_api/core/protect_conflict.py +100 -0
  725. trueppm_api/core/ratelimit.py +148 -0
  726. trueppm_api/core/redis_throttle.py +82 -0
  727. trueppm_api/core/refresh_cookie_policy.py +156 -0
  728. trueppm_api/core/request_body.py +86 -0
  729. trueppm_api/core/security_checks.py +884 -0
  730. trueppm_api/core/storage_config.py +105 -0
  731. trueppm_api/core/text_decode.py +168 -0
  732. trueppm_api/core/throttling.py +344 -0
  733. trueppm_api/core/valkey.py +214 -0
  734. trueppm_api/core/valkey_cache.py +66 -0
  735. trueppm_api/core/valkey_checks.py +104 -0
  736. trueppm_api/core/valkey_config.py +39 -0
  737. trueppm_api/core/worker_broker_wait.py +149 -0
  738. trueppm_api/core/worker_heartbeat.py +134 -0
  739. trueppm_api/fields.py +36 -0
  740. trueppm_api/permissions.py +30 -0
  741. trueppm_api/py.typed +0 -0
  742. trueppm_api/routing.py +11 -0
  743. trueppm_api/settings/__init__.py +0 -0
  744. trueppm_api/settings/base.py +2455 -0
  745. trueppm_api/settings/dev.py +273 -0
  746. trueppm_api/settings/prod.py +228 -0
  747. trueppm_api/urls.py +153 -0
  748. trueppm_api/workflows/__init__.py +38 -0
  749. trueppm_api/workflows/backends/__init__.py +6 -0
  750. trueppm_api/workflows/backends/default.py +297 -0
  751. trueppm_api/workflows/consumers/__init__.py +11 -0
  752. trueppm_api/workflows/consumers/requeue_failed_task.py +65 -0
  753. trueppm_api/workflows/interface.py +148 -0
  754. trueppm_api/workflows/registry.py +106 -0
  755. trueppm_api/workflows/services.py +90 -0
  756. trueppm_api/wsgi.py +11 -0
  757. trueppm_api-0.4.0b2.dist-info/METADATA +70 -0
  758. trueppm_api-0.4.0b2.dist-info/RECORD +759 -0
  759. trueppm_api-0.4.0b2.dist-info/WHEEL +4 -0
@@ -0,0 +1,2564 @@
1
+ """Views for the scheduling app."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import uuid
8
+ from datetime import date as _date
9
+ from datetime import datetime as _datetime
10
+ from datetime import timedelta
11
+ from typing import Any, cast
12
+
13
+ from django.conf import settings
14
+ from django.core.cache import cache
15
+ from django.db import models, transaction
16
+ from django.shortcuts import get_object_or_404
17
+ from django.utils import timezone
18
+ from django.utils.dateparse import parse_date, parse_datetime
19
+ from drf_spectacular.types import OpenApiTypes
20
+ from drf_spectacular.utils import (
21
+ OpenApiExample,
22
+ OpenApiParameter,
23
+ OpenApiResponse,
24
+ extend_schema,
25
+ extend_schema_view,
26
+ inline_serializer,
27
+ )
28
+ from rest_framework import serializers, status
29
+ from rest_framework import serializers as drf_serializers
30
+ from rest_framework.decorators import action, api_view, permission_classes, throttle_classes
31
+ from rest_framework.generics import ListAPIView
32
+ from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
33
+ from rest_framework.pagination import PageNumberPagination
34
+ from rest_framework.permissions import IsAdminUser, IsAuthenticated
35
+ from rest_framework.request import Request
36
+ from rest_framework.response import Response
37
+ from rest_framework.throttling import ScopedRateThrottle, SimpleRateThrottle
38
+ from rest_framework.views import APIView
39
+ from rest_framework.viewsets import GenericViewSet
40
+
41
+ from trueppm_api.apps.access.permissions import (
42
+ IsProjectAdmin,
43
+ IsProjectMember,
44
+ IsProjectNotArchived,
45
+ IsProjectScheduler,
46
+ McpReadableViewMixin,
47
+ McpScope,
48
+ assert_project_not_archived,
49
+ declare_scope_in_body,
50
+ )
51
+ from trueppm_api.apps.idempotency.mixins import IdempotencyMixin
52
+ from trueppm_api.apps.projects.models import (
53
+ Dependency,
54
+ EstimationMode,
55
+ Project,
56
+ Task,
57
+ three_point_estimates_ordered,
58
+ )
59
+ from trueppm_api.apps.scheduling.calendars import compose_project_calendar
60
+ from trueppm_api.apps.scheduling.forecast_staleness import (
61
+ forecast_staleness_facts,
62
+ forecast_staleness_for_payload,
63
+ forecast_staleness_from_run,
64
+ )
65
+ from trueppm_api.apps.scheduling.models import (
66
+ FailedTask,
67
+ FailedTaskStatus,
68
+ MonteCarloRun,
69
+ ProjectForecastSnapshot,
70
+ ScheduleRequestReason,
71
+ VelocitySuggestion,
72
+ )
73
+ from trueppm_api.apps.scheduling.risk_premium import (
74
+ build_risk_premium,
75
+ delta_vs_cpm_days,
76
+ risk_premium_for_forecast_payload,
77
+ risk_premium_from_values,
78
+ )
79
+ from trueppm_api.apps.scheduling.serializers import (
80
+ FailedTaskDropSerializer,
81
+ FailedTaskRequeueSerializer,
82
+ FailedTaskSerializer,
83
+ MonteCarloForecastSerializer,
84
+ MonteCarloRunSerializer,
85
+ MonteCarloWhatIfRequestSerializer,
86
+ MonteCarloWhatIfResponseSerializer,
87
+ ProjectForecastSnapshotSerializer,
88
+ VelocitySuggestionSerializer,
89
+ )
90
+ from trueppm_api.apps.scheduling.services import (
91
+ build_sched_graph,
92
+ build_sched_tasks,
93
+ enqueue_recalculate,
94
+ forecast_diagnostic,
95
+ record_monte_carlo_run,
96
+ resolve_cpm_status_date,
97
+ )
98
+ from trueppm_api.apps.scheduling.telemetry import monte_carlo_span
99
+ from trueppm_api.workflows.consumers.requeue_failed_task import WORKFLOW_NAME as REQUEUE_WORKFLOW
100
+ from trueppm_api.workflows.services import start_workflow
101
+
102
+ logger = logging.getLogger(__name__)
103
+
104
+ # Version token in the Monte Carlo read-cache key. Bump it in the same commit as
105
+ # any engine change that moves the percentiles for an unchanged project.
106
+ #
107
+ # The entry lives for 24 hours (ADR-0144, #1231) and nothing else invalidates it —
108
+ # not a task edit, not a deploy, since the cache declares no KEY_PREFIX/VERSION and
109
+ # the key carried only the project pk. So an engine correctness fix would keep
110
+ # serving its own pre-fix numbers to `GET /monte-carlo/latest/`, to the MCP
111
+ # forecast tool, and to the derivation ("why") endpoint for a full day after
112
+ # rollout, from a payload with no signal that it is stale. Bumping the token
113
+ # retires the old keyspace at deploy instead (#2833).
114
+ #
115
+ # This does NOT reach the persisted `MonteCarloRun` fallback that serves once the
116
+ # TTL expires: those rows carry no engine-version column, so a project whose last
117
+ # run predates a fix and is never re-run keeps reporting the old answer.
118
+ MC_LATEST_CACHE_VERSION = 2
119
+
120
+
121
+ def mc_latest_cache_key(pk: object) -> str:
122
+ """Read-cache key for a project's latest Monte Carlo forecast.
123
+
124
+ One definition for the write, both reads, and the tests. Three duplicated
125
+ f-strings is how a version bump gets applied to two of them.
126
+ """
127
+ return f"mc_latest:v{MC_LATEST_CACHE_VERSION}:{pk}"
128
+
129
+
130
+ def _current_plan_state(pk: uuid.UUID | str) -> tuple[int | None, _datetime | None]:
131
+ """The project's live plan version and last CPM recalc time (#3140).
132
+
133
+ Both terms the staleness discriminant compares a run against, in one narrow
134
+ ``values_list`` rather than loading the row: callers that already hold the project
135
+ read the two attributes directly, and this exists for the ones that do not.
136
+
137
+ ``(None, None)`` when the row is gone (a concurrent hard delete), which classifies
138
+ the forecast as ``unknown`` rather than inventing a comparison — see
139
+ :func:`~.forecast_staleness.classify_forecast_staleness`.
140
+ """
141
+ # `is_deleted=False` matches every sibling project fetch in this module. It changes
142
+ # nothing for the current caller, which already resolved the project through a
143
+ # filtered fetch — it stops the helper failing open on soft-delete for the next one.
144
+ row = (
145
+ Project.objects.filter(pk=pk, is_deleted=False)
146
+ .values_list("last_sync_version", "recalculated_at")
147
+ .first()
148
+ )
149
+ return row if row is not None else (None, None)
150
+
151
+
152
+ # Upper bound on how many parked tasks a single bulk requeue/drop touches, so a
153
+ # "drop all" / "requeue all" over a large filtered set cannot unbounded-load the
154
+ # DB or storm the broker (ADR-0210 §4). Oldest-first slice, with a ``capped`` flag
155
+ # in the response so the operator knows to repeat.
156
+ #
157
+ # Read straight off settings, not through `getattr(..., 500)`: the fallback made the
158
+ # knob look tunable while no settings module bound it, so the docs' claim that
159
+ # operators could raise it was false and the 500 always won (#2880). The binding now
160
+ # lives in settings/base.py (env: TRUEPPM_FAILED_TASK_BULK_ACTION_MAX) and a missing
161
+ # one is an AttributeError at import — loud, and impossible to ship silently.
162
+ FAILED_TASK_BULK_ACTION_MAX: int = settings.FAILED_TASK_BULK_ACTION_MAX
163
+
164
+ # Statuses an operator can act on: a task that is already dismissed or retried is
165
+ # terminal and is skipped by bulk actions / rejected by single actions.
166
+ _ACTIONABLE_FAILED_STATUSES = (FailedTaskStatus.DEAD, FailedTaskStatus.PENDING_RETRY)
167
+
168
+ # Shared user-facing response details.
169
+ _NOT_FOUND_DETAIL = "Not found."
170
+ _DATE_RANGE_EXCEEDED_DETAIL = "Project schedule exceeds the representable date range."
171
+
172
+
173
+ @extend_schema(
174
+ summary="Trigger a CPM recalculation for a project",
175
+ request=None,
176
+ responses={
177
+ 202: OpenApiResponse(
178
+ response=inline_serializer(
179
+ name="ScheduleTriggerResult",
180
+ fields={"queued": serializers.BooleanField()},
181
+ ),
182
+ description='Recalculation queued via the outbox; body is {"queued": true}.',
183
+ ),
184
+ 403: OpenApiResponse(
185
+ description=(
186
+ "Caller lacks the Resource Manager role on the project, or the project "
187
+ "is archived (archived plans are read-only, and a recalculation rewrites "
188
+ "every task's dates). Both causes answer the same status — branch on "
189
+ "`detail`, not on 403 alone."
190
+ )
191
+ ),
192
+ 404: OpenApiResponse(description="Project not found."),
193
+ },
194
+ )
195
+ @declare_scope_in_body(
196
+ "@api_view function: the generated WrappedAPIView carries no project_url_kwarg, so "
197
+ "has_permission cannot scope this POST. The gate is the explicit "
198
+ "IsProjectScheduler().has_object_permission(request, None, project) call in the body."
199
+ )
200
+ @api_view(["POST"])
201
+ @permission_classes([IsAuthenticated, IsProjectScheduler, IsProjectNotArchived])
202
+ def trigger_schedule(request: Request, pk: str) -> Response:
203
+ """Manually trigger a CPM recalculation for a project.
204
+
205
+ Requires the requesting user to hold at least the Resource Manager role on the
206
+ project. The request is written to the transactional outbox and dispatched
207
+ immediately if the broker is available; otherwise the Beat drain task picks
208
+ it up within 30 seconds.
209
+
210
+ Returns 404 if the project does not exist.
211
+ """
212
+ try:
213
+ project = Project.objects.get(pk=pk)
214
+ except Project.DoesNotExist:
215
+ return Response({"detail": _NOT_FOUND_DETAIL}, status=status.HTTP_404_NOT_FOUND)
216
+
217
+ # Permission check against the project object.
218
+ if not IsProjectScheduler().has_object_permission(request, None, project): # type: ignore[arg-type]
219
+ return Response({"detail": "Permission denied."}, status=status.HTTP_403_FORBIDDEN)
220
+
221
+ # ...and the archived check, in the body for the same reason the membership check
222
+ # is (#3414). `IsProjectNotArchived` IS declared above, but this is an `@api_view`
223
+ # function: the generated `WrappedAPIView` carries no `project_url_kwarg`, the route
224
+ # spells the project `pk`, so `_project_pk_from_view` returns None and
225
+ # `has_permission` returns True — and DRF never calls `has_object_permission` on a
226
+ # function view. The declaration read as the gate while a manual recalculation ran
227
+ # happily against an archived plan, rewriting every task's dates.
228
+ assert_project_not_archived(project.pk)
229
+
230
+ # Defer until any outer transaction commits so the ScheduleRequest row is
231
+ # never visible to the drain before its parent write lands.
232
+ project_id = str(project.pk)
233
+ transaction.on_commit(
234
+ lambda: enqueue_recalculate(project_id, reason=ScheduleRequestReason.MANUAL)
235
+ )
236
+ return Response({"queued": True}, status=status.HTTP_202_ACCEPTED)
237
+
238
+
239
+ # The premium derivation moved to `risk_premium` when the metric was promoted off
240
+ # this payload onto the project (#2483). Aliased rather than reimplemented so the
241
+ # forecast panel and the Overview card can never disagree about the same gap.
242
+ _delta_vs_cpm_days = delta_vs_cpm_days
243
+
244
+
245
+ def _date_delta_days(later: _date | None, earlier: _date | None) -> int | None:
246
+ """Signed calendar-day delta ``later - earlier``, or ``None`` if either is missing.
247
+
248
+ Positive means ``later`` lands after ``earlier`` (the forecast slipped). Shared
249
+ by the what-if and history endpoints so a run-to-run / current-to-whatif delta is
250
+ computed one way.
251
+ """
252
+ if later is None or earlier is None:
253
+ return None
254
+ return (later - earlier).days
255
+
256
+
257
+ def _confidence_curve(histogram: list[dict[str, object]], total: int) -> list[dict[str, object]]:
258
+ """Cumulative P(finish ≤ date) S-curve derived from the histogram buckets.
259
+
260
+ ``histogram`` is the already-binned ``[{date, count}]`` list in ascending date
261
+ order; ``total`` is the number of simulated runs. Returns one ``{date, pct}``
262
+ point per bucket carrying the cumulative share of runs that finished on or
263
+ before that bucket — the same value ``MonteCarloDetailPanel`` previously
264
+ accumulated in the browser (#987). Bounded to the bucket count (≤30 points).
265
+ """
266
+ if total <= 0:
267
+ return []
268
+ cumulative = 0
269
+ curve: list[dict[str, object]] = []
270
+ for bucket in histogram:
271
+ cumulative += cast(int, bucket["count"])
272
+ curve.append({"date": bucket["date"], "pct": round(cumulative / total * 100, 1)})
273
+ return curve
274
+
275
+
276
+ def _distribution_for_persist(payload: dict[str, Any]) -> dict[str, Any]:
277
+ """Shrink the distribution payload to fit MC_DISTRIBUTION_MAX_BYTES for storage (#1231).
278
+
279
+ Takes the ``{histogram_buckets, confidence_curve, sensitivity}`` slice of the
280
+ full result and, if its serialized size exceeds the cap, down-samples the
281
+ histogram (keeps every Nth bucket, always retaining the first and last so the
282
+ spread endpoints survive) until it fits. The confidence curve is recomputed
283
+ from the thinned buckets so the two stay consistent; sensitivity is left intact
284
+ (it is bounded by the task count, not the bucket count).
285
+
286
+ Returns a NEW dict — the caller's full ``result_dict`` (and the cache copy it
287
+ feeds) is never mutated, so the live view still serves the full-resolution
288
+ histogram while the persisted row is bounded against a pathological run.
289
+ """
290
+ dist = {
291
+ "histogram_buckets": payload.get("histogram_buckets", []),
292
+ "confidence_curve": payload.get("confidence_curve", []),
293
+ "sensitivity": payload.get("sensitivity", []),
294
+ }
295
+ cap = settings.MC_DISTRIBUTION_MAX_BYTES
296
+ if len(json.dumps(dist).encode()) <= cap:
297
+ return dist
298
+
299
+ buckets: list[dict[str, object]] = list(dist["histogram_buckets"])
300
+ total = sum(cast(int, b.get("count", 0)) for b in buckets)
301
+ # Increase the stride until the serialized payload fits. Always keep the first
302
+ # and last bucket so the distribution's min/max dates are preserved.
303
+ stride = 2
304
+ while len(json.dumps(dist).encode()) > cap and stride <= max(len(buckets), 2):
305
+ thinned = [b for i, b in enumerate(buckets) if i % stride == 0]
306
+ if buckets and buckets[-1] not in thinned:
307
+ thinned.append(buckets[-1])
308
+ dist = {
309
+ "histogram_buckets": thinned,
310
+ "confidence_curve": _confidence_curve(thinned, total),
311
+ "sensitivity": dist["sensitivity"],
312
+ }
313
+ stride += 1
314
+ return dist
315
+
316
+
317
+ def _build_sched_deps(project_pk: str, included_ids: set[str]) -> list[Any]:
318
+ """Convert a project's DB dependencies to scheduler ``Dependency`` inputs.
319
+
320
+ Drops any edge whose predecessor or successor is absent from ``included_ids``:
321
+ cross-project dependencies and edges to non-committed (BACKLOG) tasks both dangle
322
+ and would make the engine reject the network as referencing an unknown task.
323
+ Mirrors the CPM guard in scheduling.tasks (ADR-0090) — a single-project run
324
+ simulates only this project's committed tasks.
325
+
326
+ Reads through ``Dependency.live``: a soft-deleted edge is a constraint the
327
+ user removed, and forecasting against it reports a finish the plan no longer
328
+ implies (#3532).
329
+ """
330
+ from trueppm_scheduler.models import Dependency as SchedDependency
331
+ from trueppm_scheduler.models import DependencyType
332
+
333
+ db_deps = list(
334
+ Dependency.live.filter(predecessor__project_id=project_pk).select_related(
335
+ "predecessor", "successor"
336
+ )
337
+ )
338
+ return [
339
+ SchedDependency(
340
+ predecessor_id=str(d.predecessor_id),
341
+ successor_id=str(d.successor_id),
342
+ dep_type=DependencyType(d.dep_type),
343
+ lag=timedelta(days=d.lag),
344
+ )
345
+ for d in db_deps
346
+ if str(d.predecessor_id) in included_ids and str(d.successor_id) in included_ids
347
+ ]
348
+
349
+
350
+ def _mc_histogram(dist: list[_date]) -> list[dict[str, object]]:
351
+ """Bin a Monte Carlo finish-date distribution into ≤30 ascending ``{date, count}``
352
+ buckets.
353
+
354
+ ``dist`` is the engine's sorted finish-date sample (earliest first). Returns an
355
+ empty list for an empty distribution. The midpoint date of each bucket is used as
356
+ its label so the histogram is symmetric around the sampled span.
357
+ """
358
+ if not dist:
359
+ return []
360
+ min_ord = dist[0].toordinal()
361
+ max_ord = dist[-1].toordinal()
362
+ span = max(max_ord - min_ord, 1)
363
+ n_buckets = min(30, len(dist))
364
+ bucket_size = span / n_buckets
365
+ bucket_counts: dict[int, int] = {}
366
+ for d in dist:
367
+ idx = min(int((d.toordinal() - min_ord) / bucket_size), n_buckets - 1)
368
+ bucket_counts[idx] = bucket_counts.get(idx, 0) + 1
369
+ return [
370
+ {
371
+ "date": _date.fromordinal(min_ord + int((i + 0.5) * bucket_size)).isoformat(),
372
+ "count": bucket_counts.get(i, 0),
373
+ }
374
+ for i in range(n_buckets)
375
+ ]
376
+
377
+
378
+ def _persist_mc_run_if_authorized(
379
+ request: Request,
380
+ project: Project,
381
+ *,
382
+ mc_result: Any,
383
+ n_simulations: int,
384
+ cpm_finish: _date | None,
385
+ task_count: int,
386
+ result_dict: dict[str, Any],
387
+ status_date: _date | None,
388
+ plan_version: int | None,
389
+ ) -> None:
390
+ """Persist an author-attributed ``MonteCarloRun`` drift row for Scheduler+ callers.
391
+
392
+ The forecast *read* is intentionally open to any project member (a Viewer may pull
393
+ the band), but the persisted run is a different act: it attributes drift to its
394
+ author and grows the retained-run set (#1502). Gating the read at Member and the
395
+ write at Scheduler stops a Viewer/Member from spamming ``run_monte_carlo`` to
396
+ inflate history and pollute drift attribution over a schedule they cannot own. The
397
+ ``mc_latest`` cache is a per-project read cache, not per-user history, so it stays
398
+ refreshed for every caller — only the attributed row is gated here.
399
+
400
+ Best-effort: a write failure inside the service is logged and swallowed by
401
+ ``record_monte_carlo_run``; ``result_dict`` gains ``run_id`` only when persistence
402
+ succeeded. Mutates ``result_dict`` in place.
403
+ """
404
+ from trueppm_api.apps.access.models import Role
405
+ from trueppm_api.apps.access.permissions import _membership_role
406
+
407
+ # Pass project.pk (canonical UUID), not the raw URL string, so this reuses the
408
+ # per-request role cache the earlier object-permission check already warmed under
409
+ # the same key — no second membership query.
410
+ role = _membership_role(request, project.pk)
411
+ if role is None or role < Role.SCHEDULER:
412
+ return
413
+
414
+ # Persist the same distribution slice the cache holds, but bounded to
415
+ # MC_DISTRIBUTION_MAX_BYTES via down-sampling (#1231) — the cache copy is
416
+ # full-resolution and untouched. Stored so the histogram + tornado survive cache
417
+ # expiry and a past run stays viewable.
418
+ distribution = _distribution_for_persist(result_dict)
419
+ run = record_monte_carlo_run(
420
+ str(project.pk),
421
+ p50=mc_result.p50,
422
+ p80=mc_result.p80,
423
+ p95=mc_result.p95,
424
+ n_simulations=n_simulations,
425
+ cpm_finish=cpm_finish,
426
+ task_count=task_count,
427
+ user=request.user,
428
+ distribution=distribution,
429
+ # Store the reason the run is (or is not) flat alongside it, so a later
430
+ # read from history can still tell "no estimates anywhere" apart from
431
+ # "estimates exist, variance is low" — the distinction the added-time
432
+ # metric is built on (#2483).
433
+ diagnostic=result_dict.get("forecast_diagnostic"),
434
+ # The data date actually fed to the engine for this run (ADR-0132's
435
+ # never-recorded substitution, #2638) — same value already echoed on
436
+ # result_dict below, so the persisted row and the response agree.
437
+ status_date=status_date,
438
+ # The plan version the run was computed against (#3140) — the same value
439
+ # already on result_dict, so the persisted row and the cache entry give the
440
+ # same answer once the TTL expires and the read falls back to history.
441
+ plan_version=plan_version,
442
+ )
443
+ if run is not None:
444
+ result_dict["run_id"] = str(run.id)
445
+
446
+
447
+ class MonteCarloRunThrottle(ScopedRateThrottle):
448
+ """Caps synchronous Monte Carlo runs per member (#1552) to bound DoS.
449
+
450
+ ``run_monte_carlo`` executes an expensive simulation inline in the request
451
+ cycle, gated only by project membership. Scoped per-user via ``monte_carlo``
452
+ (10/min) so no single account can loop the endpoint to exhaust CPU, while a
453
+ human tuning estimates and re-running the forecast stays well under the cap.
454
+
455
+ ``ScopedRateThrottle`` normally reads its scope from ``view.throttle_scope``,
456
+ but ``run_monte_carlo`` is a function-based ``@api_view`` that cannot carry
457
+ that attribute, so the scope is bound from this class instead. The cache key
458
+ is still per-user + scope (``get_cache_key`` is inherited unchanged).
459
+ """
460
+
461
+ scope = "monte_carlo"
462
+
463
+ def allow_request(self, request: Request, view: APIView) -> bool:
464
+ # Bind the fixed scope from the class rather than off the view (an
465
+ # @api_view FBV has no throttle_scope), then run the grandparent's
466
+ # sliding-window check directly. We deliberately skip
467
+ # ScopedRateThrottle.allow_request (it re-reads view.throttle_scope,
468
+ # absent on the FBV) by calling SimpleRateThrottle explicitly instead of
469
+ # via super() — same resolution, but honest about the intentional skip
470
+ # and it doesn't trip CodeQL's "super() first arg" reliability rule.
471
+ self.rate = self.get_rate()
472
+ self.num_requests, self.duration = self.parse_rate(self.rate)
473
+ return SimpleRateThrottle.allow_request(self, request, view)
474
+
475
+
476
+ @extend_schema(
477
+ request=OpenApiTypes.OBJECT,
478
+ responses={
479
+ 200: OpenApiResponse(
480
+ response=MonteCarloForecastSerializer,
481
+ description=(
482
+ "Monte Carlo simulation result. Includes the engine result fields "
483
+ "(P50/P80/P95 finish dates, mean, std dev, etc.) plus "
484
+ "cpm_finish (deterministic CPM project finish, ISO 8601 or null), "
485
+ "delta_vs_cpm ({p50,p80,p95} signed calendar-day premium vs CPM), "
486
+ "confidence_curve ([{date, pct}] cumulative finish-by-date S-curve), "
487
+ "histogram_buckets ([{date, count}]), sensitivity ([{task_id, index}] "
488
+ "duration tornado — tasks that move the finish most, index 0..1, "
489
+ "ADR-0140), forecast_diagnostic ({deterministic, reason, tasks_total, "
490
+ "tasks_with_variance, tasks_pending_approval, agile_tasks_without_velocity, "
491
+ "tasks_estimates_below_plan} "
492
+ "— explains a flat forecast; reason is null when a real band exists), "
493
+ "last_run_at (ISO 8601), status_date (the data date this run was "
494
+ "actually computed against — project.status_date or today when unset, "
495
+ "ADR-0132/#2638), and the risk_premium_* family (ADR-0698): "
496
+ "risk_premium_state (not_run|unmeasurable|stale|zero|premium|negative — "
497
+ "the discriminant every client renders from, never null), "
498
+ "risk_premium_days, risk_premium_ratio, risk_premium_band (always null "
499
+ "until #2299), risk_premium_as_of, risk_premium_reason, "
500
+ "risk_premium_cpm_finish, risk_premium_p80. Derived at response time, "
501
+ "never cached, so the ratio never describes a remaining duration that "
502
+ "has since elapsed. Plus the forecast-staleness family (#3140): "
503
+ "forecast_staleness (current|project_changed|aged|unknown — the "
504
+ "discriminant every client renders from, never null; only `current` "
505
+ "means the forecast still describes the plan, and clients keep the "
506
+ "recompute action reachable on the other three), plan_version (the "
507
+ "project's sync version this run was computed against; null for runs "
508
+ "recorded before #3140, which classify as `unknown`, never `current`), "
509
+ "and plan_version_current (that version as of this response). "
510
+ "`project_changed` is deliberately not named `plan_changed`: the "
511
+ "underlying counter advances on ANY write in the project, so a "
512
+ "description or label edit raises it without moving a date. It is a "
513
+ "sound trigger for offering a recompute and NOT evidence that a "
514
+ "schedule value changed — do not narrate it as one."
515
+ ),
516
+ ),
517
+ 400: OpenApiResponse(
518
+ response=OpenApiTypes.OBJECT,
519
+ description="Cyclic dependency, invalid input, or out-of-range project span.",
520
+ ),
521
+ 402: OpenApiResponse(
522
+ response=OpenApiTypes.OBJECT,
523
+ description=(
524
+ "OSS simulation cap exceeded (n_simulations above MC_SIMULATION_CAP "
525
+ "or too many tasks)."
526
+ ),
527
+ examples=[
528
+ OpenApiExample(
529
+ "simulation_cap_exceeded",
530
+ value={
531
+ "error": "simulation_cap_exceeded",
532
+ "tier": "team",
533
+ "message": "Simulation count exceeds the community-edition cap.",
534
+ },
535
+ ),
536
+ ],
537
+ ),
538
+ 403: OpenApiResponse(
539
+ response=OpenApiTypes.OBJECT,
540
+ description=(
541
+ "Caller is not a member of the project, or the project is archived — a "
542
+ "run refreshes the project's forecast cache and, for Scheduler+, "
543
+ "appends a drift-history row, so it is a write."
544
+ ),
545
+ ),
546
+ 404: OpenApiResponse(
547
+ response=OpenApiTypes.OBJECT,
548
+ description="Project does not exist.",
549
+ ),
550
+ },
551
+ )
552
+ @declare_scope_in_body(
553
+ "@api_view function: the generated WrappedAPIView carries no project_url_kwarg, so "
554
+ "has_permission cannot scope this POST. The gate is the explicit "
555
+ "IsProjectMember().has_object_permission(request, None, project) call in the body."
556
+ )
557
+ @api_view(["POST"])
558
+ @permission_classes([IsAuthenticated, IsProjectMember, IsProjectNotArchived])
559
+ @throttle_classes([MonteCarloRunThrottle])
560
+ def run_monte_carlo(request: Request, pk: str) -> Response:
561
+ """Run a Monte Carlo probabilistic schedule simulation synchronously.
562
+
563
+ Monte Carlo is fast (< 100 ms vectorised) so this runs in the request/
564
+ response cycle rather than via Celery; the result is returned directly. The
565
+ per-project ``mc_latest`` read cache is refreshed for every caller, but a
566
+ persisted, author-attributed drift-history row (MonteCarloRun) is written
567
+ only for Scheduler+ — the forecast read is Member-level, its record is not
568
+ (#1502). Requests are rate-limited per user via the ``monte_carlo`` scope.
569
+
570
+ Synchronous-by-design decision (#1203): keeping this inline is only safe
571
+ because *every* multiplicative cost factor the run depends on is now bounded
572
+ by the engine — tasks (MC_TASK_CAP), simulation runs (MC_SIMULATION_CAP),
573
+ raw dependency edges (MAX_DEPENDENCIES), expanded edges (MAX_EXPANDED_EDGES),
574
+ the distinct-lag delta arrays (MAX_LAG_DELTA_CELLS), and the velocity horizon
575
+ (MAX_VELOCITY_SPRINTS) — and #1201 vectorised the previously O(edges x span)
576
+ per-edge lag precompute. With the input space bounded and the hot path
577
+ vectorised, the worst-case wall time stays within the request budget, so
578
+ moving to a Celery job (extra latency, result polling, a new failure surface)
579
+ would add cost without removing a real risk. A project that breaches the edge
580
+ cap is rejected as InvalidScheduleInput (a ValueError) and surfaces below as a
581
+ clean 400 rather than a stalled worker.
582
+
583
+ That argument depends on cap *order*, which #3527 had to preserve deliberately.
584
+ Summary expansion moved onto this path, and it walks the edge list — so it now
585
+ runs behind ``build_sched_graph``'s own O(1) ``MAX_DEPENDENCIES`` length check
586
+ rather than waiting for ``_validate_project``, which the engine does not reach
587
+ until ``monte_carlo()`` is already called. Without that, the expensive per-edge
588
+ step would run ahead of the cheap guard that is supposed to bound it.
589
+
590
+ Request body (all optional):
591
+ n_simulations (int): Number of simulation runs. Defaults to
592
+ settings.MC_SIMULATION_CAP. Must not exceed the cap.
593
+
594
+ Returns 200 on success, 402 if the OSS simulation cap is exceeded,
595
+ 400 if the schedule input is invalid (e.g. the dependency-edge cap is
596
+ breached), 404 if the project does not exist, 403 if the caller lacks
597
+ read access.
598
+ """
599
+ from trueppm_scheduler.engine import CyclicDependencyError, SimulationCapExceeded, monte_carlo
600
+ from trueppm_scheduler.models import Project as SchedProject
601
+
602
+ try:
603
+ project = (
604
+ Project.objects.select_related("calendar", "program__calendar")
605
+ # calendar__exceptions + calendar_layers__calendar__exceptions:
606
+ # compose_project_calendar reads the base calendar's exceptions (#1491)
607
+ # AND every applied overlay's (#906); prefetch both to avoid an N+1.
608
+ .prefetch_related(
609
+ "tasks",
610
+ "calendar__exceptions",
611
+ "calendar_layers__calendar__exceptions",
612
+ # ADR-0441: the resolver reads the program calendar's exceptions when a
613
+ # project inherits its base calendar from the program.
614
+ "program__calendar__exceptions",
615
+ )
616
+ .get(pk=pk, is_deleted=False)
617
+ )
618
+ except Project.DoesNotExist:
619
+ return Response({"detail": _NOT_FOUND_DETAIL}, status=status.HTTP_404_NOT_FOUND)
620
+
621
+ if not IsProjectMember().has_object_permission(request, None, project): # type: ignore[arg-type]
622
+ return Response({"detail": "Permission denied."}, status=status.HTTP_403_FORBIDDEN)
623
+
624
+ # Same #3414 shape as `trigger_schedule`: the declared `IsProjectNotArchived` cannot
625
+ # fire on an `@api_view` function whose route spells the project `pk`. A run is not a
626
+ # pure read — it refreshes the project's `mc_latest` cache and, for Scheduler+,
627
+ # appends an author-attributed `MonteCarloRun` row, so an archived plan's forecast
628
+ # history could be extended indefinitely after it was frozen.
629
+ assert_project_not_archived(project.pk)
630
+
631
+ cap: int | None = settings.MC_SIMULATION_CAP
632
+ # A JSON `null` (or absent) body parses to request.data == None; the body is
633
+ # documented as fully optional, so fall back to the default rather than
634
+ # letting None.get(...) raise AttributeError → 500 (#2310).
635
+ body = request.data if isinstance(request.data, dict) else {}
636
+ raw_n = body.get("n_simulations", cap or 1_000)
637
+ try:
638
+ n_simulations: int = int(raw_n)
639
+ except (TypeError, ValueError):
640
+ return Response(
641
+ {"detail": "n_simulations must be an integer."},
642
+ status=status.HTTP_400_BAD_REQUEST,
643
+ )
644
+ if n_simulations < 1:
645
+ return Response(
646
+ {"detail": "n_simulations must be a positive integer."},
647
+ status=status.HTTP_400_BAD_REQUEST,
648
+ )
649
+
650
+ # The plan version this run is about to be computed against (#3140) — the
651
+ # project's ADR-0686 sync sequence, already on the instance loaded above, so
652
+ # this costs nothing. Read HERE, before the committed task set is loaded
653
+ # below, and the ordering is the correctness property: a write that lands
654
+ # between this line and the query leaves the run recorded against the older
655
+ # version and therefore reading stale. Capturing it afterwards would claim
656
+ # the run covered a write it never saw — false-fresh, the one direction that
657
+ # loses the user the Rerun action.
658
+ plan_version = project.last_sync_version
659
+
660
+ # Shared converter (#1491): includes the calendar's CalendarException
661
+ # holiday/shutdown ranges, which the previous inline construction dropped —
662
+ # so Monte Carlo silently scheduled straight through configured holidays.
663
+ sched_calendar = compose_project_calendar(project)
664
+
665
+ # Monte Carlo simulates committed delivery only — BACKLOG cards are not
666
+ # part of the forecast. ADR-0057 / Task.committed.
667
+ # select_related("sprint"): build_sched_tasks reads sprint.start_date for the
668
+ # ADR-0168 sprint-window floor; load it with the task to avoid an N+1.
669
+ db_tasks = list(Task.committed.filter(project=project).select_related("sprint"))
670
+
671
+ # Shared converter (ADR-0132): the deterministic CPM pass and Monte Carlo
672
+ # build their scheduler input through one function, so a field can never reach
673
+ # one engine and not the other — the drift that caused #1185 (MC had silently
674
+ # dropped planned_start). build_sched_tasks honors the planned_start floor for
675
+ # every task (the #1185 fix, now centralized) and withholds pending three-point
676
+ # estimates in SUGGEST_APPROVE mode.
677
+ suggest_approve = project.estimation_mode == EstimationMode.SUGGEST_APPROVE
678
+ sched_tasks = build_sched_tasks(db_tasks, suggest_approve=suggest_approve)
679
+
680
+ included_ids = {str(t.id) for t in db_tasks}
681
+ sched_deps = _build_sched_deps(pk, included_ids)
682
+
683
+ # Shared graph shaping (#3527): summary (phase) rows are grouping nodes, not
684
+ # schedulable work (ADR-0105), so they are stripped and their edges fanned down
685
+ # to leaves before the simulation — exactly as the deterministic CPM pass does.
686
+ # Sharing only build_sched_tasks was not enough: every phase used to enter the
687
+ # simulation as a never-started, unconstrained block floored at the data date,
688
+ # and the longest one became the simulated finish. That made the forecast flat,
689
+ # unrelated to the network, and pushed *further out* by recording real progress.
690
+ # Inside a try, like every other engine call here: build_sched_graph raises
691
+ # InvalidScheduleInput (a ValueError) for a Start-to-Start/Start-to-Finish link
692
+ # from a summary, a breached edge cap, or a malformed WBS. The project exception
693
+ # handler only reclassifies malformed-UUID ValueErrors, so an unguarded raise
694
+ # would be a 500 — and this endpoint promises a clean 400 for exactly these.
695
+ try:
696
+ graph = build_sched_graph(db_tasks, sched_tasks, sched_deps)
697
+ except (CyclicDependencyError, ValueError) as exc:
698
+ # codeql[py/stack-trace-exposure] -- intentional user-facing validation message
699
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
700
+
701
+ # Agile-aware Monte Carlo (#411, ADR-0065/0106): feed the team's completed-sprint
702
+ # throughput to the engine so SCRUM/story-point tasks sample sprints-to-completion
703
+ # from real velocity variance. Without this the engine's velocity path can never
704
+ # fire — every story falls back to its deterministic placeholder duration (1 day),
705
+ # so an all-agile project (e.g. a board-driven program project) forecasts a single
706
+ # flat date with no uncertainty. ([], None) when there is no velocity signal, which
707
+ # leaves a waterfall/PERT project's forecast unchanged.
708
+ from trueppm_api.apps.projects.services import scheduler_velocity_inputs
709
+
710
+ velocity_samples, sprint_length_days = scheduler_velocity_inputs(
711
+ project.pk, sched_calendar.working_days
712
+ )
713
+
714
+ # Data date for the forecast (ADR-0132): the project's explicit status date, or
715
+ # today when unset — so Monte Carlo never schedules remaining work in the past
716
+ # and pins completed work to its actuals. Named so the resolved value can be
717
+ # persisted on the run and echoed in the response (#2638) — previously this
718
+ # substitution happened inline and was never recorded anywhere.
719
+ mc_status_date = project.status_date or timezone.localdate()
720
+
721
+ sched_project = SchedProject(
722
+ id=str(project.pk),
723
+ name=project.name,
724
+ start_date=project.start_date,
725
+ tasks=graph.tasks,
726
+ dependencies=graph.dependencies,
727
+ calendar=sched_calendar,
728
+ status_date=mc_status_date,
729
+ velocity_samples=velocity_samples or None,
730
+ sprint_length_days=sprint_length_days,
731
+ )
732
+
733
+ try:
734
+ # Manual Monte Carlo span (#709): times the simulation inline in the request
735
+ # cycle and records the run count; a no-op span unless OTel is configured.
736
+ with monte_carlo_span(pk, simulation_count=n_simulations):
737
+ mc_result = monte_carlo(
738
+ sched_project,
739
+ runs=n_simulations,
740
+ max_runs=cap,
741
+ max_tasks=settings.MC_TASK_CAP,
742
+ )
743
+ except SimulationCapExceeded as exc:
744
+ return Response(
745
+ # codeql[py/stack-trace-exposure] -- intentional user-facing validation message
746
+ {
747
+ "error": "simulation_cap_exceeded",
748
+ "tier": "team",
749
+ "message": str(exc),
750
+ },
751
+ status=status.HTTP_402_PAYMENT_REQUIRED,
752
+ )
753
+ except (CyclicDependencyError, ValueError) as exc:
754
+ # codeql[py/stack-trace-exposure] -- intentional user-facing validation message
755
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
756
+ except OverflowError:
757
+ # Defense in depth: the engine's MAX_PROJECT_SPAN_DAYS guard makes this
758
+ # unreachable for any realistic start date, but never let a date-range
759
+ # overflow surface as a 500 (OverflowError is not a ValueError).
760
+ return Response(
761
+ {"detail": _DATE_RANGE_EXCEEDED_DETAIL},
762
+ status=status.HTTP_400_BAD_REQUEST,
763
+ )
764
+
765
+ dist = mc_result.distribution
766
+ histogram = _mc_histogram(dist)
767
+
768
+ # The deterministic CPM spine is the max early_finish of the committed tasks
769
+ # already loaded above — no extra query. It anchors delta_vs_cpm (the risk
770
+ # premium each percentile adds over the deterministic finish) and is itself
771
+ # the project's deterministic schedule finish (#987 — single source, no
772
+ # duplicate project field). Computed before result_dict so the cached latest
773
+ # payload carries it.
774
+ cpm_finish = max(
775
+ (t.early_finish for t in db_tasks if t.early_finish is not None),
776
+ default=None,
777
+ )
778
+
779
+ # `last_run_at` lets the frontend surface a "Last run: 2h ago" freshness
780
+ # signal and decide whether to nudge a rerun (#335). Captured at cache-write
781
+ # time so it always tracks the most recent successful simulation, never the
782
+ # cache read. Held as a datetime as well as an ISO string because the risk
783
+ # premium ages the run against it (ADR-0698).
784
+ run_at = timezone.now()
785
+ result_dict = {
786
+ **mc_result.to_dict(),
787
+ "cpm_finish": cpm_finish.isoformat() if cpm_finish else None,
788
+ "delta_vs_cpm": {
789
+ "p50": _delta_vs_cpm_days(mc_result.p50, cpm_finish),
790
+ "p80": _delta_vs_cpm_days(mc_result.p80, cpm_finish),
791
+ "p95": _delta_vs_cpm_days(mc_result.p95, cpm_finish),
792
+ },
793
+ "confidence_curve": _confidence_curve(histogram, len(dist)),
794
+ "histogram_buckets": histogram,
795
+ # Why the forecast has (or lacks) a band, so the UI can explain a flat
796
+ # result instead of presenting a misleadingly precise single date (#1340).
797
+ # Computed from the already-loaded committed task set + estimation mode +
798
+ # velocity signal — no extra query.
799
+ "forecast_diagnostic": forecast_diagnostic(
800
+ # The LEAF rows, not every committed row (#3527): the diagnostic explains
801
+ # what the simulation did, and a summary is not in the simulated network.
802
+ # Counting phases made `tasks_total` overstate the run and let a
803
+ # fully-complete project miss `all_complete` — a summary's stored
804
+ # percent_complete is 0, so every phase read as incomplete work.
805
+ graph.leaf_db_tasks,
806
+ suggest_approve=suggest_approve,
807
+ has_velocity_signal=bool(velocity_samples),
808
+ deterministic=(mc_result.p50 == mc_result.p80 == mc_result.p95),
809
+ ),
810
+ "last_run_at": run_at.isoformat(),
811
+ # The plan version this run was computed against (#3140), captured above
812
+ # before the task set was read. Carried on the cache entry — not only on
813
+ # the persisted row below — because a run triggered by a *Member* refreshes
814
+ # the cache but persists no attributed row (#1502), so for those runs the
815
+ # cache entry is the only place this observation exists. Unlike the
816
+ # risk-premium family, this is not derivable at read time from anything.
817
+ "plan_version": plan_version,
818
+ # The data date this run was actually computed against (ADR-0132, #2638):
819
+ # the project's explicit status_date, or today when unset. Carried on the
820
+ # cache entry too (it is part of ``result_dict``) so a cached read states
821
+ # the same provenance as a fresh run, and on the persisted MonteCarloRun
822
+ # row below so history stays re-derivable after the fact.
823
+ "status_date": mc_status_date.isoformat(),
824
+ }
825
+ cache.set(mc_latest_cache_key(pk), result_dict, timeout=86400)
826
+
827
+ # Persist a forecast-drift history row (ADR-0175, #961) only for Scheduler+
828
+ # callers; the read is Member-level but the attributed write is not (#1502).
829
+ _persist_mc_run_if_authorized(
830
+ request,
831
+ project,
832
+ mc_result=mc_result,
833
+ n_simulations=n_simulations,
834
+ cpm_finish=cpm_finish,
835
+ # The size of the network actually simulated (#3527) — summaries are
836
+ # stripped before the run, so counting them here would describe an input
837
+ # the engine never saw.
838
+ task_count=len(graph.tasks),
839
+ result_dict=result_dict,
840
+ status_date=mc_status_date,
841
+ plan_version=plan_version,
842
+ )
843
+ # Added time (#2531, ADR-0698) rides the response but NOT the cache entry above.
844
+ # Two of its terms depend on when the response is built rather than when the run
845
+ # happened: `ratio` divides by the duration remaining as of today, which collapses
846
+ # to null once the CPM finish passes, and `state` flips to `stale` with age. A
847
+ # premium frozen at cache-write would keep reporting a share of a remainder that
848
+ # has since elapsed, so it is derived per response instead.
849
+ current_plan_version, current_recalculated_at = _current_plan_state(pk)
850
+ return Response(
851
+ {
852
+ **result_dict,
853
+ **risk_premium_from_values(
854
+ p80=mc_result.p80,
855
+ cpm_finish=cpm_finish,
856
+ taken_at=run_at,
857
+ diagnostic=result_dict["forecast_diagnostic"],
858
+ today=timezone.localdate(),
859
+ ),
860
+ # Staleness is re-read rather than assumed `current` (#3140). The project's
861
+ # version is fetched again here because a synced write can land *during* the
862
+ # simulation, and that run genuinely does not cover it — telling the user so
863
+ # immediately is the whole point of the discriminant. One indexed pk read on
864
+ # an endpoint that just ran a Monte Carlo simulation is not a cost worth
865
+ # trading a false `current` for.
866
+ **forecast_staleness_facts(
867
+ plan_version=plan_version,
868
+ plan_version_current=current_plan_version,
869
+ taken_at=run_at,
870
+ recalculated_at=current_recalculated_at,
871
+ today=timezone.localdate(),
872
+ ),
873
+ }
874
+ )
875
+
876
+
877
+ class MonteCarloLatestView(McpReadableViewMixin, APIView):
878
+ """Return the cached result of the most recent MC simulation for this project.
879
+
880
+ Returns 200 with the full result dict if a cached result exists, or 404 if
881
+ no simulation has been run since the 24-hour cache TTL last expired.
882
+
883
+ Permission: Member (any role ≥ Viewer).
884
+ """
885
+
886
+ # ADR-0678 (#2482): projects/<pk>/monte-carlo/latest/
887
+ mcp_scope = McpScope.PATH
888
+
889
+ mcp_compute_heavy = True # part of the F4 compute-heavy MCP tool set (#1808)
890
+ # Route is `projects/<pk>/…`, so `pk` names the PROJECT here (#2745). Without
891
+ # this the project-scoped classes below resolve nothing and `has_permission`
892
+ # returns True for everyone — the gate reads as live in review and enforces
893
+ # nothing. Declared per view because `pk` means something else on other routes.
894
+ project_url_kwarg = "pk"
895
+ permission_classes = [IsAuthenticated, IsProjectMember, IsProjectNotArchived]
896
+
897
+ @extend_schema(
898
+ summary="Latest cached Monte Carlo forecast for the project",
899
+ responses={
900
+ 200: OpenApiResponse(
901
+ response=MonteCarloForecastSerializer,
902
+ description=(
903
+ "The most recent Monte Carlo result for the project. Keys: p50/p80/p95 "
904
+ "(ISO-8601 finish dates), cpm_finish, delta_vs_cpm ({p50, p80, p95} "
905
+ "calendar-day deltas vs the CPM finish), runs (n_simulations), "
906
+ "confidence_curve, histogram_buckets, sensitivity, last_run_at, "
907
+ "status_date (the data date this run was computed against — "
908
+ "project.status_date or today when unset, ADR-0132/#2638; null for "
909
+ "runs persisted before #2638), from_history (true when served from a "
910
+ "persisted run after the 24h cache TTL expired), and the risk_premium_* "
911
+ "family (ADR-0698): "
912
+ "risk_premium_state (not_run|unmeasurable|stale|zero|premium|negative — "
913
+ "the discriminant every client renders from, never null), "
914
+ "risk_premium_days, risk_premium_ratio, risk_premium_band (always null "
915
+ "until #2299), risk_premium_as_of, risk_premium_reason, "
916
+ "risk_premium_cpm_finish, risk_premium_p80. The premium is derived on "
917
+ "every response and is never stored in the cache entry. Legacy runs with "
918
+ "no stored distribution return empty "
919
+ "confidence_curve/histogram_buckets/sensitivity arrays. "
920
+ "Plus the forecast-staleness family (#3140): forecast_staleness "
921
+ "(current|project_changed|aged|unknown — never null; only `current` "
922
+ "means the forecast still describes the plan, and a client keeps the "
923
+ "recompute action reachable on the other three), plan_version (the "
924
+ "project's sync version this run was computed against — unlike the "
925
+ "risk_premium family this one IS carried on the cache entry and the "
926
+ "persisted row, because it is a run-time observation that cannot be "
927
+ "re-derived later; null for runs recorded before #3140, which "
928
+ "classify as `unknown`, never `current`), and plan_version_current "
929
+ "(that version as of this response). `project_changed` is "
930
+ "deliberately not named `plan_changed`: the underlying counter "
931
+ "advances on ANY write in the project, so a description or label "
932
+ "edit raises it without moving a date. It is a sound trigger for "
933
+ "offering a recompute and NOT evidence that a schedule value "
934
+ "changed — do not narrate it as one."
935
+ ),
936
+ ),
937
+ 404: OpenApiResponse(
938
+ response=OpenApiTypes.OBJECT,
939
+ description="No simulation result available for this project ({detail}).",
940
+ ),
941
+ },
942
+ )
943
+ def get(self, request: Request, pk: str) -> Response:
944
+ """Return the latest cached Monte Carlo result for the project.
945
+
946
+ Falls back to the most recent persisted ``MonteCarloRun`` when the 24-hour
947
+ cache has expired (ADR-0175): the latest forecast now survives past the
948
+ TTL. As of #1231 the run also persists its distribution, so when present the
949
+ fallback returns the real ``histogram_buckets``/``confidence_curve``/
950
+ ``sensitivity`` instead of empty arrays — the histogram survives cache
951
+ expiry. Legacy runs (no persisted distribution) still fall back to empty,
952
+ and the frontend renders the empty-state prose for them.
953
+ """
954
+ project = get_object_or_404(Project, pk=pk, is_deleted=False)
955
+ self.check_object_permissions(request, project)
956
+ cached = cache.get(mc_latest_cache_key(pk))
957
+ if cached is not None:
958
+ # Added time is layered on at read time, never taken from the entry — the
959
+ # entry has no premium keys to take (ADR-0698 §2). A cached forecast can be
960
+ # served for 24 hours, and both `risk_premium_ratio` (a share of the
961
+ # duration still remaining today) and `risk_premium_state` (which ages into
962
+ # `stale`) would be wrong by the time it is read back.
963
+ return Response(
964
+ {
965
+ **cached,
966
+ **risk_premium_for_forecast_payload(cached, today=timezone.localdate()),
967
+ # Same read-time discipline, different reason (#3140): the entry
968
+ # carries the plan version the run SAW, and the project has been free
969
+ # to move for up to 24 hours since. `project` is already loaded, so
970
+ # the comparison costs nothing. An entry written before #3140 has no
971
+ # `plan_version` key and classifies as `unknown` — honest, and it
972
+ # self-heals on the next run, which is why `MC_LATEST_CACHE_VERSION`
973
+ # is deliberately NOT bumped here: unlike the #2833 engine fix, no
974
+ # cached *number* is wrong, only unplaceable.
975
+ **forecast_staleness_for_payload(
976
+ cached,
977
+ plan_version_current=project.last_sync_version,
978
+ recalculated_at=project.recalculated_at,
979
+ today=timezone.localdate(),
980
+ ),
981
+ }
982
+ )
983
+
984
+ latest = MonteCarloRun.objects.filter(project_id=pk).order_by("-taken_at").first()
985
+ if latest is None:
986
+ return Response(
987
+ {"detail": "No simulation result available."},
988
+ status=status.HTTP_404_NOT_FOUND,
989
+ )
990
+ # cpm_finish + delta_vs_cpm survive the TTL because both are persisted on the
991
+ # run (ADR-0175). The distribution (#1231) now survives too when persisted:
992
+ # use the stored buckets/curve/sensitivity, falling back to empty arrays for
993
+ # legacy runs that pre-date persistence (the frontend shows the empty-state
994
+ # prose then). Response shape is unchanged (snake_case keys).
995
+ dist = latest.distribution or {}
996
+ return Response(
997
+ {
998
+ # The live-run payload has carried `project_id` since #172; the
999
+ # from-history branch omitted it, and the client maps it straight
1000
+ # through as a non-optional field. Harmless while nothing read it —
1001
+ # but the added-time card's "Add estimates →" target is built from it
1002
+ # (#2531), so past the 24h TTL that link resolved to
1003
+ # `/projects/undefined`.
1004
+ "project_id": str(latest.project_id),
1005
+ "p50": latest.p50.isoformat() if latest.p50 else None,
1006
+ "p80": latest.p80.isoformat() if latest.p80 else None,
1007
+ "p95": latest.p95.isoformat() if latest.p95 else None,
1008
+ "cpm_finish": latest.cpm_finish.isoformat() if latest.cpm_finish else None,
1009
+ "delta_vs_cpm": {
1010
+ "p50": _delta_vs_cpm_days(latest.p50, latest.cpm_finish),
1011
+ "p80": _delta_vs_cpm_days(latest.p80, latest.cpm_finish),
1012
+ "p95": _delta_vs_cpm_days(latest.p95, latest.cpm_finish),
1013
+ },
1014
+ "confidence_curve": dist.get("confidence_curve", []),
1015
+ "runs": latest.n_simulations,
1016
+ "histogram_buckets": dist.get("histogram_buckets", []),
1017
+ "sensitivity": dist.get("sensitivity", []),
1018
+ # Persisted with the run since #2483, so the "why is this flat"
1019
+ # explanation now survives cache expiry alongside the distribution.
1020
+ # Legacy rows have none; the client already treats an absent
1021
+ # diagnostic as "no reason known", never as "no estimates".
1022
+ "forecast_diagnostic": latest.diagnostic,
1023
+ "last_run_at": latest.taken_at.isoformat(),
1024
+ # Persisted with the run since #2638; legacy rows predate the field
1025
+ # and read back as null rather than a guessed value (same pattern as
1026
+ # `diagnostic`/`distribution` above).
1027
+ "status_date": latest.status_date.isoformat() if latest.status_date else None,
1028
+ "from_history": True,
1029
+ # The same call `ProjectOverviewView` makes, on the same row — so the
1030
+ # Overview card and every forecast surface read one derivation of what
1031
+ # a premium of 0 means, and cannot disagree (ADR-0698).
1032
+ **build_risk_premium(latest, today=timezone.localdate()),
1033
+ # Persisted with the run since #3140. Legacy rows carry none and classify
1034
+ # as `unknown` rather than `current` — the client then keeps Rerun
1035
+ # reachable and makes no staleness claim it cannot support.
1036
+ **forecast_staleness_from_run(
1037
+ latest,
1038
+ plan_version_current=project.last_sync_version,
1039
+ recalculated_at=project.recalculated_at,
1040
+ today=timezone.localdate(),
1041
+ ),
1042
+ }
1043
+ )
1044
+
1045
+
1046
+ # Fixed RNG seed for the what-if endpoint (#993). Both the baseline and the
1047
+ # perturbed Monte Carlo runs sample with THIS seed, so they draw the *same*
1048
+ # per-run duration samples for every unperturbed task. The delta between the two
1049
+ # forecasts therefore isolates the effect of the perturbation rather than RNG
1050
+ # noise, and the endpoint is a pure function of its inputs — the same what-if
1051
+ # query always returns the same forecast, which a reproducible "slip this task"
1052
+ # demo (and a stable test assertion) both depend on.
1053
+ WHATIF_MC_SEED = 993_993
1054
+
1055
+
1056
+ class MonteCarloWhatIfView(McpReadableViewMixin, APIView):
1057
+ """Non-mutating Monte Carlo what-if: perturb one task's duration, recompute (#993).
1058
+
1059
+ Backs the MCP ``whatif`` read tool (#504/#603): accept a ``task_id`` plus a
1060
+ duration perturbation, run CPM + Monte Carlo **in memory without persisting
1061
+ anything**, and return the resulting P50/P80/P95, the deterministic CPM finish,
1062
+ whether the critical path changed, and the signed deltas versus the current
1063
+ (unperturbed) forecast.
1064
+
1065
+ Why GET, not POST: the endpoint has no side effects — it writes no rows, sets no
1066
+ cache, and enqueues no recompute — so it is a pure read/compute, correctly
1067
+ modeled as GET. That is also what makes it reachable by an ``mcp:read`` API
1068
+ token: ``McpReadableViewMixin`` confines token callers to safe methods, so a
1069
+ POST could never back a *read* MCP tool. Query params carry the perturbation
1070
+ (``?task_id=&duration_delta=`` or ``&new_duration=``).
1071
+
1072
+ Non-persistence guarantee: this view never calls ``.save()``,
1073
+ ``record_monte_carlo_run``, ``cache.set``, or ``enqueue_recalculate``. The
1074
+ perturbation is applied to freshly-built in-memory scheduler dataclasses; the
1075
+ Django rows are only read. ``schedule()`` and ``monte_carlo()`` both operate on
1076
+ copies and do not mutate their input project.
1077
+
1078
+ Permission: Member (any role >= Viewer), the same project-read gate as the
1079
+ ``run_monte_carlo`` / latest / history forecast endpoints.
1080
+ """
1081
+
1082
+ # ADR-0678 (#2482): projects/<pk>/monte-carlo/whatif/
1083
+ mcp_scope = McpScope.PATH
1084
+
1085
+ mcp_compute_heavy = True # two CPM passes + two Monte Carlo runs per call (#1808 F4)
1086
+ # Route is `projects/<pk>/…`, so `pk` names the PROJECT here (#2745). Without
1087
+ # this the project-scoped classes below resolve nothing and `has_permission`
1088
+ # returns True for everyone — the gate reads as live in review and enforces
1089
+ # nothing. Declared per view because `pk` means something else on other routes.
1090
+ project_url_kwarg = "pk"
1091
+ permission_classes = [IsAuthenticated, IsProjectMember, IsProjectNotArchived]
1092
+ throttle_classes = [ScopedRateThrottle]
1093
+ throttle_scope = "monte_carlo_whatif"
1094
+
1095
+ @extend_schema(
1096
+ summary="Non-mutating Monte Carlo what-if for a single task duration change",
1097
+ parameters=[
1098
+ OpenApiParameter(
1099
+ "task_id",
1100
+ OpenApiTypes.UUID,
1101
+ required=True,
1102
+ description="The committed task whose duration to perturb.",
1103
+ ),
1104
+ OpenApiParameter(
1105
+ "duration_delta",
1106
+ OpenApiTypes.INT,
1107
+ description=(
1108
+ "Signed day offset applied to the task's current duration "
1109
+ "(e.g. 5 to slip it a working week later, -2 to pull it in). "
1110
+ "Supply exactly one of duration_delta or new_duration."
1111
+ ),
1112
+ ),
1113
+ OpenApiParameter(
1114
+ "new_duration",
1115
+ OpenApiTypes.INT,
1116
+ description=(
1117
+ "Absolute day count to set the task's duration to (>= 0). "
1118
+ "Supply exactly one of duration_delta or new_duration."
1119
+ ),
1120
+ ),
1121
+ OpenApiParameter(
1122
+ "n_simulations",
1123
+ OpenApiTypes.INT,
1124
+ description="Monte Carlo iterations; defaults to MC_SIMULATION_CAP, capped there.",
1125
+ ),
1126
+ ],
1127
+ responses={
1128
+ 200: OpenApiResponse(
1129
+ response=MonteCarloWhatIfResponseSerializer,
1130
+ description=(
1131
+ "What-if forecast. Keys: task_id; applied ({base_duration_days, "
1132
+ "duration_delta_days, new_duration_days}); current and whatif (each "
1133
+ "{p50, p80, p95, cpm_finish (ISO-8601 or null), critical_path ([task_id])}); "
1134
+ "critical_path_changed (bool — did the set of critical tasks change); "
1135
+ "delta_vs_current ({p50, p80, p95, cpm_finish} signed calendar-day shifts, "
1136
+ "positive = later/worse, null when a date is missing); runs (n_simulations); "
1137
+ "seed (fixed RNG seed shared by both runs so the delta isolates the change); "
1138
+ "cpm_status_date and mc_status_date (ADR-0132/#2638, floor armed on the "
1139
+ "CPM path by ADR-0752 §4) — the resolved data dates (project.status_date, "
1140
+ "or today when unset) fed to the deterministic and Monte Carlo passes "
1141
+ "respectively, shared by both current and whatif since this view runs both "
1142
+ "in one call; this view never persists, so these are the only provenance a "
1143
+ "caller gets for how the forecast was computed."
1144
+ ),
1145
+ ),
1146
+ 400: OpenApiResponse(
1147
+ response=OpenApiTypes.OBJECT,
1148
+ description=(
1149
+ "Invalid input: malformed/absent params, both or neither of "
1150
+ "duration_delta/new_duration, task_id not a committed task in this "
1151
+ "project, a milestone (zero-duration) target, a summary (phase) target "
1152
+ "whose span is rolled up from its children and so cannot be perturbed, "
1153
+ "a cyclic dependency, or an out-of-range project span."
1154
+ ),
1155
+ ),
1156
+ 402: OpenApiResponse(
1157
+ response=OpenApiTypes.OBJECT,
1158
+ description="OSS simulation cap exceeded (n_simulations or task count too high).",
1159
+ ),
1160
+ 404: OpenApiResponse(
1161
+ response=OpenApiTypes.OBJECT,
1162
+ description="Project does not exist.",
1163
+ ),
1164
+ },
1165
+ )
1166
+ def get(self, request: Request, pk: str) -> Response:
1167
+ """Run the perturbed forecast in memory and return the deltas (see class doc)."""
1168
+ from trueppm_scheduler.engine import (
1169
+ CyclicDependencyError,
1170
+ SimulationCapExceeded,
1171
+ monte_carlo,
1172
+ perturb_task_duration,
1173
+ schedule,
1174
+ )
1175
+ from trueppm_scheduler.models import Project as SchedProject
1176
+
1177
+ from trueppm_api.apps.projects.services import scheduler_velocity_inputs
1178
+
1179
+ req = MonteCarloWhatIfRequestSerializer(data=request.query_params)
1180
+ req.is_valid(raise_exception=True)
1181
+ params = req.validated_data
1182
+ task_id = str(params["task_id"])
1183
+
1184
+ try:
1185
+ project = (
1186
+ Project.objects.select_related("calendar", "program__calendar")
1187
+ .prefetch_related(
1188
+ "tasks",
1189
+ "calendar__exceptions",
1190
+ "calendar_layers__calendar__exceptions",
1191
+ # ADR-0441: the resolver reads the program calendar's exceptions when a
1192
+ # project inherits its base calendar from the program.
1193
+ "program__calendar__exceptions",
1194
+ )
1195
+ .get(pk=pk, is_deleted=False)
1196
+ )
1197
+ except Project.DoesNotExist:
1198
+ return Response({"detail": _NOT_FOUND_DETAIL}, status=status.HTTP_404_NOT_FOUND)
1199
+
1200
+ # Object-level membership + not-archived gate (same read level as the
1201
+ # forecast endpoints). APIView.get has no get_object(), so enforce explicitly.
1202
+ self.check_object_permissions(request, project)
1203
+
1204
+ cap: int | None = settings.MC_SIMULATION_CAP
1205
+ n_simulations = int(params.get("n_simulations", cap or 1_000))
1206
+
1207
+ # Build the baseline scheduler input exactly as run_monte_carlo does, through
1208
+ # the shared converters (ADR-0132/#1491) so the what-if forecast is computed on
1209
+ # the identical graph the real forecast uses — same calendar exceptions, same
1210
+ # planned_start floors, same velocity signal.
1211
+ sched_calendar = compose_project_calendar(project)
1212
+ db_tasks = list(Task.committed.filter(project=project).select_related("sprint"))
1213
+ if not db_tasks:
1214
+ return Response(
1215
+ {"detail": "Project has no schedulable (committed) tasks to forecast."},
1216
+ status=status.HTTP_400_BAD_REQUEST,
1217
+ )
1218
+
1219
+ # The perturbation target must be one of THIS project's committed tasks. A
1220
+ # BACKLOG card, a task in another project, or an unknown id is rejected as a
1221
+ # clean 400 (not 404 — the project exists and the caller can read it; only the
1222
+ # task reference is invalid) and never leaks whether the id exists elsewhere.
1223
+ target_db = next((t for t in db_tasks if str(t.id) == task_id), None)
1224
+ if target_db is None:
1225
+ return Response(
1226
+ {"detail": "task_id is not a committed task in this project."},
1227
+ status=status.HTTP_400_BAD_REQUEST,
1228
+ )
1229
+ if target_db.is_milestone:
1230
+ return Response(
1231
+ {"detail": "A milestone is a zero-duration gate and cannot be perturbed."},
1232
+ status=status.HTTP_400_BAD_REQUEST,
1233
+ )
1234
+
1235
+ base_duration_days = int(target_db.duration)
1236
+ if "duration_delta" in params:
1237
+ delta_days = int(params["duration_delta"])
1238
+ else:
1239
+ # new_duration is absolute; convert to the equivalent signed shift so both
1240
+ # inputs flow through one perturbation path.
1241
+ delta_days = int(params["new_duration"]) - base_duration_days
1242
+ new_duration_days = max(0, base_duration_days + delta_days)
1243
+
1244
+ suggest_approve = project.estimation_mode == EstimationMode.SUGGEST_APPROVE
1245
+ baseline_tasks = build_sched_tasks(db_tasks, suggest_approve=suggest_approve)
1246
+
1247
+ included_ids = {str(t.id) for t in db_tasks}
1248
+ sched_deps = _build_sched_deps(pk, included_ids)
1249
+
1250
+ # Same leaf-only shaping the real forecast uses (#3527, ADR-0105) — a what-if
1251
+ # answered against a network containing phantom phases is not a what-if about
1252
+ # this project's schedule.
1253
+ try:
1254
+ graph = build_sched_graph(db_tasks, baseline_tasks, sched_deps)
1255
+ except (CyclicDependencyError, ValueError) as exc:
1256
+ # codeql[py/stack-trace-exposure] -- intentional user-facing validation message
1257
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
1258
+
1259
+ # A summary has no duration of its own — its span is rolled up from its leaves
1260
+ # — so it is absent from the network built above, and perturbing it would
1261
+ # silently change nothing. Refuse rather than hand back an unmoved forecast as
1262
+ # though the delta had been applied. Checked after the shaping because that is
1263
+ # what defines "is a summary" here, and before any simulation runs.
1264
+ if str(target_db.id) in graph.summary_ids:
1265
+ return Response(
1266
+ {
1267
+ "detail": (
1268
+ "A summary task's duration is rolled up from its children and "
1269
+ "cannot be perturbed; pick one of its leaf tasks instead."
1270
+ )
1271
+ },
1272
+ status=status.HTTP_400_BAD_REQUEST,
1273
+ )
1274
+
1275
+ leaf_tasks = graph.tasks
1276
+ leaf_deps = graph.dependencies
1277
+
1278
+ velocity_samples, sprint_length_days = scheduler_velocity_inputs(
1279
+ project.pk, sched_calendar.working_days
1280
+ )
1281
+
1282
+ # The deterministic CPM and Monte Carlo both floor a null status_date at
1283
+ # today (ADR-0752 §4, correcting ADR-0132 §1 — the CPM path used to pass
1284
+ # a null status_date raw, meaning "no floor at all"). Both are resolved
1285
+ # through the same shared helper so this read-time `current` block can
1286
+ # never drift from the persisted deterministic run
1287
+ # (`scheduling/tasks.py::_run_schedule`) on which data date it used —
1288
+ # keeping current.cpm_finish identical to the persisted deterministic
1289
+ # finish and current P50/P80/P95 identical to run_monte_carlo.
1290
+ cpm_status_date = resolve_cpm_status_date(project.status_date)
1291
+ mc_status_date = resolve_cpm_status_date(project.status_date)
1292
+
1293
+ def _make_project(tasks: list[Any], status_date: _date | None) -> Any:
1294
+ return SchedProject(
1295
+ id=str(project.pk),
1296
+ name=project.name,
1297
+ start_date=project.start_date,
1298
+ tasks=tasks,
1299
+ dependencies=leaf_deps,
1300
+ calendar=sched_calendar,
1301
+ status_date=status_date,
1302
+ velocity_samples=velocity_samples or None,
1303
+ sprint_length_days=sprint_length_days,
1304
+ )
1305
+
1306
+ try:
1307
+ # One shared Monte Carlo span (#709) over the full what-if computation —
1308
+ # baseline + perturbed CPM and simulation — through the same helper the
1309
+ # real forecast uses, so the span name and attributes cannot drift.
1310
+ with monte_carlo_span(pk, simulation_count=n_simulations):
1311
+ # The ENGINE owns the perturbation (#3533). Which input a task's
1312
+ # sampled duration comes from is the engine's own priority rule
1313
+ # (velocity → PERT triple → deterministic); an API-side shift of
1314
+ # the fields this view happens to know about moved the CPM finish
1315
+ # while leaving a velocity-sampled task's bands exactly where they
1316
+ # were, and reported both. Passing the fully-built project — with
1317
+ # the velocity signal on it — is what lets the engine reach the
1318
+ # input it will actually sample.
1319
+ perturbed_tasks = perturb_task_duration(
1320
+ _make_project(leaf_tasks, cpm_status_date), task_id, delta_days
1321
+ ).tasks
1322
+ baseline_cpm = schedule(_make_project(leaf_tasks, cpm_status_date))
1323
+ perturbed_cpm = schedule(_make_project(perturbed_tasks, cpm_status_date))
1324
+ baseline_mc = monte_carlo(
1325
+ _make_project(leaf_tasks, mc_status_date),
1326
+ runs=n_simulations,
1327
+ seed=WHATIF_MC_SEED,
1328
+ max_runs=cap,
1329
+ max_tasks=settings.MC_TASK_CAP,
1330
+ )
1331
+ perturbed_mc = monte_carlo(
1332
+ _make_project(perturbed_tasks, mc_status_date),
1333
+ runs=n_simulations,
1334
+ seed=WHATIF_MC_SEED,
1335
+ max_runs=cap,
1336
+ max_tasks=settings.MC_TASK_CAP,
1337
+ )
1338
+ except SimulationCapExceeded as exc:
1339
+ return Response(
1340
+ # codeql[py/stack-trace-exposure] -- intentional user-facing validation message
1341
+ {"error": "simulation_cap_exceeded", "tier": "team", "message": str(exc)},
1342
+ status=status.HTTP_402_PAYMENT_REQUIRED,
1343
+ )
1344
+ except (CyclicDependencyError, ValueError) as exc:
1345
+ # codeql[py/stack-trace-exposure] -- intentional user-facing validation message
1346
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
1347
+ except OverflowError:
1348
+ return Response(
1349
+ {"detail": _DATE_RANGE_EXCEEDED_DETAIL},
1350
+ status=status.HTTP_400_BAD_REQUEST,
1351
+ )
1352
+
1353
+ # A membership change in the critical set is the meaningful "the shape of the
1354
+ # plan moved" signal — compared as sets so a pure reordering along an unchanged
1355
+ # path does not read as a change.
1356
+ critical_path_changed = set(baseline_cpm.critical_path) != set(perturbed_cpm.critical_path)
1357
+
1358
+ current = {
1359
+ "p50": baseline_mc.p50.isoformat(),
1360
+ "p80": baseline_mc.p80.isoformat(),
1361
+ "p95": baseline_mc.p95.isoformat(),
1362
+ "cpm_finish": baseline_cpm.project_finish.isoformat(),
1363
+ "critical_path": list(baseline_cpm.critical_path),
1364
+ }
1365
+ whatif = {
1366
+ "p50": perturbed_mc.p50.isoformat(),
1367
+ "p80": perturbed_mc.p80.isoformat(),
1368
+ "p95": perturbed_mc.p95.isoformat(),
1369
+ "cpm_finish": perturbed_cpm.project_finish.isoformat(),
1370
+ "critical_path": list(perturbed_cpm.critical_path),
1371
+ }
1372
+ return Response(
1373
+ {
1374
+ "task_id": task_id,
1375
+ "applied": {
1376
+ "base_duration_days": base_duration_days,
1377
+ "duration_delta_days": delta_days,
1378
+ "new_duration_days": new_duration_days,
1379
+ },
1380
+ "current": current,
1381
+ "whatif": whatif,
1382
+ "critical_path_changed": critical_path_changed,
1383
+ "delta_vs_current": {
1384
+ "p50": _date_delta_days(perturbed_mc.p50, baseline_mc.p50),
1385
+ "p80": _date_delta_days(perturbed_mc.p80, baseline_mc.p80),
1386
+ "p95": _date_delta_days(perturbed_mc.p95, baseline_mc.p95),
1387
+ "cpm_finish": _date_delta_days(
1388
+ perturbed_cpm.project_finish, baseline_cpm.project_finish
1389
+ ),
1390
+ },
1391
+ "runs": n_simulations,
1392
+ "seed": WHATIF_MC_SEED,
1393
+ # The data dates fed to each engine for both the current and whatif
1394
+ # passes (ADR-0132, floor armed on the CPM path by ADR-0752 §4) —
1395
+ # this view never persists, so these are the only provenance an
1396
+ # AI/MCP or human caller gets for how "current" was computed. Both
1397
+ # baseline and perturbed share one resolved value per engine within
1398
+ # a single call, so one top-level pair covers both `current` and
1399
+ # `whatif` rather than duplicating it under each (#2638). Both are
1400
+ # always a resolved date now (never null) — a null status_date no
1401
+ # longer means "no floor at all" on the CPM path.
1402
+ "cpm_status_date": cpm_status_date.isoformat(),
1403
+ "mc_status_date": mc_status_date.isoformat(),
1404
+ }
1405
+ )
1406
+
1407
+
1408
+ # Hard ceiling on a single forecast-history response, independent of the
1409
+ # retention cap. OSS retention (MC_HISTORY_CAP=100) is already below this; the
1410
+ # ceiling only bites the Enterprise unlimited-retention case so the endpoint can
1411
+ # never stream an unbounded payload (ADR-0175).
1412
+ MC_HISTORY_RESPONSE_MAX = 500
1413
+
1414
+
1415
+ def _annotate_run_deltas(runs: list[MonteCarloRun]) -> None:
1416
+ """Attach a computed-on-read ``_delta`` to each run vs the next-older run (ADR-0108).
1417
+
1418
+ ``runs`` is newest-first; positive days = the forecast slipped later (worse). The
1419
+ oldest row has no predecessor, so its ``_delta`` stays ``None`` (baseline). Mutates
1420
+ each run in place for the serializer to read.
1421
+ """
1422
+ for i, run in enumerate(runs):
1423
+ older = runs[i + 1] if i + 1 < len(runs) else None
1424
+ if older is None:
1425
+ run._delta = None # type: ignore[attr-defined]
1426
+ else:
1427
+ run._delta = { # type: ignore[attr-defined]
1428
+ "p50": _date_delta_days(run.p50, older.p50),
1429
+ "p80": _date_delta_days(run.p80, older.p80),
1430
+ "p95": _date_delta_days(run.p95, older.p95),
1431
+ }
1432
+
1433
+
1434
+ def _mc_attribution_visible(request: Request, project: Project, pk: str) -> bool:
1435
+ """Whether the caller may see run-author attribution, per the effective audience.
1436
+
1437
+ Resolved per-workspace (ADR-0144): ADMIN_OWNER → role ≥ ADMIN; SCHEDULER_PLUS →
1438
+ role ≥ SCHEDULER; NONE → never. Default ADMIN_OWNER reproduces the prior hardcoded
1439
+ gate exactly. Drift must not become a named-individual signal below the configured
1440
+ audience (VoC Morgan).
1441
+ """
1442
+ from trueppm_api.apps.access.models import Role
1443
+ from trueppm_api.apps.access.permissions import _membership_role
1444
+ from trueppm_api.apps.scheduling.forecast_history_settings import (
1445
+ resolve_effective_mc_history,
1446
+ )
1447
+ from trueppm_api.apps.scheduling.models import MCAttributionAudience
1448
+
1449
+ role = _membership_role(request, pk)
1450
+ audience = resolve_effective_mc_history(project, "mc_history_attribution_audience")
1451
+ if audience == MCAttributionAudience.NONE:
1452
+ return False
1453
+ if audience == MCAttributionAudience.SCHEDULER_PLUS:
1454
+ return role is not None and role >= Role.SCHEDULER
1455
+ return role is not None and role >= Role.ADMIN # ADMIN_OWNER (default)
1456
+
1457
+
1458
+ @extend_schema(
1459
+ parameters=[
1460
+ OpenApiParameter(
1461
+ "expand",
1462
+ str,
1463
+ description=(
1464
+ "Set to 'distribution' to include each run's persisted distribution "
1465
+ "({histogram_buckets, confidence_curve, sensitivity}) payload (#1231). "
1466
+ "Omitted by default to keep the list lightweight; distribution is null "
1467
+ "unless expanded or for legacy runs with no stored distribution."
1468
+ ),
1469
+ ),
1470
+ ],
1471
+ responses={
1472
+ 200: OpenApiResponse(
1473
+ response=inline_serializer(
1474
+ name="MonteCarloHistoryResponse",
1475
+ fields={
1476
+ "results": MonteCarloRunSerializer(many=True),
1477
+ "cap": drf_serializers.IntegerField(allow_null=True),
1478
+ "enabled": drf_serializers.BooleanField(),
1479
+ },
1480
+ ),
1481
+ description=(
1482
+ "Project Monte Carlo run history (ADR-0175/0143). When the "
1483
+ "per-workspace config disables history, enabled is false and results "
1484
+ "is empty. Each run carries P50/P80/P95, cpm_finish, n_simulations, "
1485
+ "task_count, status_date (the data date the run was computed against "
1486
+ "— null for runs persisted before #2638), a per-percentile delta vs "
1487
+ "the previous run (null on the oldest row), triggered_by_name "
1488
+ "(non-null only for the resolved attribution audience), and "
1489
+ "distribution (only when ?expand=distribution)."
1490
+ ),
1491
+ ),
1492
+ 404: OpenApiResponse(
1493
+ response=OpenApiTypes.OBJECT,
1494
+ description="Project does not exist.",
1495
+ ),
1496
+ },
1497
+ )
1498
+ class MonteCarloHistoryView(APIView):
1499
+ """Project Monte Carlo run history — forecast drift over time (ADR-0175, #961).
1500
+
1501
+ Returns persisted runs newest-first, capped at ``settings.MC_HISTORY_CAP``,
1502
+ each with a computed-on-read per-percentile delta versus the immediately
1503
+ previous (older) run. The run-author attribution (``triggered_by_name``) is
1504
+ serialized only for Admin/Owner (role ≥ ADMIN); every other member sees the
1505
+ drift values without attribution, so forecast drift cannot become a
1506
+ named-individual performance signal (VoC Morgan).
1507
+
1508
+ Permission: Member (any role ≥ Viewer), consistent with the forecast read.
1509
+ """
1510
+
1511
+ # Route is `projects/<pk>/…`, so `pk` names the PROJECT here (#2745). Without
1512
+ # this the project-scoped classes below resolve nothing and `has_permission`
1513
+ # returns True for everyone — the gate reads as live in review and enforces
1514
+ # nothing. Declared per view because `pk` means something else on other routes.
1515
+ project_url_kwarg = "pk"
1516
+ permission_classes = [IsAuthenticated, IsProjectMember, IsProjectNotArchived]
1517
+
1518
+ def get(self, request: Request, pk: str) -> Response:
1519
+ """Return the capped, newest-first run history with per-run deltas."""
1520
+ from trueppm_api.apps.scheduling.forecast_history_settings import (
1521
+ resolve_effective_mc_history,
1522
+ )
1523
+
1524
+ project = get_object_or_404(Project, pk=pk, is_deleted=False)
1525
+ self.check_object_permissions(request, project)
1526
+
1527
+ # Per-workspace forecast-history config (ADR-0144, #1232), inheritable
1528
+ # Workspace → Program → Project. When the effective config disables history,
1529
+ # return 200 with an empty list + enabled:false rather than 403/404 — the
1530
+ # feature is off, not access-denied, so the FE renders a "history off" state.
1531
+ if not resolve_effective_mc_history(project, "mc_history_enabled"):
1532
+ return Response({"results": [], "cap": None, "enabled": False})
1533
+
1534
+ # The retention cap is now per-workspace-effective (clamped to
1535
+ # MC_HISTORY_HARD_CAP in the resolver) rather than the global constant.
1536
+ cap: int | None = resolve_effective_mc_history(project, "mc_history_retention_cap")
1537
+ # Hard response ceiling: even when the cap is None (Enterprise unlimited
1538
+ # *retention*), a single API response must stay bounded — keep the newest
1539
+ # MC_HISTORY_RESPONSE_MAX rows. select_related avoids an N+1 on triggered_by
1540
+ # when attribution is serialized.
1541
+ limit = cap if cap is not None else MC_HISTORY_RESPONSE_MAX
1542
+ # ?expand=distribution opts a single detail fetch into the heavier per-run
1543
+ # distribution payload (#1231); the default list stays lightweight.
1544
+ expand_distribution = request.query_params.get("expand") == "distribution"
1545
+ qs = (
1546
+ MonteCarloRun.objects.filter(project_id=pk)
1547
+ .select_related("triggered_by")
1548
+ .order_by("-taken_at")
1549
+ )
1550
+ # The distribution column is up to MC_DISTRIBUTION_MAX_BYTES per row; the
1551
+ # serializer never reads it on the default list path, so defer it there to
1552
+ # avoid fetching + JSON-parsing ~limit×32KB only to discard it.
1553
+ if not expand_distribution:
1554
+ qs = qs.defer("distribution")
1555
+ runs = list(qs[:limit])
1556
+ _annotate_run_deltas(runs)
1557
+ can_see_attribution = _mc_attribution_visible(request, project, pk)
1558
+
1559
+ data = MonteCarloRunSerializer(
1560
+ runs,
1561
+ many=True,
1562
+ context={
1563
+ "request": request,
1564
+ "can_see_attribution": can_see_attribution,
1565
+ "expand_distribution": expand_distribution,
1566
+ },
1567
+ ).data
1568
+ return Response({"results": data, "cap": cap, "enabled": True})
1569
+
1570
+
1571
+ @extend_schema(
1572
+ parameters=[
1573
+ # Day-grained window, declared as `date` to match the burn-series
1574
+ # contract (#1378) — the new 0.3 computed analytics endpoints expose
1575
+ # since/until with one consistent type. The runtime stays lenient: a
1576
+ # bare ISO date is the documented format, and a full ISO datetime is
1577
+ # still accepted as a backward-compatible superset (see _parse_bound).
1578
+ OpenApiParameter(
1579
+ "since",
1580
+ OpenApiTypes.DATE,
1581
+ description="Only snapshots captured at or after this ISO 8601 date (YYYY-MM-DD).",
1582
+ ),
1583
+ OpenApiParameter(
1584
+ "until",
1585
+ OpenApiTypes.DATE,
1586
+ description="Only snapshots captured at or before this ISO 8601 date (YYYY-MM-DD).",
1587
+ ),
1588
+ ],
1589
+ responses={200: ProjectForecastSnapshotSerializer(many=True)},
1590
+ )
1591
+ class ForecastSnapshotListView(ListAPIView[ProjectForecastSnapshot]):
1592
+ """Project-grain forecast snapshot history (ADR-0154, #388).
1593
+
1594
+ Returns the project's forecast snapshots newest-first (paginated), the
1595
+ persisted record of how the CPM finish and Monte Carlo percentiles drifted
1596
+ over time. Read-only — rows are server-generated on recompute and by the daily
1597
+ floor; there is no write surface. ``?since=``/``?until=`` bound the window by
1598
+ ``captured_at`` (ISO 8601 date YYYY-MM-DD, the documented format; a full ISO
1599
+ datetime is also accepted and interpreted literally, a bare date as midnight UTC).
1600
+
1601
+ Permission: Member (any role ≥ Viewer), the project-read gate — consistent
1602
+ with the Monte Carlo history read.
1603
+ """
1604
+
1605
+ serializer_class = ProjectForecastSnapshotSerializer
1606
+ # Route is `projects/<pk>/…`, so `pk` names the PROJECT here (#2745). Without
1607
+ # this the project-scoped classes below resolve nothing and `has_permission`
1608
+ # returns True for everyone — the gate reads as live in review and enforces
1609
+ # nothing. Declared per view because `pk` means something else on other routes.
1610
+ project_url_kwarg = "pk"
1611
+ permission_classes = [IsAuthenticated, IsProjectMember, IsProjectNotArchived]
1612
+
1613
+ def get_queryset(self) -> models.QuerySet[ProjectForecastSnapshot]:
1614
+ """Project-scoped, optionally date-bounded, newest-first."""
1615
+ project = get_object_or_404(Project, pk=self.kwargs["pk"], is_deleted=False)
1616
+ # IsProjectMember/IsProjectNotArchived are object-level — this list view has
1617
+ # no get_object(), so enforce them explicitly against the resolved project.
1618
+ self.check_object_permissions(self.request, project)
1619
+
1620
+ qs = ProjectForecastSnapshot.objects.filter(project_id=project.pk).order_by("-captured_at")
1621
+ since = self._parse_bound(self.request.query_params.get("since"))
1622
+ until = self._parse_bound(self.request.query_params.get("until"))
1623
+ if since is not None:
1624
+ qs = qs.filter(captured_at__gte=since)
1625
+ if until is not None:
1626
+ qs = qs.filter(captured_at__lte=until)
1627
+ return qs
1628
+
1629
+ @staticmethod
1630
+ def _parse_bound(raw: str | None) -> Any:
1631
+ """Parse an ISO date (documented) or full datetime to a timezone-aware bound.
1632
+
1633
+ A bare ``YYYY-MM-DD`` is the documented since/until format (#1378),
1634
+ interpreted as midnight in the default timezone; a full ISO datetime is
1635
+ still accepted. ``parse_datetime`` parses a date-only string into a *naive*
1636
+ midnight, so any naive result is made aware here — otherwise the bound
1637
+ would be compared naive against the aware ``captured_at`` column (a Django
1638
+ RuntimeWarning and a silent offset bug).
1639
+ """
1640
+ if not raw:
1641
+ return None
1642
+ dt = parse_datetime(raw)
1643
+ if dt is None:
1644
+ d = parse_date(raw)
1645
+ if d is None:
1646
+ return None
1647
+ dt = _datetime(d.year, d.month, d.day)
1648
+ if timezone.is_naive(dt):
1649
+ dt = timezone.make_aware(dt)
1650
+ return dt
1651
+
1652
+
1653
+ class FailedTaskPagination(PageNumberPagination):
1654
+ """Bounded page-number pagination for the dead-letter queue (#1317).
1655
+
1656
+ The list mixin already paged through the project default, but the bound was
1657
+ implicit; the dead-letter table can grow to thousands, so the cap is made
1658
+ explicit here. Page-number (not cursor) is retained deliberately — the
1659
+ inspector header shows a total ``count``, which CursorPagination omits.
1660
+ """
1661
+
1662
+ page_size = 50
1663
+ page_size_query_param = "page_size"
1664
+ max_page_size = 200
1665
+
1666
+
1667
+ @extend_schema_view(
1668
+ list=extend_schema(
1669
+ parameters=[
1670
+ OpenApiParameter(
1671
+ "status",
1672
+ str,
1673
+ description=(
1674
+ "Filter by status: dead, pending_retry, dismissed, retried. "
1675
+ "Invalid values are ignored (no filter)."
1676
+ ),
1677
+ ),
1678
+ OpenApiParameter(
1679
+ "task_name", str, description="Case-insensitive substring match on task_name."
1680
+ ),
1681
+ OpenApiParameter(
1682
+ "failed_after",
1683
+ str,
1684
+ description="ISO-8601; keep tasks with last_failed_at at or after this time.",
1685
+ ),
1686
+ OpenApiParameter(
1687
+ "failed_before",
1688
+ str,
1689
+ description="ISO-8601; keep tasks with last_failed_at at or before this time.",
1690
+ ),
1691
+ ],
1692
+ ),
1693
+ )
1694
+ class FailedTaskViewSet(IdempotencyMixin, ListModelMixin, RetrieveModelMixin, GenericViewSet): # type: ignore[type-arg]
1695
+ """Admin endpoint for dead-lettered Celery tasks.
1696
+
1697
+ List/detail/requeue/drop and the bulk ``requeue_all``/``drop_all``: admin users
1698
+ only. The serializer exposes tracebacks, args, and kwargs which may contain
1699
+ internal paths or partial secrets and must not be visible to unprivileged
1700
+ members.
1701
+
1702
+ The list endpoint backs the dead-letter inspector (#694, ADR-0172) and
1703
+ accepts read-only filters: ``?status=`` (one of the FailedTaskStatus
1704
+ values), ``?task_name=`` (case-insensitive substring), and
1705
+ ``?failed_after=`` / ``?failed_before=`` (ISO-8601, filtered on
1706
+ ``last_failed_at``). Results keep the model default ordering
1707
+ (``-last_failed_at``, newest failure first).
1708
+
1709
+ Write actions (#695, ADR-0210):
1710
+ - ``requeue`` re-enqueues a parked task with an operator-chosen backoff,
1711
+ round-tripping through the durable workflow backend (ADR-0080) rather than
1712
+ the old raw ``send_task`` side channel.
1713
+ - ``drop`` soft-removes a parked task (→ DISMISSED) with an optional audit
1714
+ note; the row is retained so the audit survives (ADR-0084 "no silent
1715
+ discards").
1716
+ - ``requeue_all`` / ``drop_all`` apply the same action across the *current
1717
+ filter set*, bounded to ``FAILED_TASK_BULK_ACTION_MAX``.
1718
+ """
1719
+
1720
+ serializer_class = FailedTaskSerializer
1721
+ permission_classes = [IsAdminUser]
1722
+ pagination_class = FailedTaskPagination
1723
+ queryset = FailedTask.objects.all()
1724
+
1725
+ def get_queryset(self) -> models.QuerySet[FailedTask]:
1726
+ """Apply the inspector's read-only filters to the dead-letter list.
1727
+
1728
+ Invalid filter values are ignored rather than raising, so a malformed
1729
+ bookmarked URL degrades to "no filter" instead of a 400 — an operator
1730
+ diagnosing an incident should never be blocked by a bad query string.
1731
+
1732
+ ``select_related('resolved_by')`` avoids an N+1 on the resolved-status list
1733
+ views (``?status=retried``/``dismissed``): the ``resolved_by_display``
1734
+ serializer field reads the operator FK, which would otherwise lazy-load
1735
+ once per row (ADR-0210 audit fields).
1736
+ """
1737
+ qs = FailedTask.objects.select_related("resolved_by")
1738
+
1739
+ status_filter = self.request.query_params.get("status")
1740
+ if status_filter in FailedTaskStatus.values:
1741
+ qs = qs.filter(status=status_filter)
1742
+
1743
+ task_name = self.request.query_params.get("task_name")
1744
+ if task_name:
1745
+ qs = qs.filter(task_name__icontains=task_name)
1746
+
1747
+ failed_after = parse_datetime(self.request.query_params.get("failed_after", ""))
1748
+ if failed_after is not None:
1749
+ qs = qs.filter(last_failed_at__gte=failed_after)
1750
+
1751
+ failed_before = parse_datetime(self.request.query_params.get("failed_before", ""))
1752
+ if failed_before is not None:
1753
+ qs = qs.filter(last_failed_at__lte=failed_before)
1754
+
1755
+ return qs
1756
+
1757
+ def _start_requeue_workflow(self, failed: FailedTask, backoff_seconds: int) -> str:
1758
+ """Start the durable requeue workflow for one task (ADR-0210 §1).
1759
+
1760
+ Routes the re-enqueue through the #652 outbox-composing workflow backend
1761
+ (``start_workflow``) rather than a raw ``send_task`` side channel, so a
1762
+ broker outage cannot silently drop the requeue. The idempotency key ties one
1763
+ requeue to one *observed failure* (``id`` + ``failure_count``): a
1764
+ double-clicked or replayed requeue collides on the key and returns the
1765
+ existing workflow instead of double-enqueuing.
1766
+ """
1767
+ return start_workflow(
1768
+ REQUEUE_WORKFLOW,
1769
+ {
1770
+ "failed_task_id": str(failed.id),
1771
+ "task_name": failed.task_name,
1772
+ "args": failed.args,
1773
+ "kwargs": failed.kwargs,
1774
+ "backoff_seconds": backoff_seconds,
1775
+ },
1776
+ idempotency_key=f"requeue:{failed.id}:{failed.failure_count}",
1777
+ )
1778
+
1779
+ @extend_schema(
1780
+ request=FailedTaskRequeueSerializer,
1781
+ responses={200: FailedTaskSerializer},
1782
+ summary="Requeue a dead-lettered task with an operator-chosen backoff",
1783
+ )
1784
+ @action(detail=True, methods=["post"], permission_classes=[IsAdminUser])
1785
+ def requeue(self, request: Request, pk: str | None = None) -> Response:
1786
+ """Re-enqueue a parked task via the durable workflow backend (ADR-0210).
1787
+
1788
+ Only ``dead``/``pending_retry`` tasks are requeueable; a terminal task is a
1789
+ 400. The re-enqueue is durable (workflow outbox); the ``backoff_seconds`` is
1790
+ a best-effort Celery countdown on the re-dispatched task.
1791
+ """
1792
+ failed = self.get_object()
1793
+ if failed.status not in _ACTIONABLE_FAILED_STATUSES:
1794
+ return Response(
1795
+ {"detail": f"Cannot requeue a task with status '{failed.status}'."},
1796
+ status=status.HTTP_400_BAD_REQUEST,
1797
+ )
1798
+ payload = FailedTaskRequeueSerializer(data=request.data)
1799
+ payload.is_valid(raise_exception=True)
1800
+ backoff_seconds = payload.validated_data["backoff_seconds"]
1801
+
1802
+ # Start the durable workflow first, then stamp the row: the side effect is the
1803
+ # durable part, so if the status update failed the workflow still ran and a
1804
+ # re-run dedupes on the idempotency key. Both commit together under
1805
+ # ATOMIC_REQUESTS, so a mid-action error rolls the whole thing back.
1806
+ workflow_id = self._start_requeue_workflow(failed, backoff_seconds)
1807
+ FailedTask.objects.filter(pk=failed.pk).update(
1808
+ status=FailedTaskStatus.RETRIED,
1809
+ resolved_by=request.user,
1810
+ resolved_at=timezone.now(),
1811
+ )
1812
+ failed.refresh_from_db()
1813
+ logger.info(
1814
+ "dead-letter requeue: task %s (%s) requeued by user %s, backoff=%ss, workflow=%s",
1815
+ failed.id,
1816
+ failed.task_name,
1817
+ getattr(request.user, "pk", None),
1818
+ backoff_seconds,
1819
+ workflow_id,
1820
+ )
1821
+ data = dict(FailedTaskSerializer(failed).data)
1822
+ data["workflow_id"] = workflow_id
1823
+ return Response(data)
1824
+
1825
+ @extend_schema(
1826
+ request=FailedTaskDropSerializer,
1827
+ responses={200: FailedTaskSerializer},
1828
+ summary="Drop (dismiss) a dead-lettered task with an optional audit note",
1829
+ )
1830
+ @action(detail=True, methods=["post"], permission_classes=[IsAdminUser])
1831
+ def drop(self, request: Request, pk: str | None = None) -> Response:
1832
+ """Soft-remove a parked task (→ DISMISSED) with an optional audit note.
1833
+
1834
+ The row is retained (not hard-deleted) so the note/operator/timestamp audit
1835
+ survives; it drops out of the operator's default ``dead``/``pending_retry``
1836
+ view. Re-dropping an already-dismissed task is an idempotent no-op.
1837
+ """
1838
+ failed = self.get_object()
1839
+ payload = FailedTaskDropSerializer(data=request.data)
1840
+ payload.is_valid(raise_exception=True)
1841
+ note = payload.validated_data["note"]
1842
+
1843
+ if failed.status == FailedTaskStatus.DISMISSED:
1844
+ return Response(FailedTaskSerializer(failed).data)
1845
+
1846
+ FailedTask.objects.filter(pk=failed.pk).update(
1847
+ status=FailedTaskStatus.DISMISSED,
1848
+ resolution_note=note,
1849
+ resolved_by=request.user,
1850
+ resolved_at=timezone.now(),
1851
+ )
1852
+ failed.refresh_from_db()
1853
+ logger.info(
1854
+ "dead-letter drop: task %s (%s) dropped by user %s%s",
1855
+ failed.id,
1856
+ failed.task_name,
1857
+ getattr(request.user, "pk", None),
1858
+ " with note" if note else "",
1859
+ )
1860
+ return Response(FailedTaskSerializer(failed).data)
1861
+
1862
+ @extend_schema(
1863
+ request=FailedTaskRequeueSerializer,
1864
+ responses={200: OpenApiResponse(description="{processed, matched, capped}")},
1865
+ summary="Requeue every actionable task in the current filter set (bounded)",
1866
+ )
1867
+ @action(
1868
+ detail=False, methods=["post"], url_path="requeue-all", permission_classes=[IsAdminUser]
1869
+ )
1870
+ def requeue_all(self, request: Request) -> Response:
1871
+ """Bulk-requeue the current filter set, bounded (ADR-0210 §4).
1872
+
1873
+ Applies the inspector's ``get_queryset`` filters, restricts to actionable
1874
+ (``dead``/``pending_retry``) tasks, and processes at most
1875
+ ``FAILED_TASK_BULK_ACTION_MAX`` (oldest-first). ``capped`` in the response
1876
+ signals that more remain and the operator should repeat.
1877
+ """
1878
+ payload = FailedTaskRequeueSerializer(data=request.data)
1879
+ payload.is_valid(raise_exception=True)
1880
+ backoff_seconds = payload.validated_data["backoff_seconds"]
1881
+
1882
+ qs = self.get_queryset().filter(status__in=_ACTIONABLE_FAILED_STATUSES)
1883
+ matched = qs.count()
1884
+ batch = list(qs.order_by("last_failed_at")[:FAILED_TASK_BULK_ACTION_MAX])
1885
+ for failed in batch:
1886
+ self._start_requeue_workflow(failed, backoff_seconds)
1887
+ if batch:
1888
+ FailedTask.objects.filter(pk__in=[f.pk for f in batch]).update(
1889
+ status=FailedTaskStatus.RETRIED,
1890
+ resolved_by=request.user,
1891
+ resolved_at=timezone.now(),
1892
+ )
1893
+ logger.info(
1894
+ "dead-letter requeue_all: %d of %d task(s) requeued by user %s, backoff=%ss",
1895
+ len(batch),
1896
+ matched,
1897
+ getattr(request.user, "pk", None),
1898
+ backoff_seconds,
1899
+ )
1900
+ return Response(
1901
+ {
1902
+ "processed": len(batch),
1903
+ "matched": matched,
1904
+ "capped": matched > FAILED_TASK_BULK_ACTION_MAX,
1905
+ }
1906
+ )
1907
+
1908
+ @extend_schema(
1909
+ request=FailedTaskDropSerializer,
1910
+ responses={200: OpenApiResponse(description="{processed, matched, capped}")},
1911
+ summary="Drop every task in the current filter set (bounded)",
1912
+ )
1913
+ @action(detail=False, methods=["post"], url_path="drop-all", permission_classes=[IsAdminUser])
1914
+ def drop_all(self, request: Request) -> Response:
1915
+ """Bulk-drop the current filter set, bounded (ADR-0210 §4).
1916
+
1917
+ Applies the inspector's ``get_queryset`` filters, excludes already-dismissed
1918
+ rows, and dismisses at most ``FAILED_TASK_BULK_ACTION_MAX`` (oldest-first) in
1919
+ a single bounded ``UPDATE`` — no per-row loop. ``capped`` signals more remain.
1920
+ """
1921
+ payload = FailedTaskDropSerializer(data=request.data)
1922
+ payload.is_valid(raise_exception=True)
1923
+ note = payload.validated_data["note"]
1924
+
1925
+ qs = self.get_queryset().exclude(status=FailedTaskStatus.DISMISSED)
1926
+ matched = qs.count()
1927
+ ids = list(
1928
+ qs.order_by("last_failed_at").values_list("pk", flat=True)[:FAILED_TASK_BULK_ACTION_MAX]
1929
+ )
1930
+ processed = 0
1931
+ if ids:
1932
+ processed = FailedTask.objects.filter(pk__in=ids).update(
1933
+ status=FailedTaskStatus.DISMISSED,
1934
+ resolution_note=note,
1935
+ resolved_by=request.user,
1936
+ resolved_at=timezone.now(),
1937
+ )
1938
+ logger.info(
1939
+ "dead-letter drop_all: %d of %d task(s) dropped by user %s",
1940
+ processed,
1941
+ matched,
1942
+ getattr(request.user, "pk", None),
1943
+ )
1944
+ return Response(
1945
+ {
1946
+ "processed": processed,
1947
+ "matched": matched,
1948
+ "capped": matched > FAILED_TASK_BULK_ACTION_MAX,
1949
+ }
1950
+ )
1951
+
1952
+
1953
+ # ---------------------------------------------------------------------------
1954
+ # Velocity suggestions (ADR-0065)
1955
+ # ---------------------------------------------------------------------------
1956
+
1957
+
1958
+ @extend_schema_view(
1959
+ list=extend_schema(
1960
+ parameters=[
1961
+ OpenApiParameter(
1962
+ "task",
1963
+ OpenApiTypes.UUID,
1964
+ location=OpenApiParameter.QUERY,
1965
+ required=False,
1966
+ description="Filter to velocity suggestions for this task.",
1967
+ ),
1968
+ OpenApiParameter(
1969
+ "pending",
1970
+ OpenApiTypes.BOOL,
1971
+ location=OpenApiParameter.QUERY,
1972
+ required=False,
1973
+ description=(
1974
+ "When true, restrict to suggestions awaiting a decision "
1975
+ "(neither accepted nor dismissed)."
1976
+ ),
1977
+ ),
1978
+ ],
1979
+ ),
1980
+ )
1981
+ class VelocitySuggestionViewSet(
1982
+ IdempotencyMixin,
1983
+ ListModelMixin,
1984
+ RetrieveModelMixin,
1985
+ GenericViewSet[VelocitySuggestion],
1986
+ ):
1987
+ """Velocity-calibration suggestions surfaced to the PM (ADR-0065).
1988
+
1989
+ Lifecycle:
1990
+ - sprint close generates a row per task in the closing sprint via
1991
+ ``compute_velocity_suggestions``
1992
+ - the PM accepts (writes ``most_likely_duration`` + enqueues
1993
+ ScheduleRequest) or dismisses (audit-only stamp) from the Task Detail
1994
+ Drawer
1995
+ - both terminal decisions are non-destructive: the row is preserved for
1996
+ audit; subsequent sprint closes may add new rows (one per task per
1997
+ sprint) but cannot overwrite a settled decision.
1998
+
1999
+ Auth model:
2000
+ - list / retrieve: any project member (Viewer+) — read access is fine
2001
+ because the surface is informational
2002
+ - accept / dismiss: PM or above (the action either writes a CPM input or
2003
+ records a governance decision; either way it's PM-scope)
2004
+
2005
+ Filtering: ``?task=<task_id>`` is the primary filter the drawer uses.
2006
+ ``?pending=true`` restricts to suggestions awaiting a decision.
2007
+ """
2008
+
2009
+ serializer_class = VelocitySuggestionSerializer
2010
+ permission_classes = [IsAuthenticated]
2011
+ queryset = VelocitySuggestion.objects.all()
2012
+
2013
+ def get_queryset(self) -> models.QuerySet[VelocitySuggestion]:
2014
+ qs = (
2015
+ VelocitySuggestion.objects.select_related("task", "sprint")
2016
+ .filter(task__is_deleted=False)
2017
+ .order_by("-created_at")
2018
+ )
2019
+
2020
+ task_id = self.request.query_params.get("task")
2021
+ if task_id:
2022
+ qs = qs.filter(task_id=task_id)
2023
+
2024
+ if self.request.query_params.get("pending", "").lower() == "true":
2025
+ qs = qs.filter(accepted_at__isnull=True, dismissed_at__isnull=True)
2026
+
2027
+ # Membership gate: only return rows whose task belongs to a project the
2028
+ # caller is a member of. We rely on the access app's project-membership
2029
+ # subquery rather than per-row checks so the list endpoint stays fast.
2030
+ # IsAuthenticated excludes AnonymousUser before this runs; the isinstance
2031
+ # guard is there to narrow the type for mypy.
2032
+ from django.contrib.auth.models import AbstractBaseUser
2033
+
2034
+ from trueppm_api.apps.access.models import ProjectMembership
2035
+
2036
+ user = self.request.user
2037
+ if not isinstance(user, AbstractBaseUser):
2038
+ return qs.none()
2039
+ # is_deleted=False (#819): without this, a user whose membership was
2040
+ # soft-deleted still sees velocity suggestions for that project via the
2041
+ # list endpoint. The accept/dismiss actions go through IsProjectAdmin
2042
+ # which already filters soft-deleted, so the write path is safe — only
2043
+ # the list path was leaking.
2044
+ member_project_ids = ProjectMembership.objects.filter(
2045
+ user=user, is_deleted=False
2046
+ ).values_list("project_id", flat=True)
2047
+ qs = qs.filter(task__project_id__in=member_project_ids)
2048
+ return qs
2049
+
2050
+ @staticmethod
2051
+ def _broadcast_settled(project_id: Any, suggestion_pk: Any, event_type: str) -> None:
2052
+ """Announce that a velocity suggestion was accepted or dismissed (#2845).
2053
+
2054
+ Both decisions mutate shared state a collaborator has on screen — the
2055
+ suggestion disappears from the pending list for everyone — and neither
2056
+ emitted anything before. Deferred to commit and built from plain scalars so
2057
+ the closure never re-reads an ORM instance (broadcast-check H-1). The payload
2058
+ is ID-only: a client re-reads through the serializer, which re-applies the
2059
+ ADR-0104 velocity gate the response itself goes through.
2060
+ """
2061
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
2062
+
2063
+ project_id_str = str(project_id)
2064
+ suggestion_id_str = str(suggestion_pk)
2065
+ transaction.on_commit(
2066
+ lambda: broadcast_board_event(project_id_str, event_type, {"id": suggestion_id_str})
2067
+ )
2068
+
2069
+ # ``request=None`` asserted rather than inferred (#2840): both decisions are
2070
+ # carried by the URL alone. The pre-fix schema published no requestBody here
2071
+ # only because VelocitySuggestionSerializer exposes no writable field — an
2072
+ # accident of the fallback that any future writable field would have reversed.
2073
+ # ``responses`` names the 409 the idempotency guards return so a client is not
2074
+ # left inferring it from the prose.
2075
+ @extend_schema(
2076
+ summary="Accept a velocity suggestion",
2077
+ request=None,
2078
+ responses={
2079
+ 200: VelocitySuggestionSerializer,
2080
+ 409: OpenApiResponse(description="Suggestion has already been dismissed."),
2081
+ 422: OpenApiResponse(
2082
+ description="Accepting would violate the task's three-point estimate ordering."
2083
+ ),
2084
+ },
2085
+ )
2086
+ @action(
2087
+ detail=True,
2088
+ methods=["post"],
2089
+ permission_classes=[IsAuthenticated, IsProjectAdmin, IsProjectNotArchived],
2090
+ )
2091
+ def accept(self, request: Request, pk: str | None = None) -> Response:
2092
+ """Apply the suggested duration to the task and enqueue a CPM recompute.
2093
+
2094
+ Idempotent: a suggestion that is already accepted returns 200 with the
2095
+ existing row. Re-applying after dismiss is rejected with 409 so the
2096
+ audit trail of the original decision is preserved.
2097
+ """
2098
+ suggestion = self.get_object()
2099
+ # Object-level permission keys off the task's project.
2100
+ self.check_object_permissions(request, suggestion.task)
2101
+
2102
+ if suggestion.accepted_at is not None:
2103
+ # get_serializer injects request context so the serializer's ADR-0104
2104
+ # velocity gate fires on these action responses too (#949).
2105
+ return Response(self.get_serializer(suggestion).data)
2106
+ if suggestion.dismissed_at is not None:
2107
+ return Response(
2108
+ {"detail": "Suggestion has already been dismissed."},
2109
+ status=status.HTTP_409_CONFLICT,
2110
+ )
2111
+
2112
+ task = suggestion.task
2113
+ project_id = task.project_id
2114
+
2115
+ # A velocity suggestion writes most_likely_duration alone. When the task
2116
+ # already carries a complete three-point estimate, overwriting the middle
2117
+ # value can break the optimistic <= most_likely <= pessimistic invariant
2118
+ # the scheduler enforces — the invalid triple then detonates the next
2119
+ # CPM/program recompute instead of failing here (#2002). Refuse so the PM
2120
+ # adjusts the optimistic/pessimistic estimates rather than corrupting them
2121
+ # silently. No-op for the common case where opt/pess are unset.
2122
+ if not three_point_estimates_ordered(
2123
+ task.optimistic_duration,
2124
+ suggestion.suggested_duration,
2125
+ task.pessimistic_duration,
2126
+ ):
2127
+ return Response(
2128
+ {
2129
+ "detail": (
2130
+ "Accepting this suggestion would set most likely duration to "
2131
+ f"{suggestion.suggested_duration} days, which violates this "
2132
+ "task's three-point estimate ordering (optimistic ≤ most "
2133
+ f"likely ≤ pessimistic; optimistic is {task.optimistic_duration}, "
2134
+ f"pessimistic is {task.pessimistic_duration}). Adjust the "
2135
+ "optimistic/pessimistic estimates first."
2136
+ )
2137
+ },
2138
+ status=status.HTTP_422_UNPROCESSABLE_ENTITY,
2139
+ )
2140
+
2141
+ with transaction.atomic():
2142
+ task.most_likely_duration = suggestion.suggested_duration
2143
+ task.save(update_fields=["most_likely_duration"])
2144
+ VelocitySuggestion.objects.filter(pk=suggestion.pk).update(
2145
+ accepted_at=timezone.now(),
2146
+ accepted_by=request.user,
2147
+ )
2148
+ # CPM cascade: the new most_likely_duration shifts the Monte Carlo
2149
+ # forecast on the next run. Enqueue inside the transaction so the
2150
+ # request is visible to the drain only after the task save commits.
2151
+ transaction.on_commit(
2152
+ lambda: enqueue_recalculate(
2153
+ str(project_id),
2154
+ reason=ScheduleRequestReason.TASK_CHANGE,
2155
+ )
2156
+ )
2157
+ # #2845: the recalc above does NOT cover this write. most_likely_duration
2158
+ # is a Monte Carlo input and is absent from _CPM_DELTA_FIELDS, so the
2159
+ # recalc's task_dates_updated delta — built from the subset of tasks whose
2160
+ # _CPM_DELTA_FIELDS actually moved — will not carry this task unless its
2161
+ # deterministic CPM output happens to shift for an unrelated reason. And
2162
+ # cpm_complete, which does fire unconditionally, is explicitly documented
2163
+ # on the client as pill-and-stats only ("the tasks cache is maintained by
2164
+ # task_dates_updated", ADR-0091). So there was no live-update path of any
2165
+ # kind for a field a collaborator can see change.
2166
+ #
2167
+ # Two events, because two things changed: the task's own field (the
2168
+ # canonical ADR-0152 delta, which the existing frontend handler already
2169
+ # knows how to apply) and the suggestion row settling.
2170
+ #
2171
+ # Scalars snapshotted before the closure, and both deferred to commit —
2172
+ # broadcast_task_updated is best-effort and its docstring requires the
2173
+ # caller to wrap it (broadcast-check H-1).
2174
+ from trueppm_api.apps.sync.broadcast import broadcast_task_updated
2175
+
2176
+ project_id_str = str(project_id)
2177
+ task_id_str = str(task.pk)
2178
+ task_version = task.server_version
2179
+ actor_id_str = str(request.user.pk)
2180
+ transaction.on_commit(
2181
+ lambda: broadcast_task_updated(
2182
+ project_id_str,
2183
+ task_id=task_id_str,
2184
+ changed_fields=["most_likely_duration"],
2185
+ version=task_version,
2186
+ actor_id=actor_id_str,
2187
+ )
2188
+ )
2189
+ self._broadcast_settled(project_id, suggestion.pk, "velocity_suggestion_accepted")
2190
+
2191
+ suggestion.refresh_from_db()
2192
+ # get_serializer injects request context so the serializer's ADR-0104
2193
+ # velocity gate fires on these action responses too (#949).
2194
+ return Response(self.get_serializer(suggestion).data)
2195
+
2196
+ @extend_schema(
2197
+ summary="Dismiss a velocity suggestion",
2198
+ request=None,
2199
+ responses={
2200
+ 200: VelocitySuggestionSerializer,
2201
+ 409: OpenApiResponse(description="Suggestion has already been accepted."),
2202
+ },
2203
+ )
2204
+ @action(
2205
+ detail=True,
2206
+ methods=["post"],
2207
+ permission_classes=[IsAuthenticated, IsProjectAdmin, IsProjectNotArchived],
2208
+ )
2209
+ def dismiss(self, request: Request, pk: str | None = None) -> Response:
2210
+ """Mark a suggestion as dismissed without touching the task.
2211
+
2212
+ Idempotent: a suggestion that is already dismissed returns 200 with the
2213
+ existing row. Dismissing after accept is rejected with 409 to preserve
2214
+ the original decision.
2215
+ """
2216
+ suggestion = self.get_object()
2217
+ self.check_object_permissions(request, suggestion.task)
2218
+
2219
+ if suggestion.dismissed_at is not None:
2220
+ # get_serializer injects request context so the serializer's ADR-0104
2221
+ # velocity gate fires on these action responses too (#949).
2222
+ return Response(self.get_serializer(suggestion).data)
2223
+ if suggestion.accepted_at is not None:
2224
+ return Response(
2225
+ {"detail": "Suggestion has already been accepted."},
2226
+ status=status.HTTP_409_CONFLICT,
2227
+ )
2228
+
2229
+ with transaction.atomic():
2230
+ VelocitySuggestion.objects.filter(pk=suggestion.pk).update(
2231
+ dismissed_at=timezone.now(),
2232
+ dismissed_by=request.user,
2233
+ )
2234
+ # #2845: dismissing removes the row from every other member's pending
2235
+ # list. Wrapped in atomic() so the on_commit registration inside
2236
+ # _broadcast_settled has a transaction to hang off — outside one it would
2237
+ # fire immediately, before the UPDATE is durable.
2238
+ self._broadcast_settled(
2239
+ suggestion.task.project_id, suggestion.pk, "velocity_suggestion_dismissed"
2240
+ )
2241
+ suggestion.refresh_from_db()
2242
+ # get_serializer injects request context so the serializer's ADR-0104
2243
+ # velocity gate fires on these action responses too (#949).
2244
+ return Response(self.get_serializer(suggestion).data)
2245
+
2246
+
2247
+ # ---------------------------------------------------------------------------
2248
+ # Schedule value derivation (ADR-0218, #1058)
2249
+ # ---------------------------------------------------------------------------
2250
+
2251
+ # The CPM quantities the derivation endpoint can explain. Mirrors
2252
+ # trueppm_scheduler.Quantity so the API contract and the engine cannot drift.
2253
+ # scheduled_start (ADR-0752) is included so a consumer — human or MCP client —
2254
+ # can ask "why does this task's SPAN start here", not only its remaining-work
2255
+ # window; scheduled_finish is deliberately NOT a member (it is always
2256
+ # identical to early_finish, so asking for it twice would invite two answers).
2257
+ _CPM_DERIVATION_QUANTITIES = frozenset(
2258
+ {
2259
+ "early_start",
2260
+ "early_finish",
2261
+ "late_start",
2262
+ "late_finish",
2263
+ "total_float",
2264
+ "free_float",
2265
+ "scheduled_start",
2266
+ }
2267
+ )
2268
+ # The Monte Carlo percentile quantities, whose derivation is the risk premium over
2269
+ # the deterministic CPM finish plus the ADR-0140 sensitivity drivers (#987).
2270
+ _MC_DERIVATION_QUANTITIES = frozenset({"p50", "p80", "p95"})
2271
+
2272
+
2273
+ def _build_cpm_sched_project(project: Project, pk: str) -> Any:
2274
+ """Assemble the scheduler ``Project`` for a deterministic CPM derivation run.
2275
+
2276
+ Mirrors the input construction of ``scheduling.tasks._run_schedule`` — the
2277
+ **deterministic pass that computes the stored schedule** — through the same shared
2278
+ converters (``compose_project_calendar`` / ``build_sched_tasks`` /
2279
+ ``build_sched_graph``), the same committed-only task set, the same
2280
+ cross-project/non-committed edge drop, and the same data-date and velocity inputs.
2281
+ A derivation explains a value a user is reading off a task row, and that value came
2282
+ from ``_run_schedule``; matching anything else explains a network nobody was shown.
2283
+
2284
+ This docstring used to name :func:`run_monte_carlo` as the thing to mirror, which
2285
+ is how it inherited that endpoint's defect wholesale: before #3527 neither applied
2286
+ the ADR-0105 summary strip, so the mirror was faithful and both were wrong. Naming
2287
+ the deterministic pass instead makes the next drift detectable, because
2288
+ ``_run_schedule`` is the only one of the three whose output is persisted and
2289
+ therefore independently checkable.
2290
+
2291
+ A summary row is consequently absent from the returned graph, and a derivation
2292
+ request naming one now gets the ``UnknownTaskError`` 404 — correct, because a
2293
+ summary's dates are rolled up from its leaves and were never produced by a CPM pass
2294
+ that could be explained.
2295
+ """
2296
+ from trueppm_scheduler.models import Project as SchedProject
2297
+
2298
+ from trueppm_api.apps.projects.services import scheduler_velocity_inputs
2299
+
2300
+ sched_calendar = compose_project_calendar(project)
2301
+ db_tasks = list(Task.committed.filter(project=project).select_related("sprint"))
2302
+ suggest_approve = project.estimation_mode == EstimationMode.SUGGEST_APPROVE
2303
+ sched_tasks = build_sched_tasks(db_tasks, suggest_approve=suggest_approve)
2304
+
2305
+ included_ids = {str(t.id) for t in db_tasks}
2306
+ # Was a second, byte-identical copy of _build_sched_deps' body (#3527). Behaviour
2307
+ # was the same, so nothing was wrong today — but a duplicated edge filter is the
2308
+ # very drift class this issue is an instance of, and the next change to the edge
2309
+ # rules (soft-deleted dependencies, #3532) would have had to find both.
2310
+ #
2311
+ # #3532 is that next change, and it landed on the deduplicated shape: the
2312
+ # soft-delete filter lives once, in _build_sched_deps' Dependency.live read, and
2313
+ # the derivation inherits it here rather than carrying its own copy.
2314
+ sched_deps = _build_sched_deps(pk, included_ids)
2315
+
2316
+ velocity_samples, sprint_length_days = scheduler_velocity_inputs(
2317
+ project.pk, sched_calendar.working_days
2318
+ )
2319
+
2320
+ graph = build_sched_graph(db_tasks, sched_tasks, sched_deps)
2321
+
2322
+ return SchedProject(
2323
+ id=str(project.pk),
2324
+ name=project.name,
2325
+ start_date=project.start_date,
2326
+ tasks=graph.tasks,
2327
+ dependencies=graph.dependencies,
2328
+ calendar=sched_calendar,
2329
+ status_date=resolve_cpm_status_date(project.status_date),
2330
+ velocity_samples=velocity_samples or None,
2331
+ sprint_length_days=sprint_length_days,
2332
+ )
2333
+
2334
+
2335
+ class ScheduleDerivationView(McpReadableViewMixin, APIView):
2336
+ """The server-computed *why* behind a computed schedule value (ADR-0218, #1058).
2337
+
2338
+ ``GET /projects/<pk>/schedule/derivation/?task_id=<id>&quantity=<quantity>``
2339
+
2340
+ Returns the derivation of a single computed value — the driving predecessor/
2341
+ successor chain, the binding constraint, each term's lag and calendar-snap
2342
+ contribution, and which CPM pass (forward/backward/float) set it. The
2343
+ derivation is computed server-side from the engine's own pass data by
2344
+ :func:`trueppm_scheduler.derive_value`; it is never recomputed in the browser
2345
+ and nothing is fabricated (rule 120) — a contribution is emitted only for a
2346
+ constraint the engine actually evaluates.
2347
+
2348
+ For a Monte Carlo percentile quantity (``p50``/``p80``/``p95``) the "why" is
2349
+ the deterministic ``cpm_finish``, the signed ``delta_vs_cpm`` risk premium, and
2350
+ the ADR-0140 sensitivity drivers of the latest persisted run (#987) — the
2351
+ existing engine output surfaced honestly, not a second recomputation.
2352
+
2353
+ RBAC: any project member (Viewer+) may read a derivation; ``McpReadableViewMixin``
2354
+ additionally exposes it to an ``mcp:read`` API token confined to safe methods,
2355
+ so an AI/MCP agent can cite the *why* alongside the value.
2356
+ """
2357
+
2358
+ # ADR-0678 (#2482): projects/<pk>/schedule/derivation/
2359
+ mcp_scope = McpScope.PATH
2360
+
2361
+ # Route is `projects/<pk>/…`, so `pk` names the PROJECT here (#2745). Without
2362
+ # this the project-scoped classes below resolve nothing and `has_permission`
2363
+ # returns True for everyone — the gate reads as live in review and enforces
2364
+ # nothing. Declared per view because `pk` means something else on other routes.
2365
+ project_url_kwarg = "pk"
2366
+ permission_classes = [IsAuthenticated, IsProjectMember, IsProjectNotArchived]
2367
+
2368
+ @extend_schema(
2369
+ operation_id="project_schedule_derivation",
2370
+ summary="Derivation (the why) of a computed schedule value",
2371
+ parameters=[
2372
+ OpenApiParameter(
2373
+ name="task_id",
2374
+ type=OpenApiTypes.STR,
2375
+ location=OpenApiParameter.QUERY,
2376
+ required=True,
2377
+ description="The task whose computed value is being explained.",
2378
+ ),
2379
+ OpenApiParameter(
2380
+ name="quantity",
2381
+ type=OpenApiTypes.STR,
2382
+ location=OpenApiParameter.QUERY,
2383
+ required=True,
2384
+ description=(
2385
+ "Which computed value to explain: a CPM quantity "
2386
+ "(early_start, early_finish, late_start, late_finish, "
2387
+ "total_float, free_float, scheduled_start) or a Monte Carlo "
2388
+ "percentile (p50, p80, p95). CPM quantities return {task_id, task_name, "
2389
+ "quantity, value, pass, is_critical, binding, contributions[]}, "
2390
+ "each contribution carrying its source task, dep_type, lag_days, "
2391
+ "imposed_date, calendar_days_added, slack_days, and is_binding. "
2392
+ "Percentiles return {quantity, value, cpm_finish, "
2393
+ "delta_vs_cpm_days, drivers[]} from the latest simulation."
2394
+ ),
2395
+ ),
2396
+ ],
2397
+ responses={
2398
+ 200: OpenApiResponse(
2399
+ description=(
2400
+ "The derivation of the requested value. The Monte Carlo quantities "
2401
+ "(p50/p80/p95) additionally carry forecast_staleness "
2402
+ "(current|project_changed|aged|unknown), plan_version and "
2403
+ "plan_version_current (#3140), so a cited percentile states whether "
2404
+ "the run it comes from still describes the current plan rather than "
2405
+ "presenting a superseded value with full derivation confidence. "
2406
+ "`project_changed` means the project was written to (or its CPM "
2407
+ "output recomputed) since the run — grounds for rerunning, NOT "
2408
+ "evidence that a schedule date changed."
2409
+ )
2410
+ ),
2411
+ 400: OpenApiResponse(
2412
+ description="Missing/unknown quantity, or invalid schedule input."
2413
+ ),
2414
+ 404: OpenApiResponse(
2415
+ description="Unknown project or task, or no simulation available."
2416
+ ),
2417
+ },
2418
+ )
2419
+ def get(self, request: Request, pk: str) -> Response:
2420
+ from trueppm_scheduler.derive import UnknownTaskError, derive_value
2421
+ from trueppm_scheduler.engine import CyclicDependencyError
2422
+
2423
+ quantity = request.query_params.get("quantity")
2424
+ if not quantity:
2425
+ return Response(
2426
+ {"detail": "The 'quantity' query parameter is required."},
2427
+ status=status.HTTP_400_BAD_REQUEST,
2428
+ )
2429
+ if quantity not in _CPM_DERIVATION_QUANTITIES and quantity not in _MC_DERIVATION_QUANTITIES:
2430
+ allowed = ", ".join(sorted(_CPM_DERIVATION_QUANTITIES | _MC_DERIVATION_QUANTITIES))
2431
+ return Response(
2432
+ {"detail": f"Unknown quantity {quantity!r}; must be one of: {allowed}."},
2433
+ status=status.HTTP_400_BAD_REQUEST,
2434
+ )
2435
+
2436
+ project = get_object_or_404(
2437
+ Project.objects.select_related("calendar", "program__calendar").prefetch_related(
2438
+ "tasks",
2439
+ "calendar__exceptions",
2440
+ "calendar_layers__calendar__exceptions",
2441
+ # ADR-0441: the resolver reads the program calendar's exceptions when a
2442
+ # project inherits its base calendar from the program.
2443
+ "program__calendar__exceptions",
2444
+ ),
2445
+ pk=pk,
2446
+ is_deleted=False,
2447
+ )
2448
+ # 404 (not 403) for a non-member: the object-scope oracle keeps a project's
2449
+ # existence from leaking to a non-member (mirrors MonteCarloLatestView).
2450
+ self.check_object_permissions(request, project)
2451
+
2452
+ if quantity in _MC_DERIVATION_QUANTITIES:
2453
+ return self._monte_carlo_derivation(project, quantity)
2454
+
2455
+ task_id = request.query_params.get("task_id")
2456
+ if not task_id:
2457
+ return Response(
2458
+ {"detail": "The 'task_id' query parameter is required for a CPM quantity."},
2459
+ status=status.HTTP_400_BAD_REQUEST,
2460
+ )
2461
+
2462
+ # _build_cpm_sched_project now shapes the graph (#3527), so it can raise the
2463
+ # engine's InvalidScheduleInput. It is inside the try for the same reason
2464
+ # derive_value is: an unguarded ValueError here becomes a 500, and this view
2465
+ # already documents a 400 for "invalid schedule input".
2466
+ try:
2467
+ sched_project = _build_cpm_sched_project(project, pk)
2468
+ if not sched_project.tasks:
2469
+ return Response(
2470
+ {"detail": "Project has no committed tasks to schedule."},
2471
+ status=status.HTTP_404_NOT_FOUND,
2472
+ )
2473
+ derivation = derive_value(sched_project, task_id, quantity)
2474
+ except UnknownTaskError:
2475
+ return Response(
2476
+ {"detail": f"Task {task_id!r} is not in the scheduled network."},
2477
+ status=status.HTTP_404_NOT_FOUND,
2478
+ )
2479
+ except (CyclicDependencyError, ValueError) as exc:
2480
+ # codeql[py/stack-trace-exposure] -- intentional user-facing validation message
2481
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
2482
+ except OverflowError:
2483
+ return Response(
2484
+ {"detail": _DATE_RANGE_EXCEEDED_DETAIL},
2485
+ status=status.HTTP_400_BAD_REQUEST,
2486
+ )
2487
+ return Response(derivation.to_dict())
2488
+
2489
+ def _monte_carlo_derivation(self, project: Project, quantity: str) -> Response:
2490
+ """Derive a Monte Carlo percentile from the latest run (#987).
2491
+
2492
+ The percentile's "why" is the deterministic ``cpm_finish`` it is measured
2493
+ against, the signed ``delta_vs_cpm`` days of risk premium, and the ADR-0140
2494
+ sensitivity drivers (the tasks whose duration most moves the finish). All
2495
+ three are already computed on the run — this surfaces them, it does not
2496
+ recompute the forecast.
2497
+
2498
+ Reads the shared ``mc_latest`` cache first, falling back to the most recent
2499
+ persisted ``MonteCarloRun`` — the same order as ``MonteCarloLatestView``.
2500
+ The cache-first read matters since #1502: a Member/Viewer-triggered run
2501
+ refreshes the cache but persists no attributed row, and the derivation is
2502
+ part of the open read surface, so it must see cache-only forecasts.
2503
+ """
2504
+ # This endpoint exists so an agent can cite the *why* beside the value
2505
+ # (ADR-0218). A percentile whose run predates the current plan is a stale
2506
+ # citation delivered with full derivation confidence, so the staleness
2507
+ # discriminant travels with the derivation too (#3140) — otherwise
2508
+ # `get_monte_carlo_forecast` and `get_schedule_derivation` report opposite
2509
+ # trustworthiness for one run.
2510
+ # Read off the project `get()` already loaded — it is fetched without
2511
+ # `.only()`/`.defer()`, so both columns are in memory and this costs nothing.
2512
+ # `_current_plan_state` exists for the caller that does NOT hold the row.
2513
+ pk = project.pk
2514
+ plan_version_current = project.last_sync_version
2515
+ recalculated_at = project.recalculated_at
2516
+ today = timezone.localdate()
2517
+ cached = cache.get(mc_latest_cache_key(pk))
2518
+ if cached is not None:
2519
+ return Response(
2520
+ {
2521
+ "quantity": quantity,
2522
+ "value": cached.get(quantity),
2523
+ "pass": "monte_carlo",
2524
+ "cpm_finish": cached.get("cpm_finish"),
2525
+ "delta_vs_cpm_days": (cached.get("delta_vs_cpm") or {}).get(quantity),
2526
+ "drivers": cached.get("sensitivity", []),
2527
+ "runs": cached.get("runs"),
2528
+ "last_run_at": cached.get("last_run_at"),
2529
+ **forecast_staleness_for_payload(
2530
+ cached,
2531
+ plan_version_current=plan_version_current,
2532
+ recalculated_at=recalculated_at,
2533
+ today=today,
2534
+ ),
2535
+ }
2536
+ )
2537
+ latest = MonteCarloRun.objects.filter(project_id=pk).order_by("-taken_at").first()
2538
+ if latest is None:
2539
+ return Response(
2540
+ {"detail": "No simulation result available; run a Monte Carlo forecast first."},
2541
+ status=status.HTTP_404_NOT_FOUND,
2542
+ )
2543
+ percentile_date = {"p50": latest.p50, "p80": latest.p80, "p95": latest.p95}[quantity]
2544
+ dist = latest.distribution or {}
2545
+ return Response(
2546
+ {
2547
+ "quantity": quantity,
2548
+ "value": percentile_date.isoformat() if percentile_date else None,
2549
+ "pass": "monte_carlo",
2550
+ "cpm_finish": latest.cpm_finish.isoformat() if latest.cpm_finish else None,
2551
+ "delta_vs_cpm_days": _delta_vs_cpm_days(percentile_date, latest.cpm_finish),
2552
+ # ADR-0140 tornado: the tasks whose duration variance drives the
2553
+ # finish — the honest "why" behind a probabilistic date.
2554
+ "drivers": dist.get("sensitivity", []),
2555
+ "runs": latest.n_simulations,
2556
+ "last_run_at": latest.taken_at.isoformat(),
2557
+ **forecast_staleness_from_run(
2558
+ latest,
2559
+ plan_version_current=plan_version_current,
2560
+ recalculated_at=recalculated_at,
2561
+ today=today,
2562
+ ),
2563
+ }
2564
+ )