@delmaredigital/payload-experiments 0.4.0 → 0.5.0

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 (290) hide show
  1. package/README.md +10 -4
  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/cohorts/build.d.ts +35 -0
  22. package/dist/cohorts/build.js +134 -0
  23. package/dist/cohorts/key.d.ts +12 -0
  24. package/dist/cohorts/key.js +15 -0
  25. package/dist/cohorts/maintenance.d.ts +10 -0
  26. package/dist/cohorts/maintenance.js +70 -0
  27. package/dist/cohorts/readiness.d.ts +30 -0
  28. package/dist/cohorts/readiness.js +54 -0
  29. package/dist/cohorts/readinessData.d.ts +29 -0
  30. package/dist/cohorts/readinessData.js +123 -0
  31. package/dist/cohorts/rule.d.ts +33 -0
  32. package/dist/cohorts/rule.js +50 -0
  33. package/dist/collections/cohortMembers.d.ts +4 -0
  34. package/dist/collections/cohortMembers.js +95 -0
  35. package/dist/collections/experiments/config.js +157 -7
  36. package/dist/collections/experiments/editability.js +10 -6
  37. package/dist/collections/experiments/lockHook.js +39 -20
  38. package/dist/collections/index.js +4 -1
  39. package/dist/collections/phases.js +4 -1
  40. package/dist/constants.d.ts +2 -0
  41. package/dist/constants.js +2 -0
  42. package/dist/db/adapter.d.ts +1 -1
  43. package/dist/db/adapter.js +14 -4
  44. package/dist/db/appends.js +1 -1
  45. package/dist/db/cohortMembership.d.ts +11 -0
  46. package/dist/db/cohortMembership.js +31 -0
  47. package/dist/db/cohortPool.d.ts +9 -0
  48. package/dist/db/cohortPool.js +53 -0
  49. package/dist/db/cohortTransactions.d.ts +3 -0
  50. package/dist/db/cohortTransactions.js +52 -0
  51. package/dist/db/cohorts.d.ts +72 -0
  52. package/dist/db/cohorts.js +280 -0
  53. package/dist/db/erase.d.ts +2 -0
  54. package/dist/db/erase.js +21 -2
  55. package/dist/db/events.d.ts +2 -0
  56. package/dist/db/events.js +8 -0
  57. package/dist/db/executor.d.ts +2 -0
  58. package/dist/db/executor.js +8 -0
  59. package/dist/db/locks.d.ts +7 -0
  60. package/dist/db/locks.js +13 -1
  61. package/dist/db/names.d.ts +95 -1
  62. package/dist/db/names.js +95 -1
  63. package/dist/db/occupancy.d.ts +21 -0
  64. package/dist/db/occupancy.js +46 -0
  65. package/dist/db/pageOccupancy.d.ts +4 -4
  66. package/dist/db/pageOccupancy.js +13 -10
  67. package/dist/db/pgExecutor.d.ts +4 -0
  68. package/dist/db/pgExecutor.js +1 -1
  69. package/dist/db/placements.js +1 -1
  70. package/dist/db/results.d.ts +5 -2
  71. package/dist/db/results.js +32 -5
  72. package/dist/db/slices.d.ts +9 -2
  73. package/dist/db/slices.js +15 -8
  74. package/dist/db/snapshots.d.ts +16 -1
  75. package/dist/db/snapshots.js +27 -2
  76. package/dist/db/sql.d.ts +2 -2
  77. package/dist/db/sql.js +1 -2
  78. package/dist/endpoints/cohortSources.d.ts +16 -0
  79. package/dist/endpoints/cohortSources.js +335 -0
  80. package/dist/endpoints/contentLocale.d.ts +1 -1
  81. package/dist/endpoints/events.js +82 -18
  82. package/dist/endpoints/index.js +45 -1
  83. package/dist/endpoints/pausedBy.d.ts +14 -0
  84. package/dist/endpoints/pausedBy.js +94 -0
  85. package/dist/endpoints/preflight.js +4 -1
  86. package/dist/endpoints/previewToken.js +2 -0
  87. package/dist/endpoints/results.d.ts +2 -2
  88. package/dist/endpoints/results.js +111 -3
  89. package/dist/endpoints/routeId.d.ts +2 -1
  90. package/dist/endpoints/routeId.js +6 -2
  91. package/dist/endpoints/summary.js +24 -1
  92. package/dist/endpoints/transitions.d.ts +7 -0
  93. package/dist/endpoints/transitions.js +50 -1
  94. package/dist/events/rows.d.ts +1 -1
  95. package/dist/events/rows.js +5 -3
  96. package/dist/exports/index.d.ts +2 -0
  97. package/dist/exports/index.js +1 -0
  98. package/dist/exports/runtimeProxy.d.ts +1 -0
  99. package/dist/exports/runtimeProxy.js +1 -0
  100. package/dist/hooks/blockRemovalRule.js +7 -4
  101. package/dist/hooks/pageGuard.js +1 -1
  102. package/dist/labels/status.d.ts +15 -0
  103. package/dist/labels/status.js +12 -0
  104. package/dist/manifest/compile.d.ts +15 -4
  105. package/dist/manifest/compile.js +91 -3
  106. package/dist/onInit.js +4 -1
  107. package/dist/options.d.ts +1 -0
  108. package/dist/options.js +10 -0
  109. package/dist/proxy/consentFallback.d.ts +1 -1
  110. package/dist/proxy/consentFallback.js +4 -4
  111. package/dist/proxy/control.d.ts +1 -1
  112. package/dist/proxy/control.js +2 -2
  113. package/dist/proxy/pageRewrite.d.ts +1 -1
  114. package/dist/proxy/pageRewrite.js +3 -2
  115. package/dist/proxy/resolve.js +76 -17
  116. package/dist/puck/ExperimentPicker.js +2 -1
  117. package/dist/puck/copy.d.ts +6 -5
  118. package/dist/puck/copy.js +3 -7
  119. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  120. package/dist/puck/editor/QuickTestActions.js +7 -1
  121. package/dist/puck/editor/armWrites.js +6 -1
  122. package/dist/puck/editor/copy.d.ts +3 -0
  123. package/dist/puck/editor/copy.js +3 -0
  124. package/dist/puck/editor/editor.css +2 -1
  125. package/dist/puck/editor/editor.model.d.ts +2 -1
  126. package/dist/puck/editor/editor.model.js +2 -0
  127. package/dist/puck/editor/placementsCache.d.ts +1 -1
  128. package/dist/puck/editor/placementsCache.js +6 -3
  129. package/dist/results/analyse.d.ts +3 -1
  130. package/dist/results/analyse.js +20 -3
  131. package/dist/results/health.d.ts +11 -0
  132. package/dist/results/health.js +38 -0
  133. package/dist/results/power.d.ts +1 -1
  134. package/dist/results/power.js +1 -1
  135. package/dist/results/snapshot.d.ts +8 -2
  136. package/dist/results/snapshot.js +23 -1
  137. package/dist/results/unitValues.d.ts +48 -0
  138. package/dist/results/unitValues.js +166 -0
  139. package/dist/runtime/assign.d.ts +7 -3
  140. package/dist/runtime/assign.js +12 -4
  141. package/dist/runtime/cohortCookie.d.ts +15 -0
  142. package/dist/runtime/cohortCookie.js +72 -0
  143. package/dist/runtime/cohortLookup.d.ts +9 -0
  144. package/dist/runtime/cohortLookup.js +25 -0
  145. package/dist/runtime/eligibility.d.ts +11 -5
  146. package/dist/runtime/eligibility.js +33 -7
  147. package/dist/runtime/header.d.ts +1 -0
  148. package/dist/runtime/header.js +1 -1
  149. package/dist/runtime/proxyRuntime.js +5 -1
  150. package/dist/runtime/targeting.d.ts +3 -2
  151. package/dist/runtime/targeting.js +2 -1
  152. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  153. package/dist/sanitizeReadinessDetail.js +41 -4
  154. package/dist/schedule/activeTime.d.ts +28 -0
  155. package/dist/schedule/activeTime.js +322 -0
  156. package/dist/schedule/ranges.d.ts +13 -0
  157. package/dist/schedule/ranges.js +11 -0
  158. package/dist/schedule/roundTime.d.ts +10 -0
  159. package/dist/schedule/roundTime.js +45 -0
  160. package/dist/schedule/types.d.ts +29 -0
  161. package/dist/schedule/types.js +1 -0
  162. package/dist/server/cohortLookup.d.ts +3 -0
  163. package/dist/server/cohortLookup.js +7 -0
  164. package/dist/server/eraseUser.d.ts +1 -0
  165. package/dist/server/getAssignments.js +63 -40
  166. package/dist/server/previewDraft.d.ts +1 -1
  167. package/dist/server/previewDraft.js +3 -2
  168. package/dist/server/recordExposures.js +4 -2
  169. package/dist/server/runResults.js +97 -150
  170. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  171. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  172. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  173. package/dist/testSurface/actions/actions.model.js +38 -5
  174. package/dist/testSurface/api.d.ts +13 -1
  175. package/dist/testSurface/api.js +19 -0
  176. package/dist/testSurface/copy/actions.d.ts +13 -0
  177. package/dist/testSurface/copy/actions.js +13 -0
  178. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  179. package/dist/testSurface/copy/cohorts.js +81 -0
  180. package/dist/testSurface/copy/common.d.ts +2 -3
  181. package/dist/testSurface/copy/common.js +4 -4
  182. package/dist/testSurface/copy/inputs.d.ts +3 -0
  183. package/dist/testSurface/copy/inputs.js +3 -0
  184. package/dist/testSurface/copy/readiness.d.ts +20 -6
  185. package/dist/testSurface/copy/readiness.js +42 -9
  186. package/dist/testSurface/copy/results.d.ts +1 -0
  187. package/dist/testSurface/copy/results.js +1 -0
  188. package/dist/testSurface/copy/schedule.d.ts +58 -0
  189. package/dist/testSurface/copy/schedule.js +150 -0
  190. package/dist/testSurface/copy/surface.d.ts +2 -0
  191. package/dist/testSurface/copy/surface.js +2 -0
  192. package/dist/testSurface/copy/testPage.d.ts +12 -2
  193. package/dist/testSurface/copy/testPage.js +17 -2
  194. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  195. package/dist/testSurface/format/roundProgress.js +34 -5
  196. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  197. package/dist/testSurface/format/scheduleStatus.js +93 -0
  198. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  199. package/dist/testSurface/format/useScheduleClock.js +20 -0
  200. package/dist/testSurface/labels.d.ts +4 -9
  201. package/dist/testSurface/labels.js +2 -7
  202. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  203. package/dist/testSurface/lockedNotice.model.js +16 -3
  204. package/dist/testSurface/readPreflight.d.ts +3 -0
  205. package/dist/testSurface/readPreflight.js +14 -0
  206. package/dist/testSurface/readinessRead.d.ts +2 -2
  207. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  208. package/dist/testSurface/results/results.model.d.ts +1 -1
  209. package/dist/testSurface/results/results.model.js +34 -6
  210. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  211. package/dist/testSurface/review/cohortEstimate.js +32 -0
  212. package/dist/testSurface/surface/contracts.d.ts +2 -1
  213. package/dist/testSurface/surface/contracts.js +1 -0
  214. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  215. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  216. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  217. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  218. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  219. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  220. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  221. package/dist/testSurface/surface/results/ResultsBody.js +46 -10
  222. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  223. package/dist/testSurface/surface/results/useResults.js +17 -6
  224. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  225. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  226. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  227. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  228. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  229. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  230. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  231. package/dist/testSurface/surface/test/Section.js +1 -1
  232. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  233. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  234. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  235. package/dist/testSurface/surface/test/fields.js +3 -3
  236. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  237. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  238. package/dist/testSurface/surface/test/testPage.css +26 -0
  239. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  240. package/dist/testSurface/surface/testDocument.model.js +2 -1
  241. package/dist/testSurface/surface/useTestDocument.js +11 -4
  242. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  243. package/dist/testSurface/targeting/targeting.model.js +1 -1
  244. package/dist/testSurface/useApi.d.ts +12 -0
  245. package/dist/transitions/addMetric.js +5 -2
  246. package/dist/transitions/allocate.js +6 -1
  247. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  248. package/dist/transitions/assertNoOverlap.js +24 -0
  249. package/dist/transitions/buildCohorts.d.ts +10 -0
  250. package/dist/transitions/buildCohorts.js +68 -0
  251. package/dist/transitions/cancelSchedule.d.ts +4 -0
  252. package/dist/transitions/cancelSchedule.js +42 -0
  253. package/dist/transitions/checkStart.d.ts +17 -3
  254. package/dist/transitions/checkStart.js +20 -7
  255. package/dist/transitions/decide.js +35 -11
  256. package/dist/transitions/kernel.d.ts +3 -1
  257. package/dist/transitions/kernel.js +5 -2
  258. package/dist/transitions/pause.d.ts +4 -0
  259. package/dist/transitions/pause.js +35 -0
  260. package/dist/transitions/phaseRecord.d.ts +19 -2
  261. package/dist/transitions/phaseRecord.js +50 -11
  262. package/dist/transitions/placementInteractions.js +1 -1
  263. package/dist/transitions/preflightData.d.ts +11 -3
  264. package/dist/transitions/preflightData.js +134 -81
  265. package/dist/transitions/reschedule.d.ts +4 -0
  266. package/dist/transitions/reschedule.js +58 -0
  267. package/dist/transitions/resume.d.ts +4 -0
  268. package/dist/transitions/resume.js +32 -0
  269. package/dist/transitions/scheduledRound.d.ts +18 -0
  270. package/dist/transitions/scheduledRound.js +42 -0
  271. package/dist/transitions/start.d.ts +4 -0
  272. package/dist/transitions/start.js +136 -55
  273. package/dist/transitions/startReads.d.ts +14 -0
  274. package/dist/transitions/startReads.js +27 -0
  275. package/dist/transitions/stop.d.ts +10 -0
  276. package/dist/transitions/stop.js +35 -22
  277. package/dist/types/admin.d.ts +1 -1
  278. package/dist/types/contracts.d.ts +7 -1
  279. package/dist/types/endpoints.d.ts +72 -3
  280. package/dist/types/manifest.d.ts +9 -0
  281. package/dist/types/runtime.d.ts +5 -0
  282. package/dist/types/snapshot.d.ts +10 -0
  283. package/dist/types/status.d.ts +1 -0
  284. package/dist/types/status.js +1 -0
  285. package/dist/types/surface.d.ts +1 -0
  286. package/dist/ui/Feedback.d.ts +9 -6
  287. package/dist/ui/Feedback.js +10 -9
  288. package/dist/ui/SelectControl.js +1 -1
  289. package/dist/ui/ui.css +2 -1
  290. package/package.json +2 -2
@@ -1,5 +1,7 @@
1
+ import type { CohortRule, StoredCohortRule } from '../../cohorts/rule.js';
1
2
  import type { EditableField } from '../../types/admin.js';
2
3
  import type { Arm, DocId, ExperimentKind, ExposurePolicy, Status, TargetingRule, UnitType } from '../../types/contracts.js';
4
+ import type { ScheduleWindow } from '../../schedule/types.js';
3
5
  /** The depth-zero collection document, including fields owned by the server. */
4
6
  export interface TestDocument {
5
7
  id: DocId;
@@ -10,9 +12,18 @@ export interface TestDocument {
10
12
  unitType: UnitType;
11
13
  phase?: number;
12
14
  updatedAt?: string;
15
+ startedAt?: string | null;
16
+ pausedAt?: string | null;
17
+ pauseReason?: string | null;
18
+ schedule?: {
19
+ startAt?: string | null;
20
+ endAt?: string | null;
21
+ timeZone?: string | null;
22
+ windows?: ScheduleWindow[] | null;
23
+ } | null;
13
24
  hypothesis?: string | null;
14
25
  arms: Arm[];
15
- targeting?: TargetingRule[] | null;
26
+ targeting?: Array<TargetingRule | CohortRule | StoredCohortRule> | null;
16
27
  allocation: number;
17
28
  pageCollection?: string | null;
18
29
  flagPoint?: string | null;
@@ -10,7 +10,8 @@ const EDITABLE_FIELDS = [
10
10
  'metrics',
11
11
  'analysis',
12
12
  'exposurePolicy',
13
- 'pageCollection'
13
+ 'pageCollection',
14
+ 'schedule'
14
15
  ];
15
16
  /** Drop unknown and locked keys even when the caller is untyped. Groups replace whole groups. */ export function editablePatch(status, partial) {
16
17
  return Object.fromEntries(EDITABLE_FIELDS.flatMap((field)=>Object.hasOwn(partial, field) && partial[field] !== undefined && isEditable(status, field) ? [
@@ -1,8 +1,7 @@
1
1
  'use client';
2
- import { contentLocaleURL } from '../contentLocaleURL.js';
3
2
  import { useCallback, useEffect, useRef, useState } from 'react';
4
3
  import { API_MESSAGES } from '../copy/common.js';
5
- import { documentChanged, readPreflight, statusOrRoundChanged } from '../readPreflight.js';
4
+ import { documentChanged, preflightURL, readPreflight, retainPauseAttribution, statusOrRoundChanged } from '../readPreflight.js';
6
5
  import { XP_IF_UPDATED_AT_HEADER } from '../../constants.js';
7
6
  import { classifyReadinessRead } from '../readinessRead.js';
8
7
  import { TEST_PAGE } from '../copy/testPage.js';
@@ -244,24 +243,27 @@ function adoptDocumentRead(session, doc, unsent) {
244
243
  });
245
244
  }
246
245
  let preflightRevision = 0;
246
+ let lastPreflight;
247
247
  async function refreshPreflight(initial = false, supersede = false) {
248
248
  if (controller.signal.aborted) return;
249
249
  const revision = ++preflightRevision;
250
250
  const requestedLocale = observers.current.contentLocale;
251
+ const requestPreflight = observers.current.requestPreflight;
252
+ const previous = lastPreflight && lastPreflight.locale === requestedLocale ? lastPreflight.answer : undefined;
251
253
  session.preflightLoading = true;
252
254
  session.publish();
253
255
  // createApi has no signal option; this read must abort without cancelling submitted PATCHes.
254
256
  let body;
255
257
  let status = 0;
256
258
  try {
257
- const { response, body: answerBody } = await readPreflight((signal)=>observers.current.requestPreflight?.(signal, supersede) ?? fetch(contentLocaleURL(`${base}/xp/experiments/${encodeURIComponent(documentId)}/preflight`, requestedLocale), {
259
+ const { response, body: answerBody } = await readPreflight((signal)=>requestPreflight?.(signal, supersede) ?? fetch(preflightURL(`${base}/xp/experiments/${encodeURIComponent(documentId)}/preflight`, requestedLocale, previous), {
258
260
  method: 'GET',
259
261
  credentials: 'include',
260
262
  cache: 'no-store',
261
263
  signal
262
264
  }), controller.signal);
263
265
  status = response.status;
264
- body = answerBody;
266
+ body = response.ok && !requestPreflight ? retainPauseAttribution(answerBody, previous) : answerBody;
265
267
  } catch {}
266
268
  if (controller.signal.aborted) return;
267
269
  if (revision !== preflightRevision) return;
@@ -283,11 +285,16 @@ function adoptDocumentRead(session, doc, unsent) {
283
285
  session.preflightFailures = read.failed ? session.preflightFailures + 1 : 0;
284
286
  const data = read.answer;
285
287
  if (data) {
288
+ lastPreflight = {
289
+ locale: requestedLocale,
290
+ answer: data
291
+ };
286
292
  observers.current.onPreflight?.(data);
287
293
  session.view.preflight = data;
288
294
  session.view.preflightError = null;
289
295
  if (initial) session.view.loadState = 'ready';
290
296
  } else {
297
+ if (status === 401 || status === 403 || status === 404) lastPreflight = undefined;
291
298
  session.view.preflight = null;
292
299
  session.view.preflightError = session.view.preflightRead.message ?? null;
293
300
  if (initial) session.view.loadState = session.view.preflightRead.loadState === 'error' ? 'ready' : session.view.preflightRead.loadState;
@@ -1,3 +1,4 @@
1
+ import type { CohortRule, StoredCohortRule } from '../../cohorts/rule.js';
1
2
  import type { TargetingRule } from '../../types/contracts.js';
2
3
  import type { SerializedAttributeKeys } from '../../types/admin.js';
3
4
  import type { TargetingOp } from '../../targeting/ops.js';
@@ -15,7 +16,7 @@ export declare function valueInput(attribute?: Attribute, op?: TargetingOp): {
15
16
  };
16
17
  export declare function coerceValue(type: AttributeType, op: TargetingOp, raw: unknown): string | number | boolean | string[] | null;
17
18
  /** Normalize the read boundary before any whole-group edit. */
18
- export declare function readTargetingRules(rules: TargetingRule[]): TargetingRule[];
19
+ export declare function readTargetingRules<T extends TargetingRule | CohortRule | StoredCohortRule>(rules: T[]): T[];
19
20
  export declare function rowPath(path: string): string;
20
21
  export declare function emptyListHint(op: TargetingOp, value: unknown): string | undefined;
21
22
  export declare function humaniseAttribute(key: string): string;
@@ -40,7 +40,7 @@ export function coerceValue(type, op, raw) {
40
40
  return raw === true || raw === 'true' ? true : raw === false || raw === 'false' ? false : null;
41
41
  }
42
42
  /** Normalize the read boundary before any whole-group edit. */ export function readTargetingRules(rules) {
43
- return rules.map((rule)=>rule.op === 'in' || rule.op === 'nin' ? {
43
+ return rules.map((rule)=>rule.kind !== 'cohort' && (rule.op === 'in' || rule.op === 'nin') ? {
44
44
  ...rule,
45
45
  value: readListValue(rule.value)
46
46
  } : rule);
@@ -16,6 +16,13 @@ export declare function useApi(apiRoute: string): {
16
16
  page?: number;
17
17
  mode?: "block";
18
18
  }, signal?: AbortSignal) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").PagesResult>>;
19
+ cohortSources: (q: string, exclude: import("../types/contracts.js").DocId, signal?: AbortSignal) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").CohortSourcesResult>>;
20
+ buildCohorts: (id: import("../types/contracts.js").DocId) => Promise<import("./api.js").ApiResult<{
21
+ cohorts: Array<{
22
+ key: string;
23
+ members: number;
24
+ }>;
25
+ }>>;
19
26
  previewPageCopy: (id: import("../types/contracts.js").DocId, arm: string, signal?: AbortSignal) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").CopyPagePlan>>;
20
27
  makePageCopy: (id: import("../types/contracts.js").DocId, arm: string, plan: import("../types/endpoints.js").CopyPagePlan) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").CopyPageResult>>;
21
28
  placementStatus: (body: import("../types/endpoints.js").PlacementStatusBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").PlacementStatusResult>>;
@@ -33,6 +40,10 @@ export declare function useApi(apiRoute: string): {
33
40
  fallback?: string;
34
41
  }) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").AddMetricResult>>;
35
42
  stop: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
43
+ pause: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").PauseBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
44
+ resume: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
45
+ reschedule: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").RescheduleBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
46
+ cancelSchedule: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
36
47
  decide: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").DecideBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
37
48
  releaseHoldout: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
38
49
  releasePages: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
@@ -56,5 +67,6 @@ export declare function useApi(apiRoute: string): {
56
67
  recompute: (id: import("../types/contracts.js").DocId) => Promise<import("./api.js").ApiResult<{
57
68
  snapshotId: string;
58
69
  }>>;
70
+ pausedBy: (signal: AbortSignal) => Promise<import("./api.js").ApiResult<Record<string, import("../types/endpoints.js").PauseAttribution>>>;
59
71
  summary: (ids: readonly import("../types/contracts.js").DocId[]) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").SummaryResponse>>;
60
72
  };
@@ -7,12 +7,14 @@ import { withTransition } from './kernel.js';
7
7
  import { readExperiment, refuse, updateExperiment } from './start.js';
8
8
  import { resolveCaps } from './resolveCaps.js';
9
9
  import { requireCurrentRound } from './phaseRecord.js';
10
+ import { requireStarted } from './scheduledRound.js';
10
11
  export async function addMetric(req, { experimentId, metric, role, phase: expectedPhase, options }) {
11
12
  if (role !== 'secondary' && role !== 'guardrail') refuse('invalid-body');
12
13
  const before = await readExperiment(req, experimentId);
13
14
  const openedPhase = before.phase;
14
15
  requireCurrentRound(expectedPhase, openedPhase);
15
- if (before.status !== 'running') refuse('invalid-status');
16
+ if (before.status !== 'running' && before.status !== 'paused') refuse('invalid-status');
17
+ requireStarted(before.startedAt, new Date());
16
18
  const found = await req.payload.find({
17
19
  collection: 'xp-metrics',
18
20
  req,
@@ -66,7 +68,8 @@ export async function addMetric(req, { experimentId, metric, role, phase: expect
66
68
  }, async ({ req, exec })=>{
67
69
  const current = await readExperiment(req, experimentId);
68
70
  requireCurrentRound(expectedPhase ?? openedPhase, current.phase);
69
- if (current.status !== 'running') refuse('invalid-status');
71
+ if (current.status !== 'running' && current.status !== 'paused') refuse('invalid-status');
72
+ requireStarted(current.startedAt, new Date());
70
73
  const ids = [
71
74
  current.metrics?.primary,
72
75
  ...current.metrics?.secondary ?? [],
@@ -1,10 +1,12 @@
1
1
  import { XpRefusal } from '../errors.js';
2
2
  import { appendAllocationChange } from '../db/appends.js';
3
3
  import { claimSlices } from '../db/slices.js';
4
+ import { storedClaim } from '../db/occupancy.js';
4
5
  import { relationshipId } from './checkStart.js';
5
6
  import { withTransition } from './kernel.js';
6
7
  import { requireCurrentRound } from './phaseRecord.js';
7
8
  import { readExperiment, refuse, updateExperiment } from './start.js';
9
+ import { requireStarted } from './scheduledRound.js';
8
10
  export async function allocate(req, { experimentId, allocation, phase: expectedPhase }) {
9
11
  if (!Number.isInteger(allocation) || allocation < 1 || allocation > 100) refuse('invalid-body');
10
12
  const before = await readExperiment(req, experimentId);
@@ -14,7 +16,9 @@ export async function allocate(req, { experimentId, allocation, phase: expectedP
14
16
  }, async ({ req, exec })=>{
15
17
  const current = await readExperiment(req, experimentId);
16
18
  requireCurrentRound(expectedPhase, current.phase);
19
+ if (current.status === 'paused') refuse('paused');
17
20
  if (current.status !== 'running') refuse('invalid-status');
21
+ requireStarted(current.startedAt, new Date());
18
22
  if (allocation <= current.allocation) refuse('allocation-lower');
19
23
  const layerId = relationshipId(current.layer);
20
24
  const layerSlices = layerId === undefined ? [] : [
@@ -22,7 +26,8 @@ export async function allocate(req, { experimentId, allocation, phase: expectedP
22
26
  ...await claimSlices(exec, {
23
27
  layerId,
24
28
  experimentId,
25
- count: allocation - current.allocation
29
+ count: allocation - current.allocation,
30
+ claim: storedClaim(current)
26
31
  })
27
32
  ].sort((a, b)=>a - b);
28
33
  await appendAllocationChange(exec, {
@@ -0,0 +1,9 @@
1
+ import type { Claim } from '../schedule/ranges.js';
2
+ import type { Executor } from '../db/executor.js';
3
+ import { type StartExperiment } from './checkStart.js';
4
+ /** The caller holds the relevant layer, flag point and page path locks.
5
+ * Start reserves new slices with claimSlices; an existing claim supplies its exact slices here.
6
+ */
7
+ export declare function assertNoOverlap(executor: Executor, experiment: Pick<StartExperiment, 'id' | 'kind' | 'flagPoint' | 'arms' | 'layer'> & {
8
+ layerSlices?: number[] | null;
9
+ }, claim: Claim): Promise<void>;
@@ -0,0 +1,24 @@
1
+ import { flagPointClaims, overlapsClaim, refuseOccupancy } from '../db/occupancy.js';
2
+ import { routedPageTests } from '../db/pageOccupancy.js';
3
+ import { layerClaims } from '../db/slices.js';
4
+ import { pageTargetPaths, relationshipId } from './checkStart.js';
5
+ /** The caller holds the relevant layer, flag point and page path locks.
6
+ * Start reserves new slices with claimSlices; an existing claim supplies its exact slices here.
7
+ */ export async function assertNoOverlap(executor, experiment, claim) {
8
+ const otherOverlaps = (row)=>String(row.id) !== String(experiment.id) && overlapsClaim(row, claim);
9
+ if (experiment.kind === 'flag' && experiment.flagPoint) {
10
+ const other = (await flagPointClaims(executor, experiment.flagPoint)).find(otherOverlaps);
11
+ if (other) refuseOccupancy(other, 'setting');
12
+ }
13
+ if (experiment.kind === 'page') {
14
+ const paths = new Set(pageTargetPaths(experiment.arms));
15
+ const other = (await routedPageTests(executor)).find((row)=>otherOverlaps(row) && pageTargetPaths(row.arms).some((path)=>paths.has(path)));
16
+ if (other) refuseOccupancy(other, 'page');
17
+ }
18
+ const layerId = relationshipId(experiment.layer);
19
+ if (layerId !== undefined && experiment.layerSlices?.length) {
20
+ const mine = new Set(experiment.layerSlices);
21
+ const other = (await layerClaims(executor, layerId)).find((row)=>otherOverlaps(row) && row.slices?.some((slice)=>mine.has(slice)));
22
+ if (other) refuseOccupancy(other, 'traffic group');
23
+ }
24
+ }
@@ -0,0 +1,10 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { DocId, ResolvedOptions } from '../types/contracts.js';
3
+ export declare function buildCohortsNow<TUser extends {
4
+ id: DocId;
5
+ }>(req: PayloadRequest, experimentId: DocId, options: ResolvedOptions<TUser>): Promise<{
6
+ cohorts: {
7
+ key: string;
8
+ members: number;
9
+ }[];
10
+ }>;
@@ -0,0 +1,68 @@
1
+ import { deriveCohort, cohortBuildTimeout } from '../cohorts/build.js';
2
+ import { inCohortTransaction } from '../db/cohortTransactions.js';
3
+ import { checkCohorts } from '../cohorts/readiness.js';
4
+ import { cohortReadRequest, freezeCohortTargeting, loadCohortFacts } from '../cohorts/readinessData.js';
5
+ import { isCohortRule } from '../cohorts/rule.js';
6
+ import { isCohortTimeout, readCohort, withCohortTimeout } from '../db/cohorts.js';
7
+ import { lockCohortErasure, lockCohorts, lockTransitionScope, sortLockKeys } from '../db/locks.js';
8
+ import { raceDeadline } from '../db/executor.js';
9
+ import { resultsExecutor } from '../db/snapshots.js';
10
+ import { readStartInputExperiment } from './preflightData.js';
11
+ import { refuse } from './start.js';
12
+ import { XpRefusal } from '../errors.js';
13
+ const BUILD_NOW_BUDGET_MS = 55_000;
14
+ export async function buildCohortsNow(req, experimentId, options) {
15
+ const now = new Date();
16
+ const deadline = +now + BUILD_NOW_BUDGET_MS;
17
+ const readExec = resultsExecutor(req.payload, ()=>deadline - Date.now());
18
+ let keys = [];
19
+ const cohorts = [];
20
+ try {
21
+ const experiment = await raceDeadline(deadline, ()=>readStartInputExperiment(cohortReadRequest(req), experimentId));
22
+ if (!experiment) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
23
+ if (experiment.status !== 'draft' && experiment.status !== 'stopped') refuse('invalid-status');
24
+ if (!experiment.targeting?.some(isCohortRule)) return {
25
+ cohorts
26
+ };
27
+ const facts = await loadCohortFacts(req, readExec, experiment, options, false, now, deadline);
28
+ const checks = checkCohorts(experiment, facts);
29
+ if (checks.length) refuse(checks[0].code, {
30
+ ...checks[0].detail,
31
+ checks
32
+ });
33
+ const { rules, sources } = freezeCohortTargeting(experiment, facts);
34
+ keys = sortLockKeys(rules.map((rule)=>rule.key));
35
+ for (const key of keys){
36
+ const rule = rules.find((rule)=>rule.key === key);
37
+ const result = await inCohortTransaction(req.payload, deadline, (exec)=>withCohortTimeout(exec, deadline, async (timed)=>{
38
+ await lockTransitionScope(timed, {
39
+ experimentId
40
+ });
41
+ const current = await raceDeadline(deadline, ()=>readStartInputExperiment(cohortReadRequest(req), experimentId));
42
+ if (current?.status !== 'draft' && current?.status !== 'stopped') refuse('invalid-status');
43
+ if (experiment.updatedAt !== current.updatedAt) refuse('stale-draft');
44
+ await lockCohortErasure(timed);
45
+ await lockCohorts(timed, [
46
+ key
47
+ ]);
48
+ const ready = await readCohort(timed, key);
49
+ return ready ?? deriveCohort(timed, rule, {
50
+ now,
51
+ options,
52
+ readExec,
53
+ source: sources.get(key)
54
+ }, deadline);
55
+ }));
56
+ cohorts.push({
57
+ key,
58
+ members: result.members
59
+ });
60
+ }
61
+ } catch (error) {
62
+ if (isCohortTimeout(error) || error instanceof XpRefusal && error.code === 'cohort-build-timeout') throw cohortBuildTimeout(keys);
63
+ throw error;
64
+ }
65
+ return {
66
+ cohorts
67
+ };
68
+ }
@@ -0,0 +1,4 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ import type { RoundBody, TransitionSuccess } from '../types/endpoints.js';
4
+ export declare function cancelSchedule(req: PayloadRequest, id: DocId, { phase: expectedPhase }?: RoundBody): Promise<TransitionSuccess>;
@@ -0,0 +1,42 @@
1
+ import { hasPhaseExposures } from '../db/events.js';
2
+ import { readLatestPhase, readPhaseRecord, requireCurrentRound } from './phaseRecord.js';
3
+ import { clearPauseFields, startsInFuture, withScheduledRound } from './scheduledRound.js';
4
+ import { refuse, updateExperiment } from './start.js';
5
+ export async function cancelSchedule(req, id, { phase: expectedPhase } = {}) {
6
+ return withScheduledRound(req, id, async (req, exec, current)=>{
7
+ requireCurrentRound(expectedPhase, current.phase);
8
+ if (current.status !== 'running' || !startsInFuture(current.startedAt, new Date())) refuse('schedule-started');
9
+ const phase = await readPhaseRecord(req, id, current.phase);
10
+ if (await hasPhaseExposures(exec, id, phase.phase) || !startsInFuture(current.startedAt, new Date())) refuse('schedule-started');
11
+ // §7.8: Cancel schedule removes its unopened phase in the transition transaction.
12
+ await req.payload.delete({
13
+ collection: 'xp-phases',
14
+ id: phase.id,
15
+ req,
16
+ overrideAccess: true
17
+ });
18
+ const previous = await readLatestPhase(req, id);
19
+ if (!startsInFuture(current.startedAt, new Date())) refuse('schedule-started');
20
+ const beforeSchedule = phase.analysis?.beforeSchedule;
21
+ return updateExperiment(req, id, {
22
+ status: previous ? 'stopped' : 'draft',
23
+ phase: previous?.phase ?? 0,
24
+ seed: previous?.seed ?? null,
25
+ startedAt: previous?.startedAt ?? null,
26
+ stoppedAt: previous?.endedAt ?? null,
27
+ claimFrom: null,
28
+ claimTo: null,
29
+ layerSlices: [],
30
+ ...clearPauseFields,
31
+ ...beforeSchedule?.arms ? {
32
+ arms: beforeSchedule.arms
33
+ } : {},
34
+ ...beforeSchedule?.timeZone !== undefined ? {
35
+ schedule: {
36
+ ...current.schedule,
37
+ timeZone: beforeSchedule.timeZone
38
+ }
39
+ } : {}
40
+ });
41
+ });
42
+ }
@@ -1,8 +1,10 @@
1
+ import { type CohortFacts, type CohortReadinessCode } from '../cohorts/readiness.js';
2
+ import type { CohortRule } from '../cohorts/rule.js';
1
3
  import { type GoalContent } from '../goals/fairness.js';
2
4
  import type { Arm, DocId, ExperimentKind, ExposurePolicy, FlagPoint, MetricSource, ResolvedOptions, Status, TargetingRule, UnitType } from '../types/contracts.js';
3
- import type { ArmIssueCode, PreflightResult } from '../types/endpoints.js';
5
+ import type { ArmIssueCode, OccupiedInRangeDetail, PreflightResult } from '../types/endpoints.js';
4
6
  import type { BlockPlacement, FlagPlacement } from './placements.js';
5
- export type ReadinessCode = ArmIssueCode | 'nested-tests' | 'goal-in-some-versions' | 'placement-unchecked' | 'invalid-status' | 'no-planned-duration' | 'no-primary-metric' | 'no-reach-per-day' | 'placement-unpublished' | 'duplicate-version-row' | 'interacting-tests' | 'version-identical' | 'version-same-address' | 'unknown-collection' | 'page-no-targets' | 'page-in-use' | 'page-target-unpublished' | 'page-targets-unchecked' | 'version-page-unavailable' | 'version-page-unchecked' | 'page-user-unit' | 'flag-no-point' | 'flag-params-invalid' | 'flag-point-busy' | 'flag-placement-missing' | 'no-placements' | 'placement-removed' | 'empty-slot' | 'make-content-unsupported' | 'layer-unit-mismatch' | 'layer-full' | 'unknown-metric-source' | 'unit-source-mismatch' | 'block-path-rule' | 'undeclared-targeting-key' | 'invalid-targeting-rule';
7
+ export type ReadinessCode = ArmIssueCode | CohortReadinessCode | 'nested-tests' | 'goal-in-some-versions' | 'placement-unchecked' | 'invalid-status' | 'no-planned-duration' | 'no-primary-metric' | 'no-reach-per-day' | 'placement-unpublished' | 'duplicate-version-row' | 'interacting-tests' | 'version-identical' | 'version-same-address' | 'unknown-collection' | 'page-no-targets' | 'page-in-use' | 'page-target-unpublished' | 'page-targets-unchecked' | 'version-page-unavailable' | 'version-page-unchecked' | 'page-user-unit' | 'flag-no-point' | 'flag-params-invalid' | 'flag-point-busy' | 'flag-placement-missing' | 'no-placements' | 'placement-removed' | 'empty-slot' | 'make-content-unsupported' | 'layer-unit-mismatch' | 'layer-full' | 'unknown-metric-source' | 'unit-source-mismatch' | 'block-path-rule' | 'cohort-build-timeout' | 'undeclared-targeting-key' | 'invalid-targeting-rule';
6
8
  export interface StartExperiment {
7
9
  id: DocId;
8
10
  slug: string;
@@ -11,7 +13,15 @@ export interface StartExperiment {
11
13
  unitType: UnitType;
12
14
  phase?: number;
13
15
  updatedAt?: string;
16
+ pausedAt?: string | null;
17
+ pausedBy?: string | null;
14
18
  pageCollection?: string | null;
19
+ schedule?: {
20
+ startAt?: string | null;
21
+ endAt?: string | null;
22
+ timeZone?: string | null;
23
+ windows?: import('../schedule/types.js').ScheduleWindow[] | null;
24
+ } | null;
15
25
  arms: Arm[];
16
26
  allocation: number;
17
27
  exposurePolicy: ExposurePolicy;
@@ -19,7 +29,7 @@ export interface StartExperiment {
19
29
  layer?: DocId | {
20
30
  id: DocId;
21
31
  } | null;
22
- targeting?: TargetingRule[] | null;
32
+ targeting?: Array<TargetingRule | CohortRule> | null;
23
33
  metrics?: {
24
34
  primary?: DocId | {
25
35
  id: DocId;
@@ -57,6 +67,7 @@ export interface CheckStartInput {
57
67
  placementError?: PlacementFailure;
58
68
  flagPlacementError?: PlacementFailure;
59
69
  flagPointBusy?: boolean;
70
+ flagOccupancy?: OccupiedInRangeDetail;
60
71
  goalContent?: GoalContent;
61
72
  interactions?: import('./placementInteractions.js').InteractionDetail[];
62
73
  unknownPageCollection?: boolean;
@@ -69,11 +80,14 @@ export interface CheckStartInput {
69
80
  unpublishedPageTargets?: string[];
70
81
  pageTargetsUnchecked?: boolean;
71
82
  pageTestsInUse?: Pick<StartExperiment, 'id' | 'arms'>[];
83
+ pageOccupancy?: OccupiedInRangeDetail;
84
+ layerOccupancy?: OccupiedInRangeDetail;
72
85
  layer?: {
73
86
  unitType: UnitType;
74
87
  usedSlices: number[];
75
88
  } | null;
76
89
  attributeKeys?: ResolvedOptions['attributeKeys'];
90
+ cohortFacts?: CohortFacts;
77
91
  }
78
92
  export declare const ARM_CHECK_ORDER: readonly ArmIssueCode[];
79
93
  export declare const relationshipId: (value: DocId | {
@@ -1,3 +1,4 @@
1
+ import { checkCohorts } from '../cohorts/readiness.js';
1
2
  import { placementLanguageSuffix } from '../testSurface/copy/languages.js';
2
3
  import { asymmetricGoal } from '../goals/fairness.js';
3
4
  import { withSlotsFor } from '../arms/model.js';
@@ -170,7 +171,10 @@ function invalidParams(arms, point) {
170
171
  const occupiedPaths = new Set((input.pageTestsInUse ?? []).filter((other)=>String(other.id) !== String(e.id)).flatMap((other)=>pageTargetPaths(other.arms)));
171
172
  const sharedPaths = e.kind === 'page' ? pageTargetPaths(e.arms).filter((path)=>occupiedPaths.has(path)) : [];
172
173
  add('page-in-use', sharedPaths.length === 0, {
173
- paths: sharedPaths
174
+ paths: sharedPaths,
175
+ ...input.pageOccupancy ? {
176
+ occupancy: input.pageOccupancy
177
+ } : {}
174
178
  });
175
179
  add('page-target-unpublished', !input.unpublishedPageTargets?.length, input.unpublishedPageTargets?.[0]);
176
180
  add('page-targets-unchecked', true);
@@ -180,7 +184,9 @@ function invalidParams(arms, point) {
180
184
  add('flag-no-point', e.kind !== 'flag' || !!point);
181
185
  const params = e.kind === 'flag' && point ? invalidParams(e.arms, point) : [];
182
186
  add('flag-params-invalid', params.length === 0, params);
183
- add('flag-point-busy', e.kind !== 'flag' || !input.flagPointBusy);
187
+ add('flag-point-busy', e.kind !== 'flag' || !input.flagPointBusy, input.flagOccupancy ? {
188
+ occupancy: input.flagOccupancy
189
+ } : undefined);
184
190
  const missing = input.flagPlacements === undefined ? [] : e.arms.filter((arm)=>arm.kind !== 'holdout' && !input.flagPlacements.some((placement)=>placement.arm === arm.key && placement.ok));
185
191
  const failed = input.flagPlacements?.filter((placement)=>!placement.ok) ?? [];
186
192
  add('flag-placement-missing', e.kind !== 'flag' || !input.flagPlacementError && missing.length === 0 && failed.length === 0, input.flagPlacementError ?? {
@@ -263,7 +269,10 @@ function invalidParams(arms, point) {
263
269
  const free = 100 - new Set(input.layer?.usedSlices).size;
264
270
  add('layer-full', e.layer == null || !!input.layer && free >= e.allocation, {
265
271
  available: free,
266
- requested: e.allocation
272
+ requested: e.allocation,
273
+ ...input.layerOccupancy ? {
274
+ occupancy: input.layerOccupancy
275
+ } : {}
267
276
  });
268
277
  for (const detail of input.goalContent?.unchecked ?? [])checks.push({
269
278
  code: 'placement-unchecked',
@@ -299,18 +308,19 @@ function invalidParams(arms, point) {
299
308
  id,
300
309
  source
301
310
  })));
302
- const pathRules = (e.targeting ?? []).flatMap((rule, index)=>rule.attribute === 'path' ? [
311
+ const pathRules = (e.targeting ?? []).flatMap((rule, index)=>rule.kind !== 'cohort' && rule.attribute === 'path' ? [
303
312
  index
304
313
  ] : []);
305
314
  add('block-path-rule', e.kind !== 'block' || pathRules.length === 0, {
306
315
  rules: pathRules
307
316
  });
308
- const undeclared = (e.targeting ?? []).filter((rule)=>!Object.hasOwn(input.attributeKeys ?? {}, rule.attribute));
317
+ const attributeRules = (e.targeting ?? []).filter((rule)=>rule.kind !== 'cohort');
318
+ const undeclared = attributeRules.filter((rule)=>!Object.hasOwn(input.attributeKeys ?? {}, rule.attribute));
309
319
  add('undeclared-targeting-key', undeclared.length === 0, {
310
320
  message: 'Targeting uses an undeclared attribute.',
311
321
  attributes: undeclared.map((rule)=>rule.attribute)
312
322
  });
313
- const invalidRules = (e.targeting ?? []).filter((rule)=>{
323
+ const invalidRules = attributeRules.filter((rule)=>{
314
324
  const type = Object.hasOwn(input.attributeKeys ?? {}, rule.attribute) ? input.attributeKeys[rule.attribute].type : undefined;
315
325
  if (!type) return false // Report undeclared keys through their own refusal.
316
326
  ;
@@ -323,5 +333,8 @@ function invalidParams(arms, point) {
323
333
  add('invalid-targeting-rule', invalidRules.length === 0, {
324
334
  attributes: invalidRules.map((rule)=>rule.attribute)
325
335
  });
326
- return checks;
336
+ return [
337
+ ...checks,
338
+ ...checkCohorts(e, input.cohortFacts)
339
+ ];
327
340
  }
@@ -7,11 +7,14 @@ import { reclaimSlices } from '../db/slices.js';
7
7
  import { decideGuard } from '../results/decideGuard.js';
8
8
  import { lockPagePaths } from '../db/locks.js';
9
9
  import { routedPageTests } from '../db/pageOccupancy.js';
10
+ import { OCCUPYING_STATUSES, overlapsClaim } from '../db/occupancy.js';
11
+ import { assertNoOverlap } from './assertNoOverlap.js';
10
12
  import { pageTargetPaths, relationshipId } from './checkStart.js';
11
13
  import { expectedConfirm, matchesConfirm, storedWinnerLabel } from './confirmPhrases.js';
12
14
  import { withTransition } from './kernel.js';
13
15
  import { requireCurrentRound, readPhaseRecord, setPhaseEndedAt, writePhaseRecord } from './phaseRecord.js';
14
16
  import { readExperiment, refuse, updateExperiment } from './start.js';
17
+ import { requireStarted } from './scheduledRound.js';
15
18
  export async function decide(req, { experimentId, winnerArm, note, confirmation, phase: expectedPhase }) {
16
19
  const before = await readExperiment(req, experimentId);
17
20
  const options = req.payload.config.custom?.xp;
@@ -23,8 +26,14 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation,
23
26
  }, async ({ req, exec })=>{
24
27
  const current = await readExperiment(req, experimentId);
25
28
  requireCurrentRound(expectedPhase, current.phase);
26
- if (current.status !== 'running' && current.status !== 'stopped') refuse('invalid-status');
27
- if (current.kind === 'flag' && current.flagPoint) {
29
+ const open = current.status === 'running' || current.status === 'paused';
30
+ if (!open && current.status !== 'stopped') refuse('invalid-status');
31
+ requireStarted(current.startedAt, new Date());
32
+ const claim = {
33
+ from: new Date(),
34
+ to: null
35
+ };
36
+ if (current.kind === 'flag' && current.flagPoint && !(open && current.claimTo)) {
28
37
  // §7.8: recheck point occupancy under its lock before restoring live routing.
29
38
  const busy = await req.payload.find({
30
39
  collection: 'xp-experiments',
@@ -41,16 +50,13 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation,
41
50
  },
42
51
  {
43
52
  status: {
44
- in: [
45
- 'running',
46
- 'decided'
47
- ]
53
+ in: OCCUPYING_STATUSES
48
54
  }
49
55
  }
50
56
  ]
51
57
  }
52
58
  });
53
- if (busy.docs.some((doc)=>String(doc.id) !== String(experimentId))) refuse('flag-point-busy');
59
+ if (busy.docs.some((doc)=>String(doc.id) !== String(experimentId) && overlapsClaim(doc, claim))) refuse('flag-point-busy');
54
60
  }
55
61
  const test = await readPhaseRecord(req, experimentId, current.phase);
56
62
  if (test.phaseKind !== 'test') refuse('invalid-status');
@@ -69,7 +75,7 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation,
69
75
  const mine = pageTargetPaths(test.arms);
70
76
  await lockPagePaths(exec, mine);
71
77
  // Other tests' routed (frozen-round) arms, as the runtime matches them.
72
- const occupied = new Set((await routedPageTests(exec)).filter((other)=>String(other.id) !== String(experimentId)).flatMap((other)=>pageTargetPaths(other.arms)));
78
+ const occupied = new Set((await routedPageTests(exec)).filter((other)=>String(other.id) !== String(experimentId) && overlapsClaim(other, claim)).flatMap((other)=>pageTargetPaths(other.arms)));
73
79
  const shared = mine.filter((path)=>occupied.has(path));
74
80
  if (shared.length) refuse('page-in-use', {
75
81
  paths: shared
@@ -118,20 +124,36 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation,
118
124
  const snapshotDoc = snapshots.docs[0];
119
125
  const snapshot = snapshotDoc?.snapshot;
120
126
  if (decideGuard(snapshot ?? null, winnerArm) && (!note?.trim() || !matchesConfirm(expectedConfirm('decide', storedWinnerLabel(winner)), confirmation))) refuse('confirmation-required');
121
- const at = new Date().toISOString();
122
127
  const holdout = test.arms.find((arm)=>arm.kind === 'holdout');
123
128
  const rollout = holdout !== undefined && winner.kind !== 'control';
124
129
  let slices = current.layerSlices ?? [];
130
+ if (open && current.claimTo) {
131
+ // Deciding removes the schedule end. A later reservation must still be usable.
132
+ if (current.kind === 'page') await lockPagePaths(exec, pageTargetPaths(test.arms));
133
+ await assertNoOverlap(exec, {
134
+ ...current,
135
+ arms: test.arms,
136
+ layerSlices: rollout ? slices : []
137
+ }, {
138
+ from: new Date(),
139
+ to: null
140
+ });
141
+ }
125
142
  if (rollout && current.status === 'stopped' && relationshipId(current.layer) !== undefined) {
126
143
  const original = test.analysis?.layerSlices;
127
144
  if (!Array.isArray(original) || original.length !== test.allocation || !original.every((slice)=>Number.isInteger(slice) && slice >= 0 && slice < 100) || new Set(original).size !== original.length) refuse('slices-taken');
128
145
  slices = await reclaimSlices(exec, {
129
146
  layerId: relationshipId(current.layer),
130
147
  experimentId,
131
- slices: original
148
+ slices: original,
149
+ claim
132
150
  });
133
151
  }
134
- await setPhaseEndedAt(req, experimentId, test.phase, at);
152
+ const at = new Date().toISOString();
153
+ const scheduledEnd = test.schedule?.endAt;
154
+ const endedAt = current.status === 'paused' ? current.pausedAt : scheduledEnd && new Date(scheduledEnd) < new Date(at) ? new Date(scheduledEnd).toISOString() : at;
155
+ if (!endedAt) refuse('invalid-phase');
156
+ await setPhaseEndedAt(req, experimentId, test.phase, endedAt);
135
157
  const phase = rollout ? test.phase + 1 : test.phase;
136
158
  if (rollout) {
137
159
  const arms = [
@@ -168,6 +190,8 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation,
168
190
  phase,
169
191
  seed: test.seed,
170
192
  decidedAt: at,
193
+ claimFrom: at,
194
+ claimTo: null,
171
195
  layerSlices: rollout ? slices : [],
172
196
  decision: {
173
197
  winnerArm,
@@ -9,8 +9,10 @@ export interface TransitionScope {
9
9
  bump?: boolean;
10
10
  /** Best-effort content audit only; a borrowed transaction must never be killed here. */
11
11
  audit?: boolean;
12
- /** Trusted server-side Start must commit its own transaction. Preflight passes the request to host callbacks. */
12
+ /** Trusted system transitions must commit their own transactions. */
13
13
  requireOwnedTransaction?: boolean;
14
+ /** Limit statement time for a scheduled stop run by results. */
15
+ deadline?: number;
14
16
  /** Guard an ordinary access-checked edit without bypassing the collection's lock hook. */
15
17
  edit?: boolean;
16
18
  excludeIds?: DocId[];