@delmaredigital/payload-experiments 0.4.0-rc.7 → 0.4.0-rc.9

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 (221) hide show
  1. package/README.md +12 -12
  2. package/dist/admin/blocks/model.js +2 -2
  3. package/dist/admin/copy/blocks.js +1 -1
  4. package/dist/admin/surface/ResultsRoute.js +17 -11
  5. package/dist/admin/surface/TestsHome.js +53 -20
  6. package/dist/admin/surface/newTest/PageWizard.js +8 -2
  7. package/dist/admin/surface/results/ResultsHeader.js +11 -6
  8. package/dist/admin/surface/test/TestPage.js +3 -3
  9. package/dist/blocks/formState.js +1 -1
  10. package/dist/collections/experiments/config.js +8 -3
  11. package/dist/collections/experiments/deleteGuard.js +2 -2
  12. package/dist/collections/experiments/lockHook.js +21 -2
  13. package/dist/collections/experiments/pickSlug.js +2 -0
  14. package/dist/collections/metricsGuards.js +2 -0
  15. package/dist/collections/serialize.js +5 -4
  16. package/dist/constants.d.ts +1 -0
  17. package/dist/constants.js +1 -0
  18. package/dist/db/adapter.d.ts +9 -1
  19. package/dist/db/adapter.js +77 -1
  20. package/dist/db/delete.d.ts +1 -1
  21. package/dist/db/delete.js +2 -4
  22. package/dist/db/events.d.ts +9 -0
  23. package/dist/db/events.js +42 -8
  24. package/dist/db/executor.d.ts +7 -1
  25. package/dist/db/executor.js +7 -3
  26. package/dist/db/results.d.ts +5 -1
  27. package/dist/db/results.js +21 -5
  28. package/dist/db/snapshots.d.ts +1 -0
  29. package/dist/endpoints/deleteImpact.js +2 -1
  30. package/dist/endpoints/events.js +103 -39
  31. package/dist/endpoints/index.js +2 -8
  32. package/dist/endpoints/placementStatus.js +7 -4
  33. package/dist/endpoints/results.d.ts +1 -1
  34. package/dist/endpoints/results.js +6 -2
  35. package/dist/endpoints/routeId.d.ts +2 -2
  36. package/dist/endpoints/routeId.js +11 -5
  37. package/dist/endpoints/summary.js +46 -12
  38. package/dist/endpoints/transitions.js +37 -24
  39. package/dist/errors.d.ts +4 -0
  40. package/dist/errors.js +6 -0
  41. package/dist/events/request.d.ts +6 -2
  42. package/dist/events/request.js +35 -8
  43. package/dist/events/rows.d.ts +1 -1
  44. package/dist/events/rows.js +24 -8
  45. package/dist/events/writable.d.ts +9 -0
  46. package/dist/events/writable.js +13 -0
  47. package/dist/exports/index.d.ts +1 -1
  48. package/dist/exports/rsc.d.ts +1 -0
  49. package/dist/exports/rsc.js +1 -0
  50. package/dist/goals/fairness.js +2 -2
  51. package/dist/hooks/hostHook.js +6 -2
  52. package/dist/hooks/pageGuard.js +4 -0
  53. package/dist/lib/fetchAllDocs.d.ts +1 -1
  54. package/dist/manifest/compile.js +8 -5
  55. package/dist/onInit.js +14 -0
  56. package/dist/options.js +5 -0
  57. package/dist/proxy/pageNavigation.d.ts +4 -0
  58. package/dist/proxy/pageNavigation.js +28 -0
  59. package/dist/proxy/resolve.js +52 -25
  60. package/dist/puck/editor/ConfigureTestDrawer.js +5 -4
  61. package/dist/puck/editor/ExperimentSlotEditor.js +182 -58
  62. package/dist/puck/editor/QuickTestActions.d.ts +5 -2
  63. package/dist/puck/editor/QuickTestActions.js +16 -4
  64. package/dist/puck/editor/ResultsReadout.d.ts +2 -1
  65. package/dist/puck/editor/ResultsReadout.js +2 -1
  66. package/dist/puck/editor/VersionBuilder.d.ts +13 -2
  67. package/dist/puck/editor/VersionBuilder.js +133 -49
  68. package/dist/puck/editor/armWrites.js +1 -1
  69. package/dist/puck/editor/armsCache.js +1 -3
  70. package/dist/puck/editor/copy.d.ts +4 -1
  71. package/dist/puck/editor/copy.js +4 -1
  72. package/dist/puck/editor/editor.chrome.css +1 -0
  73. package/dist/puck/editor/editor.css +1 -0
  74. package/dist/puck/editor/editor.model.d.ts +1 -0
  75. package/dist/puck/editor/placementsCache.d.ts +5 -1
  76. package/dist/puck/editor/placementsCache.js +17 -9
  77. package/dist/puck/editor/usePageSaveReadiness.d.ts +9 -0
  78. package/dist/puck/editor/usePageSaveReadiness.js +34 -0
  79. package/dist/puck/editor/usePlacementNotice.d.ts +2 -2
  80. package/dist/puck/editor/usePlacementNotice.js +5 -4
  81. package/dist/results/aggregate.d.ts +6 -3
  82. package/dist/results/aggregate.js +9 -9
  83. package/dist/results/health.d.ts +8 -0
  84. package/dist/results/health.js +28 -0
  85. package/dist/results/identityCredit.d.ts +1 -0
  86. package/dist/results/identityCredit.js +4 -1
  87. package/dist/results/verdict.js +2 -1
  88. package/dist/runtime/cookie.d.ts +10 -2
  89. package/dist/runtime/cookie.js +38 -6
  90. package/dist/runtime/cookieOptions.d.ts +6 -0
  91. package/dist/runtime/cookieOptions.js +14 -0
  92. package/dist/runtime/proxyRuntime.d.ts +1 -0
  93. package/dist/runtime/proxyRuntime.js +18 -8
  94. package/dist/runtime/signing.d.ts +1 -0
  95. package/dist/runtime/signing.js +5 -0
  96. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  97. package/dist/sanitizeReadinessDetail.js +20 -2
  98. package/dist/server/getAssignments.js +11 -10
  99. package/dist/server/recordContentChange.d.ts +1 -1
  100. package/dist/server/recordContentChange.js +11 -2
  101. package/dist/server/resolveExperimentBlocks.js +2 -4
  102. package/dist/server/resolveExperimentData.js +2 -5
  103. package/dist/server/runResults.js +52 -14
  104. package/dist/server/startExperiment.d.ts +20 -0
  105. package/dist/server/startExperiment.js +70 -0
  106. package/dist/server/trackConversion.js +10 -13
  107. package/dist/testSurface/actions/DecideDialog.d.ts +4 -1
  108. package/dist/testSurface/actions/DecideDialog.js +32 -14
  109. package/dist/testSurface/actions/MakeContentResult.d.ts +4 -3
  110. package/dist/testSurface/actions/MakeContentResult.js +9 -1
  111. package/dist/testSurface/api.d.ts +5 -5
  112. package/dist/testSurface/api.js +21 -9
  113. package/dist/testSurface/copy/actions.d.ts +1 -0
  114. package/dist/testSurface/copy/actions.js +1 -0
  115. package/dist/testSurface/copy/common.d.ts +3 -1
  116. package/dist/testSurface/copy/common.js +4 -2
  117. package/dist/testSurface/copy/languages.d.ts +1 -0
  118. package/dist/testSurface/copy/languages.js +1 -0
  119. package/dist/testSurface/copy/metrics.d.ts +1 -0
  120. package/dist/testSurface/copy/metrics.js +1 -0
  121. package/dist/testSurface/copy/readiness.d.ts +12 -1
  122. package/dist/testSurface/copy/readiness.js +18 -1
  123. package/dist/testSurface/copy/results.d.ts +5 -2
  124. package/dist/testSurface/copy/results.js +5 -2
  125. package/dist/testSurface/copy/testPage.d.ts +20 -2
  126. package/dist/testSurface/copy/testPage.js +34 -3
  127. package/dist/testSurface/readPreflight.d.ts +5 -0
  128. package/dist/testSurface/readPreflight.js +7 -0
  129. package/dist/testSurface/readinessRead.d.ts +3 -0
  130. package/dist/testSurface/readinessRead.js +4 -0
  131. package/dist/testSurface/results/VerdictHero.d.ts +2 -1
  132. package/dist/testSurface/results/VerdictHero.js +5 -1
  133. package/dist/testSurface/results/results.model.d.ts +1 -1
  134. package/dist/testSurface/results/results.model.js +6 -2
  135. package/dist/testSurface/surface/contracts.d.ts +8 -1
  136. package/dist/testSurface/surface/editorPlacement.d.ts +2 -2
  137. package/dist/testSurface/surface/editorPlacement.js +1 -1
  138. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +2 -2
  139. package/dist/testSurface/surface/pagePicker/PageCombobox.js +20 -6
  140. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +4 -2
  141. package/dist/testSurface/surface/readiness/ActionDialogs.js +39 -34
  142. package/dist/testSurface/surface/readiness/Banner.js +23 -12
  143. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +4 -3
  144. package/dist/testSurface/surface/readiness/SaveStatus.js +15 -15
  145. package/dist/testSurface/surface/readiness/readiness.model.d.ts +6 -1
  146. package/dist/testSurface/surface/readiness/readiness.model.js +108 -11
  147. package/dist/testSurface/surface/readiness/useTransition.d.ts +4 -4
  148. package/dist/testSurface/surface/readiness/useTransition.js +12 -10
  149. package/dist/testSurface/surface/results/ReleasePages.d.ts +4 -2
  150. package/dist/testSurface/surface/results/ReleasePages.js +5 -4
  151. package/dist/testSurface/surface/results/ResultsBody.d.ts +4 -2
  152. package/dist/testSurface/surface/results/ResultsBody.js +86 -43
  153. package/dist/testSurface/surface/results/useResults.d.ts +7 -6
  154. package/dist/testSurface/surface/results/useResults.js +3 -2
  155. package/dist/testSurface/surface/setting/parts.js +58 -18
  156. package/dist/testSurface/surface/test/AdvancedSection.js +1 -0
  157. package/dist/testSurface/surface/test/DeleteTest.d.ts +6 -2
  158. package/dist/testSurface/surface/test/DeleteTest.js +145 -54
  159. package/dist/testSurface/surface/test/GoalSection.js +7 -3
  160. package/dist/testSurface/surface/test/LengthSection.js +3 -0
  161. package/dist/testSurface/surface/test/PageHoldout.js +4 -1
  162. package/dist/testSurface/surface/test/ReadinessBar.js +1 -1
  163. package/dist/testSurface/surface/test/TargetingSection.js +77 -12
  164. package/dist/testSurface/surface/test/TestSurface.js +81 -19
  165. package/dist/testSurface/surface/test/VersionsSection.js +56 -29
  166. package/dist/testSurface/surface/test/fields.d.ts +29 -4
  167. package/dist/testSurface/surface/test/fields.js +159 -39
  168. package/dist/testSurface/surface/test/pageParts.js +14 -5
  169. package/dist/testSurface/surface/test/testPage.model.d.ts +1 -0
  170. package/dist/testSurface/surface/test/testPage.model.js +6 -0
  171. package/dist/testSurface/surface/testDocument.model.d.ts +3 -0
  172. package/dist/testSurface/surface/testDocument.model.js +4 -1
  173. package/dist/testSurface/surface/useTestDocument.d.ts +22 -4
  174. package/dist/testSurface/surface/useTestDocument.js +407 -160
  175. package/dist/testSurface/useApi.d.ts +5 -5
  176. package/dist/testSurface/useOnTestReturn.d.ts +2 -0
  177. package/dist/testSurface/useOnTestReturn.js +27 -0
  178. package/dist/testSurface/useReadinessPolling.js +3 -1
  179. package/dist/transitions/addMetric.d.ts +1 -4
  180. package/dist/transitions/allocate.d.ts +2 -2
  181. package/dist/transitions/allocate.js +3 -1
  182. package/dist/transitions/archive.d.ts +1 -1
  183. package/dist/transitions/archive.js +3 -2
  184. package/dist/transitions/checkStart.d.ts +1 -0
  185. package/dist/transitions/checkStart.js +17 -6
  186. package/dist/transitions/decide.d.ts +1 -1
  187. package/dist/transitions/decide.js +5 -3
  188. package/dist/transitions/deleteExperiment.d.ts +2 -2
  189. package/dist/transitions/deleteExperiment.js +17 -7
  190. package/dist/transitions/kernel.d.ts +2 -0
  191. package/dist/transitions/kernel.js +9 -4
  192. package/dist/transitions/makeContent.d.ts +2 -1
  193. package/dist/transitions/makeContent.js +12 -8
  194. package/dist/transitions/nestedPlacementNames.d.ts +2 -2
  195. package/dist/transitions/nestedPlacementNames.js +4 -5
  196. package/dist/transitions/phaseRecord.d.ts +2 -0
  197. package/dist/transitions/phaseRecord.js +5 -0
  198. package/dist/transitions/placementInteractions.d.ts +3 -3
  199. package/dist/transitions/placementInteractions.js +8 -7
  200. package/dist/transitions/placements.d.ts +2 -0
  201. package/dist/transitions/placements.js +5 -5
  202. package/dist/transitions/preflightData.d.ts +3 -2
  203. package/dist/transitions/preflightData.js +67 -41
  204. package/dist/transitions/releaseHoldout.d.ts +2 -1
  205. package/dist/transitions/releaseHoldout.js +3 -1
  206. package/dist/transitions/releasePages.d.ts +2 -1
  207. package/dist/transitions/releasePages.js +3 -1
  208. package/dist/transitions/resolveCaps.d.ts +2 -4
  209. package/dist/transitions/start.d.ts +6 -8
  210. package/dist/transitions/start.js +67 -34
  211. package/dist/transitions/startReads.d.ts +7 -0
  212. package/dist/transitions/startReads.js +28 -0
  213. package/dist/transitions/stop.d.ts +2 -1
  214. package/dist/transitions/stop.js +3 -2
  215. package/dist/types/contracts.d.ts +6 -3
  216. package/dist/types/endpoints.d.ts +52 -9
  217. package/dist/types/runtime.d.ts +15 -9
  218. package/dist/types/snapshot.d.ts +2 -0
  219. package/dist/ui/ChipsInput.d.ts +8 -1
  220. package/dist/ui/ChipsInput.js +17 -4
  221. package/package.json +2 -2
@@ -16,7 +16,7 @@ export declare function useApi(apiRoute: string): {
16
16
  page?: number;
17
17
  }, signal?: AbortSignal) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").PagesResult>>;
18
18
  placementStatus: (body: import("../types/endpoints.js").PlacementStatusBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").PlacementStatusResult>>;
19
- start: (id: import("../types/contracts.js").DocId) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
19
+ start: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
20
20
  allocate: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").AllocateBody, options?: {
21
21
  notFound?: string;
22
22
  forbidden?: string;
@@ -29,11 +29,11 @@ export declare function useApi(apiRoute: string): {
29
29
  codes?: Readonly<Record<string, string>>;
30
30
  fallback?: string;
31
31
  }) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").AddMetricResult>>;
32
- stop: (id: import("../types/contracts.js").DocId) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
32
+ stop: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
33
33
  decide: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").DecideBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
34
- releaseHoldout: (id: import("../types/contracts.js").DocId) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
35
- releasePages: (id: import("../types/contracts.js").DocId) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
36
- makeContent: (id: import("../types/contracts.js").DocId) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").MakeContentResult>>;
34
+ releaseHoldout: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
35
+ releasePages: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
36
+ makeContent: (id: import("../types/contracts.js").DocId, phase?: number) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").MakeContentResult>>;
37
37
  dismissContentEntry: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").DismissContentEntryBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").DismissContentEntryResult>>;
38
38
  restoreContentEntry: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").RestoreContentEntryBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").RestoreContentEntryResult>>;
39
39
  archive: (id: import("../types/contracts.js").DocId, body: import("../types/endpoints.js").ArchiveBody) => Promise<import("./api.js").ApiResult<import("../types/endpoints.js").TransitionSuccess>>;
@@ -0,0 +1,2 @@
1
+ /** Focus and visibility can both fire when returning to a tab. */
2
+ export declare function useOnTestReturn(onReturn: () => void, enabled?: boolean): void;
@@ -0,0 +1,27 @@
1
+ 'use client';
2
+ import { useEffect } from 'react';
3
+ /** Focus and visibility can both fire when returning to a tab. */ export function useOnTestReturn(onReturn, enabled = true) {
4
+ useEffect(()=>{
5
+ if (!enabled) return;
6
+ let lastReturn = -Infinity;
7
+ const refresh = ()=>{
8
+ if (document.visibilityState !== 'visible' || Date.now() - lastReturn < 100) return;
9
+ lastReturn = Date.now();
10
+ onReturn();
11
+ };
12
+ const restored = (event)=>{
13
+ if (event.persisted) refresh();
14
+ };
15
+ window.addEventListener('focus', refresh);
16
+ window.addEventListener('pageshow', restored);
17
+ document.addEventListener('visibilitychange', refresh);
18
+ return ()=>{
19
+ window.removeEventListener('focus', refresh);
20
+ window.removeEventListener('pageshow', restored);
21
+ document.removeEventListener('visibilitychange', refresh);
22
+ };
23
+ }, [
24
+ enabled,
25
+ onReturn
26
+ ]);
27
+ }
@@ -8,7 +8,9 @@ import { useEffect, useRef } from 'react';
8
8
  let timer;
9
9
  const schedule = ()=>{
10
10
  clearTimeout(timer);
11
- if (document.visibilityState === 'visible') timer = setTimeout(()=>action.current(), read.pollDelay);
11
+ if (document.visibilityState === 'visible') timer = setTimeout(()=>{
12
+ if (document.visibilityState === 'visible') action.current();
13
+ }, read.pollDelay);
12
14
  };
13
15
  schedule();
14
16
  document.addEventListener('visibilitychange', schedule);
@@ -7,10 +7,7 @@ export declare function addMetric<TUser extends {
7
7
  experimentId: DocId;
8
8
  options: ResolvedOptions<TUser>;
9
9
  }): Promise<{
10
- detail?: {
11
- metricId: DocId;
12
- message: string;
13
- }[] | undefined;
10
+ detail?: import("../types/endpoints.js").StartExperimentWarning[] | undefined;
14
11
  warnings: AddMetricWarning[];
15
12
  doc: import("payload").JsonObject & import("payload").TypeWithID;
16
13
  revision: number;
@@ -1,8 +1,8 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
- export declare function allocate(req: PayloadRequest, { experimentId, allocation }: {
3
+ import type { AllocateBody } from '../types/endpoints.js';
4
+ export declare function allocate(req: PayloadRequest, { experimentId, allocation, phase: expectedPhase }: AllocateBody & {
4
5
  experimentId: DocId;
5
- allocation: number;
6
6
  }): Promise<{
7
7
  doc: import("payload").JsonObject & import("payload").TypeWithID;
8
8
  revision: number;
@@ -3,8 +3,9 @@ import { appendAllocationChange } from '../db/appends.js';
3
3
  import { claimSlices } from '../db/slices.js';
4
4
  import { relationshipId } from './checkStart.js';
5
5
  import { withTransition } from './kernel.js';
6
+ import { requireCurrentRound } from './phaseRecord.js';
6
7
  import { readExperiment, refuse, updateExperiment } from './start.js';
7
- export async function allocate(req, { experimentId, allocation }) {
8
+ export async function allocate(req, { experimentId, allocation, phase: expectedPhase }) {
8
9
  if (!Number.isInteger(allocation) || allocation < 1 || allocation > 100) refuse('invalid-body');
9
10
  const before = await readExperiment(req, experimentId);
10
11
  const { result: doc, revision } = await withTransition(req, {
@@ -12,6 +13,7 @@ export async function allocate(req, { experimentId, allocation }) {
12
13
  layerId: relationshipId(before.layer)
13
14
  }, async ({ req, exec })=>{
14
15
  const current = await readExperiment(req, experimentId);
16
+ requireCurrentRound(expectedPhase, current.phase);
15
17
  if (current.status !== 'running') refuse('invalid-status');
16
18
  if (allocation <= current.allocation) refuse('allocation-lower');
17
19
  const layerId = relationshipId(current.layer);
@@ -1,7 +1,7 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
3
  import type { ArchiveBody } from '../types/endpoints.js';
4
- export declare function archive(req: PayloadRequest, { experimentId, mode, confirmation }: ArchiveBody & {
4
+ export declare function archive(req: PayloadRequest, { experimentId, mode, confirmation, phase: expectedPhase }: ArchiveBody & {
5
5
  experimentId: DocId;
6
6
  }): Promise<{
7
7
  doc: import("payload").JsonObject & import("payload").TypeWithID;
@@ -2,15 +2,16 @@ import { contentDone } from '../contentDone.js';
2
2
  import { relationshipId } from './checkStart.js';
3
3
  import { expectedConfirm, matchesConfirm, storedWinnerLabel } from './confirmPhrases.js';
4
4
  import { withTransition } from './kernel.js';
5
- import { setPhaseEndedAt } from './phaseRecord.js';
5
+ import { requireCurrentRound, setPhaseEndedAt } from './phaseRecord.js';
6
6
  import { readExperiment, refuse, updateExperiment } from './start.js';
7
- export async function archive(req, { experimentId, mode, confirmation }) {
7
+ export async function archive(req, { experimentId, mode, confirmation, phase: expectedPhase }) {
8
8
  const before = await readExperiment(req, experimentId);
9
9
  const { result: doc, revision } = await withTransition(req, {
10
10
  experimentId,
11
11
  layerId: relationshipId(before.layer)
12
12
  }, async ({ req })=>{
13
13
  const current = await readExperiment(req, experimentId);
14
+ requireCurrentRound(expectedPhase, current.phase);
14
15
  const decision = current.decision;
15
16
  if (mode === 'stopped' ? current.status !== 'stopped' : current.status !== 'decided') refuse('invalid-status');
16
17
  if (mode === 'hard-coded' && current.kind !== 'code') refuse('invalid-status');
@@ -10,6 +10,7 @@ export interface StartExperiment {
10
10
  kind: ExperimentKind;
11
11
  unitType: UnitType;
12
12
  phase?: number;
13
+ updatedAt?: string;
13
14
  pageCollection?: string | null;
14
15
  arms: Arm[];
15
16
  allocation: number;
@@ -1,5 +1,6 @@
1
1
  import { placementLanguageSuffix } from '../testSurface/copy/languages.js';
2
2
  import { asymmetricGoal } from '../goals/fairness.js';
3
+ import { withSlotsFor } from '../arms/model.js';
3
4
  import { checkArms } from '../collections/experiments/armInvariants.js';
4
5
  import { normalisePath } from '../runtime/normalisePath.js';
5
6
  import { isOpValid } from '../targeting/ops.js';
@@ -31,7 +32,7 @@ const placementDetail = ({ collection, id, title, locales, allLocales, locale, l
31
32
  })}`
32
33
  });
33
34
  /** Group only the languages with this finding, independently for each page and
34
- * finding payload. Single-language occurrence details keep their original shape. */ function placementDetails(findings, all, input, findingKey = (detail)=>JSON.stringify(detail)) {
35
+ * finding payload. Single-language occurrence details keep their original shape. */ function placementDetails(findings, all, input, { findingKey = (detail)=>JSON.stringify(detail), includeLocaleCodes = false } = {}) {
35
36
  const groups = new Map();
36
37
  const ordered = [];
37
38
  for (const { placement, detail } of findings){
@@ -92,6 +93,11 @@ const placementDetail = ({ collection, id, title, locales, allLocales, locale, l
92
93
  } : {
93
94
  locales: names
94
95
  },
96
+ ...includeLocaleCodes ? {
97
+ localeCodes: [
98
+ ...languages.keys()
99
+ ]
100
+ } : {},
95
101
  ...detail
96
102
  };
97
103
  });
@@ -126,7 +132,7 @@ function invalidParams(arms, point) {
126
132
  } : {}
127
133
  });
128
134
  add('invalid-status', e.status === 'draft' || e.status === 'stopped');
129
- const issues = checkArms(e.arms, e.kind);
135
+ const issues = checkArms(e.kind === 'block' && Array.isArray(e.arms) ? withSlotsFor(e.arms, 'block') : e.arms, e.kind);
130
136
  for (const code of ARM_CHECK_ORDER){
131
137
  const matches = issues.filter((issue)=>issue.code === code);
132
138
  add(code, matches.length === 0, matches);
@@ -217,7 +223,7 @@ function invalidParams(arms, point) {
217
223
  placement,
218
224
  detail: {}
219
225
  })), placements, input));
220
- const identical = placements.filter((p)=>p.published).flatMap((placement)=>(placement.identicalSlots ?? []).filter((slot)=>e.arms.some((arm)=>arm.slot === slot && arm.kind !== 'holdout')).map((arm)=>({
226
+ const identical = placements.filter((p)=>p.published).flatMap((placement)=>(placement.identicalSlots ?? []).filter((slot)=>e.arms.some((arm)=>arm.key === slot && arm.kind !== 'holdout')).map((arm)=>({
221
227
  placement,
222
228
  detail: {
223
229
  arm
@@ -235,13 +241,18 @@ function invalidParams(arms, point) {
235
241
  }
236
242
  });
237
243
  }
238
- const empty = placements.filter((placement)=>placement.published && e.arms.some((arm)=>arm.kind !== 'holdout' && (!arm.slot || !(placement.slots[arm.slot] > 0))));
244
+ const missingVersions = (slots)=>e.arms.filter((arm)=>arm.kind !== 'holdout' && arm.key !== 'holdout' && !(slots[arm.key] > 0)).map((arm)=>arm.key);
245
+ const empty = placements.filter((placement)=>placement.published && missingVersions(placement.slots).length > 0);
239
246
  add('empty-slot', e.kind !== 'block' || empty.length === 0, placementDetails(empty.map((placement)=>({
240
247
  placement,
241
248
  detail: {
242
- slots: placement.slots
249
+ slots: placement.slots,
250
+ missing: missingVersions(placement.slots)
243
251
  }
244
- })), placements, input, (detail)=>JSON.stringify(e.arms.filter((arm)=>arm.kind !== 'holdout' && (!arm.slot || !(detail.slots[arm.slot] > 0))).map((arm)=>arm.key))));
252
+ })), placements, input, {
253
+ findingKey: (detail)=>JSON.stringify(detail.missing),
254
+ includeLocaleCodes: true
255
+ }));
245
256
  add('make-content-unsupported', true);
246
257
  const localized = placements.find((placement)=>placement.localized);
247
258
  if (localized) Object.assign(checks[checks.length - 1], {
@@ -1,7 +1,7 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
3
  import type { DecideBody } from '../types/endpoints.js';
4
- export declare function decide(req: PayloadRequest, { experimentId, winnerArm, note, confirmation }: DecideBody & {
4
+ export declare function decide(req: PayloadRequest, { experimentId, winnerArm, note, confirmation, phase: expectedPhase }: DecideBody & {
5
5
  experimentId: DocId;
6
6
  }): Promise<{
7
7
  doc: import("payload").JsonObject & import("payload").TypeWithID;
@@ -1,3 +1,4 @@
1
+ import { withSlotsFor } from '../arms/model.js';
1
2
  import { detached, scanPlacements, lockAndRescanPlacements, placementInteractions } from './placementInteractions.js';
2
3
  import { DEFAULT_SEQUENTIAL_TUNING_PARAMETER } from '../constants.js';
3
4
  import { refreshPlacementDocs } from '../db/placements.js';
@@ -9,9 +10,9 @@ import { routedPageTests } from '../db/pageOccupancy.js';
9
10
  import { pageTargetPaths, relationshipId } from './checkStart.js';
10
11
  import { expectedConfirm, matchesConfirm, storedWinnerLabel } from './confirmPhrases.js';
11
12
  import { withTransition } from './kernel.js';
12
- import { readPhaseRecord, setPhaseEndedAt, writePhaseRecord } from './phaseRecord.js';
13
+ import { requireCurrentRound, readPhaseRecord, setPhaseEndedAt, writePhaseRecord } from './phaseRecord.js';
13
14
  import { readExperiment, refuse, updateExperiment } from './start.js';
14
- export async function decide(req, { experimentId, winnerArm, note, confirmation }) {
15
+ export async function decide(req, { experimentId, winnerArm, note, confirmation, phase: expectedPhase }) {
15
16
  const before = await readExperiment(req, experimentId);
16
17
  const options = req.payload.config.custom?.xp;
17
18
  const placements = before.status === 'stopped' && before.kind === 'block' ? await detached(req, ()=>scanPlacements(req, options, before.slug)) : [];
@@ -21,6 +22,7 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation
21
22
  flagPointId: before.kind === 'flag' ? before.flagPoint : undefined
22
23
  }, async ({ req, exec })=>{
23
24
  const current = await readExperiment(req, experimentId);
25
+ requireCurrentRound(expectedPhase, current.phase);
24
26
  if (current.status !== 'running' && current.status !== 'stopped') refuse('invalid-status');
25
27
  if (current.kind === 'flag' && current.flagPoint) {
26
28
  // §7.8: recheck point occupancy under its lock before restoring live routing.
@@ -148,7 +150,7 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation
148
150
  phaseKind: 'rollout',
149
151
  startedAt: at,
150
152
  seed: test.seed,
151
- arms,
153
+ arms: current.kind === 'block' ? withSlotsFor(arms, 'block') : arms,
152
154
  allocation: test.allocation,
153
155
  allocationChanges: [],
154
156
  targeting: test.targeting,
@@ -3,5 +3,5 @@ import type { DocId } from '../types/contracts.js';
3
3
  /** Lock the entire bulk scope before any per-document hook can take state. */
4
4
  export declare function prepareBulkDelete(req: PayloadRequest, where: Where): Promise<void>;
5
5
  /** Payload deleteByID owns the request transaction; never commit inside hooks. */
6
- export declare function deleteExperiment(req: PayloadRequest, experimentId: DocId): Promise<void>;
7
- export declare function deleteExperimentAfter(req: PayloadRequest, experimentId: DocId): Promise<void>;
6
+ export declare function deleteExperiment(req: PayloadRequest, requestedId: DocId): Promise<void>;
7
+ export declare function deleteExperimentAfter(req: PayloadRequest): Promise<void>;
@@ -1,13 +1,19 @@
1
1
  import { safeError } from '../log.js';
2
2
  import { retireSlug } from '../db/slugs.js';
3
3
  import { txExecutor } from '../db/executor.js';
4
+ import { assertReadCommitted } from '../db/adapter.js';
4
5
  import { deleteExperimentSnapshots, serializeDelete } from '../db/delete.js';
5
6
  import { deleteExperimentEvents } from '../db/events.js';
6
7
  import { lockTransitionScope, sortLockKeys } from '../db/locks.js';
8
+ import { experimentId as canonicalExperimentId } from '../endpoints/routeId.js';
9
+ import { XpRefusal } from '../errors.js';
7
10
  import { buildAndStoreManifest } from '../manifest/compile.js';
8
- import { readExperiment, refuse } from './start.js';
11
+ import { API_MESSAGES } from '../testSurface/copy/common.js';
12
+ import { readExperiment } from './start.js';
9
13
  /** Lock the entire bulk scope before any per-document hook can take state. */ export async function prepareBulkDelete(req, where) {
10
14
  await serializeDelete(req, async ()=>{
15
+ const exec = txExecutor(req);
16
+ await assertReadCommitted(req);
11
17
  // §7.8 transition exception: hook read only discovers the lock set; delete still checks access.
12
18
  const { docs } = await req.payload.find({
13
19
  collection: 'xp-experiments',
@@ -22,20 +28,25 @@ import { readExperiment, refuse } from './start.js';
22
28
  where
23
29
  });
24
30
  for (const experimentId of sortLockKeys(docs.map((doc)=>String(doc.id)))){
25
- await lockTransitionScope(txExecutor(req), {
31
+ await lockTransitionScope(exec, {
26
32
  experimentId
27
33
  });
28
34
  }
29
35
  });
30
36
  }
31
- /** Payload deleteByID owns the request transaction; never commit inside hooks. */ export async function deleteExperiment(req, experimentId) {
37
+ /** Payload deleteByID owns the request transaction; never commit inside hooks. */ export async function deleteExperiment(req, requestedId) {
32
38
  await serializeDelete(req, async (state)=>{
33
39
  const exec = txExecutor(req);
40
+ await assertReadCommitted(req);
41
+ const experimentId = canonicalExperimentId(req, requestedId, 'payload');
42
+ if (experimentId === undefined) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
34
43
  await lockTransitionScope(exec, {
35
44
  experimentId
36
45
  });
37
46
  const current = await readExperiment(req, experimentId);
38
- if (current.status !== 'draft' && current.status !== 'archived') refuse('invalid-status');
47
+ if (current.status !== 'draft' && current.status !== 'archived') {
48
+ throw new XpRefusal('invalid-status', API_MESSAGES.deleteInvalidStatus, undefined, 409);
49
+ }
39
50
  try {
40
51
  const collection = 'xp-phases';
41
52
  // §7.8 transition exception: cascade while FK references still exist.
@@ -76,14 +87,13 @@ import { readExperiment, refuse } from './start.js';
76
87
  }
77
88
  });
78
89
  }
79
- export async function deleteExperimentAfter(req, experimentId) {
90
+ export async function deleteExperimentAfter(req) {
80
91
  await serializeDelete(req, async (state)=>{
81
92
  for (const slug of state.retiredSlugs)await retireSlug(txExecutor(req), slug);
82
93
  state.retiredSlugs.clear();
83
94
  await buildAndStoreManifest(req, {
84
95
  excludeIds: [
85
- ...state.excludedIds.values(),
86
- experimentId
96
+ ...state.excludedIds.values()
87
97
  ],
88
98
  pruneFlagDefaultIds: [
89
99
  ...state.pruneFlagDefaultIds.values()
@@ -9,6 +9,8 @@ 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. */
13
+ requireOwnedTransaction?: boolean;
12
14
  excludeIds?: DocId[];
13
15
  }
14
16
  /** Runs transition writes on the request's transaction under ordered locks.
@@ -1,10 +1,11 @@
1
- import { commitTransaction, initTransaction, killTransaction } from 'payload';
1
+ import { commitTransaction, killTransaction } from 'payload';
2
+ import { assertReadCommitted, initTransitionTransaction } from '../db/adapter.js';
2
3
  import { pooledExecutor, txExecutor } from '../db/executor.js';
3
4
  import { lockTransitionScope } from '../db/locks.js';
4
5
  import { currentTxid, txidStatus } from '../db/txid.js';
5
6
  import { contentChangeSavepoint } from '../db/appends.js';
6
7
  import { isPageBusy } from '../db/pageBusy.js';
7
- import { XpRefusal } from '../errors.js';
8
+ import { XpRefusal, XpStartTransactionOpen } from '../errors.js';
8
9
  import { buildAndStoreManifest } from '../manifest/compile.js';
9
10
  /** Runs transition writes on the request's transaction under ordered locks.
10
11
  * Returns the callback result and, unless bump is false, the stored manifest's
@@ -17,15 +18,19 @@ import { buildAndStoreManifest } from '../manifest/compile.js';
17
18
  * itself fails: the host must observe its own failed commit. Other failures kill
18
19
  * even a borrowed transaction. Owned audits follow the ordinary owned path.
19
20
  */ export async function withTransition(req, scope, fn) {
21
+ if (scope.requireOwnedTransaction && req.transactionID != null) {
22
+ throw new XpStartTransactionOpen();
23
+ }
20
24
  const hadTransition = Object.prototype.hasOwnProperty.call(req.context, 'xpTransition');
21
25
  const previousTransition = req.context.xpTransition;
22
26
  let borrowedAudit = scope.audit === true && req.transactionID != null;
23
27
  try {
24
- const owns = await initTransaction(req);
28
+ const owns = await initTransitionTransaction(req);
25
29
  borrowedAudit = scope.audit === true && !owns;
26
30
  const exec = txExecutor(req);
27
- req.context.xpTransition = true;
28
31
  const work = async ()=>{
32
+ if (!owns) await assertReadCommitted(req);
33
+ req.context.xpTransition = true;
29
34
  await lockTransitionScope(exec, scope);
30
35
  return fn({
31
36
  exec,
@@ -1,3 +1,4 @@
1
+ import type { RoundBody } from '../types/endpoints.js';
1
2
  import { type PayloadRequest } from 'payload';
2
3
  import type { ContentReportReason } from '../types/reasons.js';
3
4
  import type { DocId, ResolvedOptions } from '../types/contracts.js';
@@ -17,7 +18,7 @@ type ContentDoc = {
17
18
  export declare function hostTransaction(req: PayloadRequest, experimentId: DocId, fn: () => Promise<void>): Promise<void>;
18
19
  export declare function makeContent<TUser extends {
19
20
  id: DocId;
20
- }>(req: PayloadRequest, { experimentId, options }: {
21
+ }>(req: PayloadRequest, { experimentId, options, phase: expectedPhase }: RoundBody & {
21
22
  experimentId: DocId;
22
23
  options: ResolvedOptions<TUser>;
23
24
  }): Promise<{
@@ -1,7 +1,9 @@
1
+ import { requireCurrentRound } from './phaseRecord.js';
1
2
  import { placementReader } from '../blocks/placementLocale.js';
2
3
  import { puckExperimentSlug } from '../puck/experimentSlug.js';
3
4
  import { puckVisibility, hiddenOnSizes, visibilitySizes } from '../puck/visibility.js';
4
- import { Forbidden, NotFound, ValidationError, Locked, commitTransaction, initTransaction, killTransaction } from 'payload';
5
+ import { Forbidden, NotFound, ValidationError, Locked, commitTransaction, killTransaction } from 'payload';
6
+ import { initTransitionTransaction } from '../db/adapter.js';
5
7
  import { latestDraftContent, publishedContent as readPublishedContent } from '../db/publishedContent.js';
6
8
  import { EXPERIMENT_BLOCK_SLUG, hostBlocks, slotBlocks } from '../blocks/model.js';
7
9
  import { findRegisteredBlocksField, freshBlockIds } from '../blocks/formState.js';
@@ -195,7 +197,7 @@ async function fieldRefusal(fields, req, doc, operation = 'update', data = doc,
195
197
  delete req.transactionID;
196
198
  delete req.context.xpTransition;
197
199
  try {
198
- if (!await initTransaction(req)) throw new Error('A content transaction could not be started.');
200
+ if (!await initTransitionTransaction(req)) throw new Error('A content transaction could not be started.');
199
201
  await fn();
200
202
  const xid = await currentTxid(txExecutor(req));
201
203
  await commitTransaction(req);
@@ -211,7 +213,7 @@ async function fieldRefusal(fields, req, doc, operation = 'update', data = doc,
211
213
  else req.context.xpTransition = transition;
212
214
  }
213
215
  }
214
- export async function makeContent(req, { experimentId, options }) {
216
+ export async function makeContent(req, { experimentId, options, phase: expectedPhase }) {
215
217
  const before = await readExperiment(req, experimentId);
216
218
  const { result } = await withTransition(req, {
217
219
  experimentId,
@@ -220,6 +222,7 @@ export async function makeContent(req, { experimentId, options }) {
220
222
  bump: false
221
223
  }, async ({ exec })=>{
222
224
  const current = await readExperiment(req, experimentId);
225
+ requireCurrentRound(expectedPhase, current.phase);
223
226
  if (current.status !== 'decided' || ![
224
227
  'block',
225
228
  'flag',
@@ -255,7 +258,7 @@ export async function makeContent(req, { experimentId, options }) {
255
258
  // Roll back any remaining writes, then check the row while still
256
259
  // detached from the outer transition and its privileged context.
257
260
  await killTransaction(req);
258
- if (!await initTransaction(req)) throw new Error('A content transaction could not be started.');
261
+ if (!await initTransitionTransaction(req)) throw new Error('A content transaction could not be started.');
259
262
  missing = !await readPublishedContent(req, collection, id);
260
263
  }
261
264
  throw error;
@@ -292,7 +295,8 @@ export async function makeContent(req, { experimentId, options }) {
292
295
  }
293
296
  };
294
297
  if (current.kind === 'block') {
295
- if (!winner.slot) refuse('invalid-winner');
298
+ if (winner.key === 'holdout') refuse('invalid-winner');
299
+ const winnerSlot = winner.key;
296
300
  const registrations = [
297
301
  ...puckCollections(options),
298
302
  ...options.blocks?.collections ?? []
@@ -423,13 +427,13 @@ export async function makeContent(req, { experimentId, options }) {
423
427
  block
424
428
  ];
425
429
  const rows = Array.isArray(block.slots) ? block.slots : [];
426
- if (!rows.some((row)=>row?.slot === winner.slot)) throw new Error('The winning content slot is missing.');
430
+ if (!rows.some((row)=>row?.slot === winnerSlot)) throw new Error('The winning content slot is missing.');
427
431
  const registered = findRegisteredBlocksField(config?.fields ?? [], field);
428
432
  if (!registered) throw new Error('This content field is no longer configured.');
429
433
  return slotBlocks(freshBlockIds([
430
434
  block
431
- ], registered.field, req.payload.config)[0], winner.slot);
432
- }) : unwrap(value, current.slug, winner.slot);
435
+ ], registered.field, req.payload.config)[0], winnerSlot);
436
+ }) : unwrap(value, current.slug, winnerSlot);
433
437
  const draft = drafts ? await latestDraftContent(req, collection, id) ?? published : published;
434
438
  const draftValue = draft[field] ?? null;
435
439
  const draftContent = transform(draftValue);
@@ -1,5 +1,5 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { BlockPlacement } from './placements.js';
3
- /** Read through manager access, on both preflight and Start's locked rescan. */
4
- export declare function nestedPlacementNames(req: PayloadRequest, placements: readonly BlockPlacement[]): Promise<Map<string, string>>;
3
+ /** Read names for preflight and Start's locked rescan. */
4
+ export declare function nestedPlacementNames(req: PayloadRequest, placements: readonly BlockPlacement[], system?: boolean): Promise<Map<string, string>>;
5
5
  export declare const nameNestedPlacements: (placements: readonly BlockPlacement[], names: ReadonlyMap<string, string>) => BlockPlacement[];
@@ -1,4 +1,5 @@
1
- /** Read through manager access, on both preflight and Start's locked rescan. */ export async function nestedPlacementNames(req, placements) {
1
+ import { findStartDocuments } from './startReads.js';
2
+ /** Read names for preflight and Start's locked rescan. */ export async function nestedPlacementNames(req, placements, system = false) {
2
3
  const slugs = [
3
4
  ...new Set(placements.flatMap((p)=>(p.nestedTests ?? []).flatMap((pair)=>[
4
5
  pair.outer,
@@ -6,10 +7,8 @@
6
7
  ])))
7
8
  ];
8
9
  if (!slugs.length) return new Map();
9
- const found = await req.payload.find({
10
+ const found = await findStartDocuments(req, {
10
11
  collection: 'xp-experiments',
11
- req,
12
- overrideAccess: false,
13
12
  depth: 0,
14
13
  pagination: false,
15
14
  where: {
@@ -17,7 +16,7 @@
17
16
  in: slugs
18
17
  }
19
18
  }
20
- });
19
+ }, system);
21
20
  return new Map(found.docs.map((doc)=>[
22
21
  String(doc.slug),
23
22
  String(doc.name)
@@ -1,6 +1,8 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { Arm, DocId, TargetingRule } from '../types/contracts.js';
3
3
  import type { AllocationChange, ContentChange } from '../db/appends.js';
4
+ /** Check the round after acquiring the experiment lock and before writing. */
5
+ export declare function requireCurrentRound(expected: number | undefined, current: number | undefined): void;
4
6
  export interface PhaseRecord {
5
7
  experiment: DocId;
6
8
  phase: number;
@@ -1,4 +1,9 @@
1
1
  import { XpRefusal } from '../errors.js';
2
+ /** Check the round after acquiring the experiment lock and before writing. */ export function requireCurrentRound(expected, current) {
3
+ if (expected !== undefined && expected !== current) {
4
+ throw new XpRefusal('round-changed', 'This test is on a different round. Review the current round and try again.', undefined, 409);
5
+ }
6
+ }
2
7
  export async function readPhaseRecord(req, experimentId, phase) {
3
8
  // §7.8: frozen configuration lookup serves an authorised transition.
4
9
  const { docs } = await req.payload.find({
@@ -7,7 +7,7 @@ export declare function detached<T>(req: PayloadRequest, fn: () => Promise<T>):
7
7
  export declare function uniquePlacementDocs(placements: readonly Pick<BlockPlacement, 'collection' | 'id'>[]): PlacementDoc[];
8
8
  export declare function scanPlacements<TUser extends {
9
9
  id: DocId;
10
- }>(req: PayloadRequest, options: ResolvedOptions<TUser>, slug: string): Promise<BlockPlacement[]>;
10
+ }>(req: PayloadRequest, options: ResolvedOptions<TUser>, slug: string, system?: boolean): Promise<BlockPlacement[]>;
11
11
  export declare function placementPaths<TUser extends {
12
12
  id: DocId;
13
13
  }>(req: PayloadRequest, options: ResolvedOptions<TUser>, docs: readonly PlacementDoc[]): Promise<string[]>;
@@ -26,7 +26,7 @@ export declare function placementInteractions<TUser extends {
26
26
  kind: string;
27
27
  arms: Arm[];
28
28
  pageCollection?: string | null;
29
- }, paths: string[]): Promise<InteractionDetail[]>;
29
+ }, paths: string[], system?: boolean): Promise<InteractionDetail[]>;
30
30
  export declare function lockAndRescanPlacements<TUser extends {
31
31
  id: DocId;
32
32
  }>(req: PayloadRequest, exec: Executor, options: ResolvedOptions<TUser>, experiment: {
@@ -34,7 +34,7 @@ export declare function lockAndRescanPlacements<TUser extends {
34
34
  slug: string;
35
35
  kind: string;
36
36
  arms: Arm[];
37
- }, before: readonly BlockPlacement[]): Promise<{
37
+ }, before: readonly BlockPlacement[], system?: boolean): Promise<{
38
38
  placements: BlockPlacement[];
39
39
  docs: PlacementDoc[];
40
40
  }>;
@@ -30,11 +30,12 @@ export function uniquePlacementDocs(placements) {
30
30
  ])).values()
31
31
  ];
32
32
  }
33
- export function scanPlacements(req, options, slug) {
33
+ export function scanPlacements(req, options, slug, system = false) {
34
34
  return scanBlockPlacements(req, {
35
35
  slug,
36
36
  puckCollections: options.puck?.collections ?? [],
37
- blocksCollections: options.blocks?.collections ?? []
37
+ blocksCollections: options.blocks?.collections ?? [],
38
+ system
38
39
  });
39
40
  }
40
41
  export async function placementPaths(req, options, docs) {
@@ -53,7 +54,7 @@ export async function placementPaths(req, options, docs) {
53
54
  ]);
54
55
  }
55
56
  const active = (test)=>test.status === 'running' || test.status === 'decided';
56
- export async function placementInteractions(req, exec, options, experiment, paths) {
57
+ export async function placementInteractions(req, exec, options, experiment, paths, system = false) {
57
58
  const result = [];
58
59
  for (const test of (await placementTests(exec))){
59
60
  if (!active(test) || String(test.id) === String(experiment.id)) continue;
@@ -67,7 +68,7 @@ export async function placementInteractions(req, exec, options, experiment, path
67
68
  version: test.arms.some((a)=>a.kind === 'variant' && a.pageTarget && normalisePath(a.pageTarget) === path)
68
69
  });
69
70
  } else if (experiment.kind === 'page' && test.kind === 'block') {
70
- const docs = test.placementDocs ?? uniquePlacementDocs(await detached(req, ()=>scanPlacements(req, options, test.slug)));
71
+ const docs = test.placementDocs ?? uniquePlacementDocs(await detached(req, ()=>scanPlacements(req, options, test.slug, system)));
71
72
  const relevant = docs.filter((doc)=>!experiment.pageCollection || doc.collection === experiment.pageCollection);
72
73
  for (const path of (await placementPaths(req, options, relevant)).filter((path)=>paths.includes(path)))result.push({
73
74
  experimentId: test.id,
@@ -81,14 +82,14 @@ export async function placementInteractions(req, exec, options, experiment, path
81
82
  }
82
83
  return result;
83
84
  }
84
- export async function lockAndRescanPlacements(req, exec, options, experiment, before) {
85
+ export async function lockAndRescanPlacements(req, exec, options, experiment, before, system = false) {
85
86
  const paths = await placementPaths(req, options, uniquePlacementDocs(before));
86
87
  await lockPagePaths(exec, paths);
87
- const placements = await detached(req, ()=>scanPlacements(req, options, experiment.slug));
88
+ const placements = await detached(req, ()=>scanPlacements(req, options, experiment.slug, system));
88
89
  const docs = uniquePlacementDocs(placements);
89
90
  const afterPaths = await placementPaths(req, options, docs);
90
91
  if (afterPaths.some((path)=>!paths.includes(path))) throw new XpRefusal('placements-changed', "This test's pages changed while it was starting. Try again.", undefined, 409);
91
- const conflicts = await placementInteractions(req, exec, options, experiment, paths);
92
+ const conflicts = await placementInteractions(req, exec, options, experiment, paths, system);
92
93
  if (conflicts.length) throw new XpRefusal('interacting-tests', interactingTestsCopy(conflicts[0].path, conflicts[0].status, conflicts[0].name, conflicts[0].version), conflicts, 409);
93
94
  return {
94
95
  placements,
@@ -39,6 +39,8 @@ interface ScanOptions {
39
39
  publishedOnly?: boolean;
40
40
  /** Hooks and manager-authorized visitor-impact reads must see every placement (CORE-21). */
41
41
  pageGuard?: true;
42
+ /** Trusted server-side Start checks placements without a manager actor. */
43
+ system?: boolean;
42
44
  change?: PlacementChange;
43
45
  }
44
46
  /** Published rows only, one pass per collection across both editor registrations.