@delmaredigital/payload-experiments 0.4.1 → 0.5.1

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 (310) hide show
  1. package/README.md +9 -5
  2. package/dist/admin/blocks/model.js +2 -0
  3. package/dist/admin/copy/blocks.d.ts +1 -0
  4. package/dist/admin/copy/blocks.js +1 -0
  5. package/dist/admin/copy/status.d.ts +3 -0
  6. package/dist/admin/copy/status.js +3 -0
  7. package/dist/admin/placementStatus.model.js +3 -0
  8. package/dist/admin/status.model.d.ts +3 -2
  9. package/dist/admin/status.model.js +9 -3
  10. package/dist/admin/surface/ResultsRoute.js +2 -1
  11. package/dist/admin/surface/TestsHome.d.ts +2 -1
  12. package/dist/admin/surface/TestsHome.js +31 -11
  13. package/dist/admin/surface/TestsSurface.js +4 -0
  14. package/dist/admin/surface/home.model.d.ts +11 -6
  15. package/dist/admin/surface/home.model.js +19 -8
  16. package/dist/admin/surface/newTest/PageWizard.js +13 -3
  17. package/dist/admin/surface/results/ResultsHeader.js +43 -9
  18. package/dist/admin/surface/test/TestPage.js +11 -1
  19. package/dist/admin/useLayerUsage.d.ts +1 -1
  20. package/dist/admin/views/buildSurfaceProps.js +3 -0
  21. package/dist/blocks/placementLocale.d.ts +14 -0
  22. package/dist/blocks/placementLocale.js +80 -13
  23. package/dist/blocks/placementPublication.d.ts +14 -0
  24. package/dist/blocks/placementPublication.js +24 -0
  25. package/dist/cohorts/build.d.ts +35 -0
  26. package/dist/cohorts/build.js +134 -0
  27. package/dist/cohorts/key.d.ts +12 -0
  28. package/dist/cohorts/key.js +15 -0
  29. package/dist/cohorts/maintenance.d.ts +10 -0
  30. package/dist/cohorts/maintenance.js +70 -0
  31. package/dist/cohorts/readiness.d.ts +30 -0
  32. package/dist/cohorts/readiness.js +54 -0
  33. package/dist/cohorts/readinessData.d.ts +29 -0
  34. package/dist/cohorts/readinessData.js +123 -0
  35. package/dist/cohorts/rule.d.ts +33 -0
  36. package/dist/cohorts/rule.js +50 -0
  37. package/dist/collections/cohortMembers.d.ts +4 -0
  38. package/dist/collections/cohortMembers.js +95 -0
  39. package/dist/collections/experiments/config.js +157 -7
  40. package/dist/collections/experiments/editability.js +10 -6
  41. package/dist/collections/experiments/lockHook.js +39 -20
  42. package/dist/collections/index.js +4 -1
  43. package/dist/collections/phases.js +4 -1
  44. package/dist/constants.d.ts +2 -0
  45. package/dist/constants.js +2 -0
  46. package/dist/db/adapter.d.ts +2 -1
  47. package/dist/db/adapter.js +17 -4
  48. package/dist/db/appends.d.ts +2 -1
  49. package/dist/db/appends.js +3 -2
  50. package/dist/db/bulkPlacementRemoval.d.ts +5 -0
  51. package/dist/db/bulkPlacementRemoval.js +7 -2
  52. package/dist/db/cohortMembership.d.ts +11 -0
  53. package/dist/db/cohortMembership.js +31 -0
  54. package/dist/db/cohortPool.d.ts +9 -0
  55. package/dist/db/cohortPool.js +53 -0
  56. package/dist/db/cohortTransactions.d.ts +3 -0
  57. package/dist/db/cohortTransactions.js +52 -0
  58. package/dist/db/cohorts.d.ts +72 -0
  59. package/dist/db/cohorts.js +280 -0
  60. package/dist/db/erase.d.ts +2 -0
  61. package/dist/db/erase.js +21 -2
  62. package/dist/db/events.d.ts +2 -0
  63. package/dist/db/events.js +8 -0
  64. package/dist/db/executor.d.ts +2 -0
  65. package/dist/db/executor.js +8 -0
  66. package/dist/db/locks.d.ts +7 -0
  67. package/dist/db/locks.js +13 -1
  68. package/dist/db/names.d.ts +95 -1
  69. package/dist/db/names.js +95 -1
  70. package/dist/db/occupancy.d.ts +21 -0
  71. package/dist/db/occupancy.js +46 -0
  72. package/dist/db/pageBindings.d.ts +2 -2
  73. package/dist/db/pageBindings.js +3 -3
  74. package/dist/db/pageOccupancy.d.ts +4 -4
  75. package/dist/db/pageOccupancy.js +13 -10
  76. package/dist/db/pgExecutor.d.ts +4 -0
  77. package/dist/db/pgExecutor.js +1 -1
  78. package/dist/db/placements.d.ts +6 -1
  79. package/dist/db/placements.js +27 -1
  80. package/dist/db/results.d.ts +5 -2
  81. package/dist/db/results.js +32 -5
  82. package/dist/db/slices.d.ts +9 -2
  83. package/dist/db/slices.js +15 -8
  84. package/dist/db/snapshots.d.ts +16 -1
  85. package/dist/db/snapshots.js +27 -2
  86. package/dist/db/sql.d.ts +2 -2
  87. package/dist/db/sql.js +1 -2
  88. package/dist/endpoints/cohortSources.d.ts +16 -0
  89. package/dist/endpoints/cohortSources.js +335 -0
  90. package/dist/endpoints/contentLocale.d.ts +1 -1
  91. package/dist/endpoints/duplicateOriginal.d.ts +1 -0
  92. package/dist/endpoints/events.js +82 -18
  93. package/dist/endpoints/index.js +45 -1
  94. package/dist/endpoints/pausedBy.d.ts +14 -0
  95. package/dist/endpoints/pausedBy.js +94 -0
  96. package/dist/endpoints/preflight.js +4 -1
  97. package/dist/endpoints/previewToken.js +2 -0
  98. package/dist/endpoints/results.d.ts +2 -2
  99. package/dist/endpoints/results.js +111 -3
  100. package/dist/endpoints/routeId.d.ts +2 -1
  101. package/dist/endpoints/routeId.js +6 -2
  102. package/dist/endpoints/summary.js +24 -1
  103. package/dist/endpoints/transitions.d.ts +7 -0
  104. package/dist/endpoints/transitions.js +50 -1
  105. package/dist/events/rows.d.ts +1 -1
  106. package/dist/events/rows.js +5 -3
  107. package/dist/exports/index.d.ts +2 -0
  108. package/dist/exports/index.js +1 -0
  109. package/dist/exports/runtimeProxy.d.ts +1 -0
  110. package/dist/exports/runtimeProxy.js +1 -0
  111. package/dist/hooks/blockRemovalRule.d.ts +1 -1
  112. package/dist/hooks/blockRemovalRule.js +12 -8
  113. package/dist/hooks/pageGuard.d.ts +7 -1
  114. package/dist/hooks/pageGuard.js +177 -4
  115. package/dist/hooks/puckNestedTests.d.ts +1 -1
  116. package/dist/hooks/puckNestedTests.js +3 -1
  117. package/dist/labels/status.d.ts +15 -0
  118. package/dist/labels/status.js +12 -0
  119. package/dist/manifest/compile.d.ts +15 -4
  120. package/dist/manifest/compile.js +91 -3
  121. package/dist/onInit.js +4 -6
  122. package/dist/options.d.ts +1 -0
  123. package/dist/options.js +10 -0
  124. package/dist/proxy/consentFallback.d.ts +1 -1
  125. package/dist/proxy/consentFallback.js +4 -4
  126. package/dist/proxy/control.d.ts +1 -1
  127. package/dist/proxy/control.js +2 -2
  128. package/dist/proxy/pageRewrite.d.ts +1 -1
  129. package/dist/proxy/pageRewrite.js +3 -2
  130. package/dist/proxy/resolve.js +76 -17
  131. package/dist/puck/ExperimentPicker.js +2 -1
  132. package/dist/puck/copy.d.ts +6 -5
  133. package/dist/puck/copy.js +3 -7
  134. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  135. package/dist/puck/editor/QuickTestActions.js +7 -1
  136. package/dist/puck/editor/armWrites.js +6 -1
  137. package/dist/puck/editor/copy.d.ts +3 -0
  138. package/dist/puck/editor/copy.js +3 -0
  139. package/dist/puck/editor/editor.css +2 -1
  140. package/dist/puck/editor/editor.model.d.ts +2 -1
  141. package/dist/puck/editor/editor.model.js +2 -0
  142. package/dist/puck/editor/placementsCache.d.ts +1 -1
  143. package/dist/puck/editor/placementsCache.js +6 -3
  144. package/dist/results/analyse.d.ts +3 -1
  145. package/dist/results/analyse.js +20 -3
  146. package/dist/results/health.d.ts +11 -0
  147. package/dist/results/health.js +38 -0
  148. package/dist/results/power.d.ts +1 -1
  149. package/dist/results/power.js +1 -1
  150. package/dist/results/snapshot.d.ts +8 -2
  151. package/dist/results/snapshot.js +23 -1
  152. package/dist/results/unitValues.d.ts +48 -0
  153. package/dist/results/unitValues.js +166 -0
  154. package/dist/runtime/assign.d.ts +7 -3
  155. package/dist/runtime/assign.js +12 -4
  156. package/dist/runtime/cohortCookie.d.ts +15 -0
  157. package/dist/runtime/cohortCookie.js +72 -0
  158. package/dist/runtime/cohortLookup.d.ts +9 -0
  159. package/dist/runtime/cohortLookup.js +25 -0
  160. package/dist/runtime/eligibility.d.ts +11 -5
  161. package/dist/runtime/eligibility.js +33 -7
  162. package/dist/runtime/header.d.ts +1 -0
  163. package/dist/runtime/header.js +1 -1
  164. package/dist/runtime/proxyRuntime.js +5 -1
  165. package/dist/runtime/targeting.d.ts +3 -2
  166. package/dist/runtime/targeting.js +2 -1
  167. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  168. package/dist/sanitizeReadinessDetail.js +41 -4
  169. package/dist/schedule/activeTime.d.ts +28 -0
  170. package/dist/schedule/activeTime.js +322 -0
  171. package/dist/schedule/ranges.d.ts +13 -0
  172. package/dist/schedule/ranges.js +11 -0
  173. package/dist/schedule/roundTime.d.ts +10 -0
  174. package/dist/schedule/roundTime.js +45 -0
  175. package/dist/schedule/types.d.ts +29 -0
  176. package/dist/schedule/types.js +1 -0
  177. package/dist/server/cohortLookup.d.ts +3 -0
  178. package/dist/server/cohortLookup.js +7 -0
  179. package/dist/server/eraseUser.d.ts +1 -0
  180. package/dist/server/getAssignments.js +63 -40
  181. package/dist/server/previewDraft.d.ts +1 -1
  182. package/dist/server/previewDraft.js +3 -2
  183. package/dist/server/recordContentChange.d.ts +1 -1
  184. package/dist/server/recordContentChange.js +42 -20
  185. package/dist/server/recordExposures.js +4 -2
  186. package/dist/server/runResults.js +97 -150
  187. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  188. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  189. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  190. package/dist/testSurface/actions/actions.model.js +38 -5
  191. package/dist/testSurface/api.d.ts +13 -1
  192. package/dist/testSurface/api.js +19 -0
  193. package/dist/testSurface/copy/actions.d.ts +13 -0
  194. package/dist/testSurface/copy/actions.js +13 -0
  195. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  196. package/dist/testSurface/copy/cohorts.js +81 -0
  197. package/dist/testSurface/copy/common.d.ts +2 -3
  198. package/dist/testSurface/copy/common.js +4 -4
  199. package/dist/testSurface/copy/inputs.d.ts +3 -0
  200. package/dist/testSurface/copy/inputs.js +3 -0
  201. package/dist/testSurface/copy/readiness.d.ts +20 -6
  202. package/dist/testSurface/copy/readiness.js +42 -9
  203. package/dist/testSurface/copy/results.d.ts +1 -0
  204. package/dist/testSurface/copy/results.js +1 -0
  205. package/dist/testSurface/copy/schedule.d.ts +58 -0
  206. package/dist/testSurface/copy/schedule.js +150 -0
  207. package/dist/testSurface/copy/surface.d.ts +2 -0
  208. package/dist/testSurface/copy/surface.js +2 -0
  209. package/dist/testSurface/copy/testPage.d.ts +12 -2
  210. package/dist/testSurface/copy/testPage.js +17 -2
  211. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  212. package/dist/testSurface/format/roundProgress.js +34 -5
  213. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  214. package/dist/testSurface/format/scheduleStatus.js +93 -0
  215. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  216. package/dist/testSurface/format/useScheduleClock.js +20 -0
  217. package/dist/testSurface/labels.d.ts +4 -9
  218. package/dist/testSurface/labels.js +2 -7
  219. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  220. package/dist/testSurface/lockedNotice.model.js +16 -3
  221. package/dist/testSurface/readPreflight.d.ts +3 -0
  222. package/dist/testSurface/readPreflight.js +14 -0
  223. package/dist/testSurface/readinessRead.d.ts +2 -2
  224. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  225. package/dist/testSurface/results/results.model.d.ts +1 -1
  226. package/dist/testSurface/results/results.model.js +34 -6
  227. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  228. package/dist/testSurface/review/cohortEstimate.js +32 -0
  229. package/dist/testSurface/surface/contracts.d.ts +2 -1
  230. package/dist/testSurface/surface/contracts.js +1 -0
  231. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  232. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  233. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  234. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  235. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  236. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  237. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  238. package/dist/testSurface/surface/results/ResultsBody.js +44 -8
  239. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  240. package/dist/testSurface/surface/results/useResults.js +17 -6
  241. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  242. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  243. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  244. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  245. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  246. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  247. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  248. package/dist/testSurface/surface/test/Section.js +1 -1
  249. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  250. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  251. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  252. package/dist/testSurface/surface/test/fields.js +3 -3
  253. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  254. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  255. package/dist/testSurface/surface/test/testPage.css +26 -0
  256. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  257. package/dist/testSurface/surface/testDocument.model.js +2 -1
  258. package/dist/testSurface/surface/useTestDocument.js +11 -4
  259. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  260. package/dist/testSurface/targeting/targeting.model.js +1 -1
  261. package/dist/testSurface/useApi.d.ts +12 -0
  262. package/dist/transitions/addMetric.js +5 -2
  263. package/dist/transitions/allocate.js +6 -1
  264. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  265. package/dist/transitions/assertNoOverlap.js +24 -0
  266. package/dist/transitions/buildCohorts.d.ts +10 -0
  267. package/dist/transitions/buildCohorts.js +68 -0
  268. package/dist/transitions/cancelSchedule.d.ts +4 -0
  269. package/dist/transitions/cancelSchedule.js +42 -0
  270. package/dist/transitions/checkStart.d.ts +17 -3
  271. package/dist/transitions/checkStart.js +20 -7
  272. package/dist/transitions/decide.js +40 -13
  273. package/dist/transitions/kernel.d.ts +3 -1
  274. package/dist/transitions/kernel.js +5 -2
  275. package/dist/transitions/pause.d.ts +4 -0
  276. package/dist/transitions/pause.js +35 -0
  277. package/dist/transitions/phaseRecord.d.ts +19 -2
  278. package/dist/transitions/phaseRecord.js +50 -11
  279. package/dist/transitions/placementInteractions.d.ts +7 -2
  280. package/dist/transitions/placementInteractions.js +9 -7
  281. package/dist/transitions/placements.d.ts +4 -3
  282. package/dist/transitions/placements.js +28 -14
  283. package/dist/transitions/preflightData.d.ts +11 -3
  284. package/dist/transitions/preflightData.js +134 -81
  285. package/dist/transitions/reschedule.d.ts +4 -0
  286. package/dist/transitions/reschedule.js +58 -0
  287. package/dist/transitions/resume.d.ts +4 -0
  288. package/dist/transitions/resume.js +32 -0
  289. package/dist/transitions/scheduledRound.d.ts +18 -0
  290. package/dist/transitions/scheduledRound.js +42 -0
  291. package/dist/transitions/start.d.ts +4 -0
  292. package/dist/transitions/start.js +139 -56
  293. package/dist/transitions/startReads.d.ts +14 -0
  294. package/dist/transitions/startReads.js +27 -0
  295. package/dist/transitions/stop.d.ts +10 -0
  296. package/dist/transitions/stop.js +35 -22
  297. package/dist/types/admin.d.ts +1 -1
  298. package/dist/types/contracts.d.ts +7 -1
  299. package/dist/types/endpoints.d.ts +72 -3
  300. package/dist/types/manifest.d.ts +9 -0
  301. package/dist/types/runtime.d.ts +5 -0
  302. package/dist/types/snapshot.d.ts +10 -0
  303. package/dist/types/status.d.ts +1 -0
  304. package/dist/types/status.js +1 -0
  305. package/dist/types/surface.d.ts +1 -0
  306. package/dist/ui/Feedback.d.ts +9 -6
  307. package/dist/ui/Feedback.js +10 -9
  308. package/dist/ui/SelectControl.js +1 -1
  309. package/dist/ui/ui.css +2 -1
  310. package/package.json +2 -2
@@ -1,3 +1,10 @@
1
+ import { isCohortTimeout, withCohortTimeout } from '../db/cohorts.js';
2
+ import { isCohortRule } from '../cohorts/rule.js';
3
+ import { checkCohorts, isCohortReadiness } from '../cohorts/readiness.js';
4
+ import { freezeCohortTargeting, loadCohortFacts } from '../cohorts/readinessData.js';
5
+ import { buildStartCohorts, cohortBuildTimeout } from '../cohorts/build.js';
6
+ import { resultsExecutor } from '../db/snapshots.js';
7
+ import { COHORT_COPY } from '../testSurface/copy/cohorts.js';
1
8
  import { withSlotsFor } from '../arms/model.js';
2
9
  import { nestedPlacementNames, nameNestedPlacements } from './nestedPlacementNames.js';
3
10
  import { nestedTestCopy } from '../puck/nestedTestCopy.js';
@@ -7,9 +14,9 @@ import { detached } from './placementInteractions.js';
7
14
  import { lockAndRescanPlacements, placementInteractions } from './placementInteractions.js';
8
15
  import { lockPagePaths } from '../db/locks.js';
9
16
  import { lockMetricsForFreeze } from '../db/metricUsage.js';
10
- import { DEFAULT_SEQUENTIAL_TUNING_PARAMETER } from '../constants.js';
17
+ import { COHORT_START_BUDGET_MS, DEFAULT_SEQUENTIAL_TUNING_PARAMETER } from '../constants.js';
11
18
  import { claimSlices } from '../db/slices.js';
12
- import { READINESS_COPY, asymmetricGoalsCopy, firstStartOnlyCopy, sameAddressCopy, interactingTestsCopy, pageInUseCopy, unpublishedPageCopy } from '../testSurface/copy/readiness.js';
19
+ import { READINESS_COPY, asymmetricGoalsCopy, firstStartOnlyCopy, sameAddressCopy, interactingTestsCopy, pageInUseCopy, scheduleOccupancyCopy, unpublishedPageCopy } from '../testSurface/copy/readiness.js';
13
20
  import { GROUP_LABELS } from '../testSurface/copy/arms.js';
14
21
  import { controlVersionLabel } from '../labels/arms.js';
15
22
  import { XpRefusal } from '../errors.js';
@@ -17,10 +24,13 @@ import { isOpValid } from '../targeting/ops.js';
17
24
  import { newSeed } from '../runtime/seed.js';
18
25
  import { checkStart, pageTargetPaths, relationshipId } from './checkStart.js';
19
26
  import { withTransition } from './kernel.js';
20
- import { requireCurrentRound, writePhaseRecord } from './phaseRecord.js';
21
- import { loadPageTestsInUse, loadStartInputsBatch, readStartInputExperiment, unpublishedPageTargets } from './preflightData.js';
27
+ import { latestPhaseNumber, requireCurrentRound, writePhaseRecord } from './phaseRecord.js';
28
+ import { loadStartInputsBatch, readStartInputExperiment, unpublishedPageTargets } from './preflightData.js';
22
29
  import { resolveCaps } from './resolveCaps.js';
23
- import { findStartDocuments, readStartState } from './startReads.js';
30
+ import { readStartState } from './startReads.js';
31
+ import { assertNoOverlap } from './assertNoOverlap.js';
32
+ import { claimRange } from '../schedule/ranges.js';
33
+ import { isValidTimeZone } from '../schedule/activeTime.js';
24
34
  export async function readExperiment(req, id) {
25
35
  // §7.8: internal lookup serves the authorised transition write. Preserve
26
36
  // admin-only analysis.method/kind for freezing; return access-filtered docs.
@@ -42,6 +52,11 @@ export async function readExperiment(req, id) {
42
52
  export function refuse(code, detail, controlLabel) {
43
53
  const groupLabel = (key)=>key === 'control' ? controlVersionLabel(controlLabel) : GROUP_LABELS[key];
44
54
  const messages = {
55
+ 'cohort-source-invalid': COHORT_COPY.invalid,
56
+ 'cohort-cycle': COHORT_COPY.cycle,
57
+ 'cohort-source-open': COHORT_COPY.open,
58
+ 'cohort-lookup-missing': COHORT_COPY.lookup,
59
+ 'cohort-build-timeout': COHORT_COPY.timeout,
45
60
  'nested-tests': nestedTestCopy.readiness(detail),
46
61
  'goal-in-some-versions': asymmetricGoalsCopy(detail),
47
62
  'placements-changed': "This test's pages changed while it was starting. Try again.",
@@ -68,14 +83,21 @@ export function refuse(code, detail, controlLabel) {
68
83
  'entry-not-found': 'That page is not in the report.',
69
84
  'entry-ok': 'That page was already updated.',
70
85
  'entry-dismissed': 'That page was already dismissed.',
71
- 'entry-not-dismissed': 'That page is not dismissed.'
86
+ 'entry-not-dismissed': 'That page is not dismissed.',
87
+ 'not-live': scheduleOccupancyCopy.notLive,
88
+ 'not-pausable': scheduleOccupancyCopy.notPausable,
89
+ paused: scheduleOccupancyCopy.paused,
90
+ 'reschedule-past': scheduleOccupancyCopy.reschedulePast,
91
+ 'schedule-started': scheduleOccupancyCopy.scheduleStarted
72
92
  };
73
93
  const conflict = [
94
+ 'cohort-build-timeout',
74
95
  'page-busy',
75
96
  'placements-changed',
76
97
  'interacting-tests',
77
98
  'invalid-status',
78
99
  'stale-draft',
100
+ 'stale-edit',
79
101
  'page-in-use',
80
102
  'flag-point-busy',
81
103
  'layer-full',
@@ -83,12 +105,16 @@ export function refuse(code, detail, controlLabel) {
83
105
  'not-decided',
84
106
  'entry-ok',
85
107
  'entry-dismissed',
86
- 'entry-not-dismissed'
108
+ 'entry-not-dismissed',
109
+ 'not-live',
110
+ 'not-pausable',
111
+ 'paused',
112
+ 'schedule-started'
87
113
  ].includes(code);
88
114
  throw new XpRefusal(code, messages[code] ?? 'The experiment is not ready to start.', detail, code === 'entry-not-found' ? 404 : conflict ? 409 : 422);
89
115
  }
90
116
  export async function updateExperiment(req, id, data, system = false) {
91
- // §7.8: an authorized manager transition or trusted system Start writes locked plugin fields.
117
+ // §7.8: an authorized manager transition, trusted system Start or scheduled Stop writes locked plugin fields.
92
118
  const updated = await req.payload.update({
93
119
  collection: 'xp-experiments',
94
120
  req,
@@ -112,10 +138,36 @@ export async function updateExperiment(req, id, data, system = false) {
112
138
  if (!docs[0]) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
113
139
  return docs[0];
114
140
  }
141
+ function scheduleForStart(value, defaultZone, now) {
142
+ const { startAt, endAt, timeZone, windows } = value ?? {};
143
+ // Payload stores no array rows for both omitted and empty windows.
144
+ if (startAt == null && endAt == null && !windows?.length) return undefined;
145
+ const zone = timeZone || defaultZone;
146
+ const invalid = (field, message)=>{
147
+ throw new XpRefusal('schedule-invalid', message, {
148
+ field: `schedule.${field}`
149
+ }, 422);
150
+ };
151
+ if (!zone || !isValidTimeZone(zone)) return invalid('timeZone', scheduleOccupancyCopy.timeZone);
152
+ const start = startAt == null ? +now : Date.parse(startAt);
153
+ if (!Number.isFinite(start)) return invalid('startAt', scheduleOccupancyCopy.invalidStart);
154
+ if (endAt != null && !(Date.parse(endAt) > Math.max(+now, start))) return invalid('endAt', scheduleOccupancyCopy.pastEnd);
155
+ if (windows?.some((window)=>!window.days?.length)) return invalid('windows', scheduleOccupancyCopy.windows);
156
+ return {
157
+ startAt: startAt ?? undefined,
158
+ endAt: endAt ?? undefined,
159
+ timeZone: zone,
160
+ windows: windows ?? []
161
+ };
162
+ }
115
163
  async function prepareStart(req, options, before, system) {
164
+ // Start checks occupancy on the locked transaction. Preflight shows advisory readiness.
116
165
  const input = (await loadStartInputsBatch(req, options, [
117
166
  before
118
- ], false, system)).get(String(before.id));
167
+ ], false, system, {
168
+ checkOccupancy: false,
169
+ readCohorts: false
170
+ })).get(String(before.id));
119
171
  if (!input) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
120
172
  const full = await readExperiment(req, before.id);
121
173
  if (full.updatedAt !== before.updatedAt) refuse('stale-draft');
@@ -127,13 +179,11 @@ async function prepareStart(req, options, before, system) {
127
179
  };
128
180
  // Warning-only codes always have ok: true. These exclusions narrow
129
181
  // ReadinessCode to RefusalCode, which intentionally excludes warnings.
130
- const failed = checkStart(input).find((check)=>!check.ok);
182
+ const failed = checkStart(input).find((check)=>!check.ok && !isCohortReadiness(check.code));
131
183
  if (failed && failed.code !== 'page-targets-unchecked' && failed.code !== 'make-content-unsupported') refuse(failed.code, failed.detail, before.arms.find((arm)=>arm.kind === 'control')?.label);
132
- const at = new Date();
133
- const caps = await resolveCaps(input.metrics, options.metricSources ?? [], at);
184
+ const caps = await resolveCaps(input.metrics, options.metricSources ?? [], new Date());
134
185
  return {
135
186
  input,
136
- at,
137
187
  caps
138
188
  };
139
189
  }
@@ -157,10 +207,11 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
157
207
  }, async ({ req, exec })=>{
158
208
  const current = await readExperiment(req, experimentId);
159
209
  // A concurrent Start or Stop must yield the locked status before considering a stale snapshot.
160
- if (onlyIfNeverStarted && (current.status !== 'draft' || (current.phase ?? 0) !== 0)) {
210
+ const lastPhase = current.phase || await latestPhaseNumber(req, experimentId);
211
+ if (onlyIfNeverStarted && (current.status !== 'draft' || lastPhase !== 0)) {
161
212
  const detail = {
162
213
  status: current.status,
163
- phase: current.phase ?? 0
214
+ phase: lastPhase
164
215
  };
165
216
  throw new XpRefusal('first-start-only', firstStartOnlyCopy(current.status), detail, 409);
166
217
  }
@@ -168,30 +219,37 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
168
219
  if (current.updatedAt !== updatedAt) refuse('stale-draft');
169
220
  if (current.status !== 'draft' && current.status !== 'stopped') refuse('invalid-status');
170
221
  if ('error' in prepared) throw prepared.error;
171
- const { input, at, caps } = prepared;
222
+ const { input, caps } = prepared;
223
+ if (current.kind === 'page') await lockPagePaths(exec, pageTargetPaths(current.arms));
224
+ const at = new Date();
225
+ const schedule = scheduleForStart(current.schedule, options.timeZone, at);
226
+ const claim = claimRange({
227
+ startedAt: at,
228
+ schedule
229
+ });
230
+ const startedAt = new Date(Math.max(+at, +claim.from)).toISOString();
231
+ const scheduled = +claim.from > +at;
232
+ const previousArms = current.arms;
233
+ const inheritedTimeZone = schedule && schedule.timeZone !== current.schedule?.timeZone ? schedule.timeZone : undefined;
234
+ await assertNoOverlap(exec, {
235
+ ...current,
236
+ layerSlices: undefined
237
+ }, claim);
172
238
  const controlLabel = current.arms.find((arm)=>arm.kind === 'control')?.label;
173
239
  let placementDocs;
174
240
  if (current.kind === 'block') {
175
- const rescan = await lockAndRescanPlacements(req, exec, options, current, input.placements ?? [], system);
241
+ const rescan = await lockAndRescanPlacements(req, exec, options, current, input.placements ?? [], {
242
+ system
243
+ });
176
244
  placementDocs = rescan.docs;
177
245
  const failure = checkStart({
178
246
  ...input,
179
247
  experiment: current,
180
248
  placements: nameNestedPlacements(rescan.placements, await nestedPlacementNames(req, rescan.placements, system))
181
- }).find((check)=>!check.ok);
249
+ }).find((check)=>!check.ok && !isCohortReadiness(check.code));
182
250
  if (failure && failure.code !== 'page-targets-unchecked' && failure.code !== 'make-content-unsupported') refuse(failure.code, failure.detail, controlLabel);
183
251
  }
184
252
  if (current.kind === 'page') {
185
- // Independent experiment/layer locks do not serialize overlapping pages.
186
- // Re-read occupancy after acquiring sorted path locks; hold through commit.
187
- // A waiting Start then sees the first Start's live test on this transaction.
188
- await lockPagePaths(exec, pageTargetPaths(current.arms));
189
- const recheck = checkStart({
190
- ...input,
191
- experiment: current,
192
- pageTestsInUse: await loadPageTestsInUse(req)
193
- }).find((check)=>check.code === 'page-in-use' && !check.ok);
194
- if (recheck) refuse('page-in-use', recheck.detail);
195
253
  const conflicts = await placementInteractions(req, exec, options, current, pageTargetPaths(current.arms), system);
196
254
  if (conflicts.length) refuse('interacting-tests', conflicts);
197
255
  if (options.pages) {
@@ -211,29 +269,6 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
211
269
  }
212
270
  }
213
271
  if (current.kind === 'flag' && current.flagPoint) {
214
- const busy = await findStartDocuments(req, {
215
- collection: 'xp-experiments',
216
- depth: 0,
217
- limit: 2,
218
- where: {
219
- and: [
220
- {
221
- flagPoint: {
222
- equals: current.flagPoint
223
- }
224
- },
225
- {
226
- status: {
227
- in: [
228
- 'running',
229
- 'decided'
230
- ]
231
- }
232
- }
233
- ]
234
- }
235
- }, system);
236
- if (busy.docs.some((doc)=>String(doc.id) !== String(experimentId))) refuse('flag-point-busy');
237
272
  const point = options.flagPoints.find((point)=>point.id === current.flagPoint);
238
273
  const state = await readStartState(req, system);
239
274
  const defaults = state.flagDefaults;
@@ -244,7 +279,7 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
244
279
  const recheck = checkStart({
245
280
  ...input,
246
281
  experiment: current
247
- }).find((check)=>!check.ok);
282
+ }).find((check)=>!check.ok && !isCohortReadiness(check.code));
248
283
  if (recheck && recheck.code !== 'page-targets-unchecked' && recheck.code !== 'make-content-unsupported') refuse(recheck.code, recheck.detail, controlLabel);
249
284
  }
250
285
  if (input.metrics.some((metric)=>metric.source.startsWith('click:'))) {
@@ -265,7 +300,20 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
265
300
  const locked = lockedMetrics.find((row)=>String(row.id) === String(metric.id));
266
301
  return locked.slug !== metric.slug || locked.source !== metric.source;
267
302
  })) throw new XpRefusal('stale-draft', 'A goal changed. Review it again before starting.', undefined, 409);
268
- const targeting = (current.targeting ?? []).map((rule)=>{
303
+ const cohortNow = new Date();
304
+ if (current.targeting?.some(isCohortRule) && options.cohorts?.proxyLookup !== true) refuse('cohort-lookup-missing');
305
+ const deadline = +cohortNow + COHORT_START_BUDGET_MS;
306
+ const frozen = !current.targeting?.some(isCohortRule) ? undefined : await withCohortTimeout(exec, deadline, async (timed)=>{
307
+ const facts = await loadCohortFacts(req, timed, current, options, system, cohortNow, deadline);
308
+ const failure = checkCohorts(current, facts)[0];
309
+ if (failure) refuse(failure.code, failure.detail);
310
+ return freezeCohortTargeting(current, facts);
311
+ }).catch((error)=>{
312
+ if (isCohortTimeout(error)) throw cohortBuildTimeout([]);
313
+ throw error;
314
+ });
315
+ const targeting = (frozen?.targeting ?? (current.targeting ?? []).filter((rule)=>!isCohortRule(rule))).map((rule)=>{
316
+ if (isCohortRule(rule)) return rule;
269
317
  const type = Object.hasOwn(options.attributeKeys ?? {}, rule.attribute) ? options.attributeKeys[rule.attribute].type : undefined;
270
318
  const validValue = type === 'string' && [
271
319
  'in',
@@ -282,15 +330,23 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
282
330
  type
283
331
  };
284
332
  });
333
+ if (frozen) {
334
+ await buildStartCohorts(exec, frozen.rules, frozen.sources, {
335
+ options,
336
+ now: cohortNow,
337
+ budgetMs: deadline - Date.now(),
338
+ readExec: resultsExecutor(req.payload, ()=>deadline - Date.now())
339
+ });
340
+ }
285
341
  const layerId = relationshipId(current.layer);
286
342
  const layerSlices = layerId === undefined ? [] : await claimSlices(exec, {
287
343
  layerId,
288
344
  experimentId,
289
- count: current.allocation
345
+ count: current.allocation,
346
+ claim
290
347
  });
291
- const phase = (current.phase ?? 0) + 1;
348
+ const phase = lastPhase + 1;
292
349
  const seed = newSeed();
293
- const startedAt = at.toISOString();
294
350
  const definitions = caps.definitions.map((metric)=>({
295
351
  ...metric,
296
352
  metricId: metric.id,
@@ -299,6 +355,16 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
299
355
  role: String(relationshipId(current.metrics?.primary)) === String(metric.id) ? 'primary' : current.metrics?.guardrails?.some((id)=>String(relationshipId(id)) === String(metric.id)) ? 'guardrail' : 'secondary'
300
356
  }));
301
357
  const arms = current.kind === 'block' ? withSlotsFor(current.arms, 'block') : current.arms;
358
+ // Cancel needs the editable values from just before Schedule, which may
359
+ // differ from the frozen values of any earlier round.
360
+ const beforeSchedule = scheduled && (current.kind === 'flag' || inheritedTimeZone) ? {
361
+ ...current.kind === 'flag' ? {
362
+ arms: previousArms
363
+ } : {},
364
+ ...inheritedTimeZone ? {
365
+ timeZone: current.schedule?.timeZone ?? null
366
+ } : {}
367
+ } : undefined;
302
368
  await writePhaseRecord(req, {
303
369
  experiment: experimentId,
304
370
  phase,
@@ -310,6 +376,9 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
310
376
  allocationChanges: [],
311
377
  targeting,
312
378
  metricDefinitions: definitions,
379
+ ...schedule ? {
380
+ schedule
381
+ } : {},
313
382
  ...placementDocs ? {
314
383
  placementDocs
315
384
  } : {},
@@ -317,6 +386,9 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
317
386
  ...current.analysis,
318
387
  method: current.analysis?.method ?? 'sequential',
319
388
  alpha: 0.05,
389
+ ...beforeSchedule ? {
390
+ beforeSchedule
391
+ } : {},
320
392
  sequentialTuningParameter: current.analysis?.sequentialTuningParameter ?? DEFAULT_SEQUENTIAL_TUNING_PARAMETER,
321
393
  cupedLookbackDays: 14,
322
394
  layerSlices,
@@ -341,6 +413,17 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
341
413
  seed,
342
414
  startedAt,
343
415
  stoppedAt: null,
416
+ pausedAt: null,
417
+ pausedBy: null,
418
+ pauseReason: null,
419
+ ...inheritedTimeZone ? {
420
+ schedule: {
421
+ ...current.schedule,
422
+ timeZone: inheritedTimeZone
423
+ }
424
+ } : {},
425
+ claimFrom: claim.from.toISOString(),
426
+ claimTo: claim.to?.toISOString() ?? null,
344
427
  layerSlices,
345
428
  arms
346
429
  }, system);
@@ -1,7 +1,21 @@
1
1
  import type { PayloadRequest } from 'payload';
2
+ import { type OccupancyRow } from '../db/occupancy.js';
3
+ import type { DocId } from '../types/contracts.js';
2
4
  type StartReadQuery = Parameters<PayloadRequest['payload']['find']>[0] & {
3
5
  collection: 'xp-experiments' | 'xp-metrics' | 'xp-layers';
4
6
  };
5
7
  export declare function findStartDocuments(req: PayloadRequest, query: StartReadQuery, system?: boolean): Promise<import("payload").PaginatedDocs<import("payload").JsonObject & import("payload").TypeWithID>>;
6
8
  export declare function readStartState(req: PayloadRequest, system?: boolean): Promise<import("payload").JsonObject>;
9
+ /** Cache the peer rows in batched readiness, then test each draft's own range. */
10
+ export declare function readStartPeers(req: PayloadRequest, where: {
11
+ layer: {
12
+ equals: DocId;
13
+ };
14
+ } | {
15
+ flagPoint: {
16
+ equals: string;
17
+ };
18
+ }, system: boolean): Promise<(OccupancyRow & {
19
+ layerSlices?: number[] | null;
20
+ })[]>;
7
21
  export {};
@@ -1,3 +1,4 @@
1
+ import { OCCUPYING_STATUSES } from '../db/occupancy.js';
1
2
  export function findStartDocuments(req, query, system = false) {
2
3
  // §7.8: Start from trusted host code reads plugin readiness data without a manager actor.
3
4
  if (system) return req.payload.find({
@@ -26,3 +27,29 @@ export function readStartState(req, system = false) {
26
27
  depth: 0
27
28
  });
28
29
  }
30
+ /** Cache the peer rows in batched readiness, then test each draft's own range. */ export async function readStartPeers(req, where, system) {
31
+ const peers = [];
32
+ for(let page = 1;; page++){
33
+ const usage = await findStartDocuments(req, {
34
+ collection: 'xp-experiments',
35
+ depth: 0,
36
+ limit: 100,
37
+ page,
38
+ where: {
39
+ and: [
40
+ where,
41
+ {
42
+ status: {
43
+ in: OCCUPYING_STATUSES
44
+ }
45
+ }
46
+ ]
47
+ }
48
+ }, system);
49
+ peers.push(...usage.docs.map((doc)=>({
50
+ ...doc,
51
+ scheduleTimeZone: doc.schedule?.timeZone
52
+ })));
53
+ if (!usage.hasNextPage) return peers;
54
+ }
55
+ }
@@ -1,9 +1,19 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
3
  import type { RoundBody } from '../types/endpoints.js';
4
+ import { type TransitionExperiment } from './start.js';
5
+ export declare function stopRound(req: PayloadRequest, current: TransitionExperiment, at: string, system?: boolean): Promise<import("payload").JsonObject & import("payload").TypeWithID>;
4
6
  export declare function stop(req: PayloadRequest, { experimentId, phase: expectedPhase }: RoundBody & {
5
7
  experimentId: DocId;
6
8
  }): Promise<{
7
9
  doc: import("payload").JsonObject & import("payload").TypeWithID;
8
10
  revision: number;
9
11
  }>;
12
+ /** System-only Stop. Re-read the frozen end inside the lock so a concurrent
13
+ * reschedule, pause, decision or new round wins over discovery by runResults. */
14
+ export declare function stopScheduledExperiment(req: PayloadRequest, { experimentId, phase, dueBy, deadline }: {
15
+ experimentId: DocId;
16
+ phase: number;
17
+ dueBy: Date;
18
+ deadline: number;
19
+ }): Promise<void>;
@@ -1,26 +1,39 @@
1
- import { relationshipId } from './checkStart.js';
2
- import { withTransition } from './kernel.js';
3
- import { requireCurrentRound, setPhaseEndedAt } from './phaseRecord.js';
4
- import { readExperiment, refuse, updateExperiment } from './start.js';
1
+ import { readPhaseRecord, requireCurrentRound, setPhaseEndedAt } from './phaseRecord.js';
2
+ import { requireStarted, withScheduledRound } from './scheduledRound.js';
3
+ import { refuse, updateExperiment } from './start.js';
4
+ export async function stopRound(req, current, at, system = false) {
5
+ await setPhaseEndedAt(req, current.id, current.phase, at);
6
+ return updateExperiment(req, current.id, {
7
+ status: 'stopped',
8
+ layerSlices: [],
9
+ stoppedAt: at
10
+ }, system);
11
+ }
5
12
  export async function stop(req, { experimentId, phase: expectedPhase }) {
6
- const before = await readExperiment(req, experimentId);
7
- const { result: doc, revision } = await withTransition(req, {
8
- experimentId,
9
- layerId: relationshipId(before.layer)
10
- }, async ({ req })=>{
11
- const current = await readExperiment(req, experimentId);
13
+ return withScheduledRound(req, experimentId, async (req, _exec, current)=>{
12
14
  requireCurrentRound(expectedPhase, current.phase);
13
- if (current.status !== 'running') refuse('invalid-status');
14
- const at = new Date().toISOString();
15
- await setPhaseEndedAt(req, experimentId, current.phase, at);
16
- return updateExperiment(req, experimentId, {
17
- status: 'stopped',
18
- layerSlices: [],
19
- stoppedAt: at
20
- });
15
+ if (current.status !== 'running' && current.status !== 'paused') refuse('invalid-status');
16
+ const now = new Date();
17
+ requireStarted(current.startedAt, now);
18
+ const scheduledEnd = current.claimTo ? new Date(current.claimTo) : null;
19
+ const at = current.status === 'paused' ? current.pausedAt : scheduledEnd && scheduledEnd <= now ? scheduledEnd.toISOString() : now.toISOString();
20
+ if (!at) refuse('invalid-phase');
21
+ return stopRound(req, current, at);
21
22
  });
22
- return {
23
- doc,
24
- revision: revision
25
- };
23
+ }
24
+ class ScheduleNoLongerDue extends Error {
25
+ }
26
+ /** System-only Stop. Re-read the frozen end inside the lock so a concurrent
27
+ * reschedule, pause, decision or new round wins over discovery by runResults. */ export async function stopScheduledExperiment(req, { experimentId, phase, dueBy, deadline }) {
28
+ try {
29
+ await withScheduledRound(req, experimentId, async (req, _exec, current)=>{
30
+ if (current.status !== 'running' || current.phase !== phase) throw new ScheduleNoLongerDue();
31
+ const record = await readPhaseRecord(req, experimentId, phase);
32
+ const endAt = record.schedule?.endAt;
33
+ if (record.phaseKind !== 'test' || !endAt || new Date(endAt) > dueBy) throw new ScheduleNoLongerDue();
34
+ return stopRound(req, current, new Date(endAt).toISOString(), true);
35
+ }, deadline);
36
+ } catch (error) {
37
+ if (!(error instanceof ScheduleNoLongerDue)) throw error;
38
+ }
26
39
  }
@@ -18,4 +18,4 @@ export type SerializedAttributeKeys = Record<string, {
18
18
  type: 'string' | 'number' | 'boolean';
19
19
  values?: string[];
20
20
  }>;
21
- export type EditableField = 'name' | 'hypothesis' | 'arms' | 'targeting' | 'allocation' | 'flagPoint' | 'metrics' | 'analysis' | 'exposurePolicy' | 'pageCollection';
21
+ export type EditableField = 'name' | 'hypothesis' | 'arms' | 'targeting' | 'allocation' | 'flagPoint' | 'metrics' | 'analysis' | 'exposurePolicy' | 'pageCollection' | 'schedule';
@@ -14,12 +14,13 @@ export interface PreviewPlacement {
14
14
  export type Attributes = Record<string, string | number | boolean>;
15
15
  export type ExposurePolicy = 'render' | 'viewport' | 'pageview' | 'manual';
16
16
  export type ExperimentKind = 'block' | 'page' | 'flag' | 'code';
17
- export type Status = 'draft' | 'running' | 'stopped' | 'decided' | 'archived';
17
+ export type { Status } from './status.js';
18
18
  export type UnitType = 'visitor' | 'user';
19
19
  import type { ArmKey } from './armKey.js';
20
20
  export type { ArmKey };
21
21
  export type ArmKind = 'control' | 'variant' | 'holdout';
22
22
  export interface TargetingRule {
23
+ kind?: 'attribute';
23
24
  attribute: string;
24
25
  op: TargetingOp;
25
26
  value: string | number | boolean | string[];
@@ -137,6 +138,11 @@ export interface ExperimentsPluginOptions<TUser extends {
137
138
  readResults?: ExperimentsAccess;
138
139
  readIdentities?: ExperimentsAccess;
139
140
  };
141
+ /** Default IANA time zone for experiment schedules. */
142
+ timeZone?: string;
143
+ cohorts?: {
144
+ proxyLookup: boolean;
145
+ };
140
146
  theme?: {
141
147
  accent?: string;
142
148
  };