@sonordev/contracts 2.27.0 → 2.29.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.
package/dist/resonance.js CHANGED
@@ -9,31 +9,31 @@ var RESONANCE_SOURCE_MARKER_PARAMETER = "sonor_source";
9
9
  var RESONANCE_SUBJECT_HEADER = "X-Sonor-Resonance-Subject";
10
10
 
11
11
  // src/contracts/wire-schema.ts
12
- function createWireSchema(fail3, isValidationError) {
12
+ function createWireSchema(fail4, isValidationError) {
13
13
  const own = (v, k) => Object.prototype.hasOwnProperty.call(v, k);
14
14
  const field3 = (schema, read) => ({ schema, read });
15
- const text3 = (max = 200, pattern, min = 1) => field3({ type: "string", minLength: min, maxLength: max, ...pattern ? { pattern: pattern.source } : {} }, (v, p) => typeof v === "string" && v.length >= min && v.length <= max && (!pattern || pattern.test(v)) ? v : fail3(p, "invalid string"));
16
- const choice3 = (...values) => field3({ type: "string", enum: values }, (v, p) => typeof v === "string" && values.includes(v) ? v : fail3(p, "unsupported value"));
17
- const literal3 = (value) => field3({ const: value }, (v, p) => v === value ? value : fail3(p, "unexpected value"));
18
- const integer3 = (min = 0, max = Number.MAX_SAFE_INTEGER) => field3({ type: "integer", minimum: min, maximum: max }, (v, p) => typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max ? v : fail3(p, "invalid integer"));
19
- const bool2 = field3({ type: "boolean" }, (v, p) => typeof v === "boolean" ? v : fail3(p, "must be boolean"));
15
+ const text4 = (max = 200, pattern, min = 1) => field3({ type: "string", minLength: min, maxLength: max, ...pattern ? { pattern: pattern.source } : {} }, (v, p) => typeof v === "string" && v.length >= min && v.length <= max && (!pattern || pattern.test(v)) ? v : fail4(p, "invalid string"));
16
+ const choice3 = (...values) => field3({ type: "string", enum: values }, (v, p) => typeof v === "string" && values.includes(v) ? v : fail4(p, "unsupported value"));
17
+ const literal3 = (value) => field3({ const: value }, (v, p) => v === value ? value : fail4(p, "unexpected value"));
18
+ const integer3 = (min = 0, max = Number.MAX_SAFE_INTEGER) => field3({ type: "integer", minimum: min, maximum: max }, (v, p) => typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max ? v : fail4(p, "invalid integer"));
19
+ const bool2 = field3({ type: "boolean" }, (v, p) => typeof v === "boolean" ? v : fail4(p, "must be boolean"));
20
20
  const optional3 = (f) => ({ ...f, optional: true });
21
21
  const nullable3 = (f) => field3({ anyOf: [f.schema, { type: "null" }] }, (v, p) => v === null ? null : f.read(v, p));
22
22
  const list3 = (f, max = 100, min = 0) => field3({ type: "array", items: f.schema, minItems: min, maxItems: max }, (v, p) => {
23
- if (!Array.isArray(v) || v.length < min || v.length > max) fail3(p, "invalid array");
23
+ if (!Array.isArray(v) || v.length < min || v.length > max) fail4(p, "invalid array");
24
24
  return v.map((x, i) => f.read(x, `${p}[${i}]`));
25
25
  });
26
26
  const object3 = (fields2) => field3({ type: "object", additionalProperties: false, properties: Object.fromEntries(Object.entries(fields2).map(([k, f]) => [k, f.schema])), required: Object.keys(fields2).filter((k) => !("optional" in fields2[k])) }, (v, p) => {
27
- if (!v || typeof v !== "object" || Array.isArray(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) fail3(p, "must be a plain object");
27
+ if (!v || typeof v !== "object" || Array.isArray(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) fail4(p, "must be a plain object");
28
28
  const source2 = v, result = {};
29
- for (const key of Reflect.ownKeys(source2)) if (typeof key !== "string" || !own(fields2, key)) fail3(p, "unknown field");
29
+ for (const key of Reflect.ownKeys(source2)) if (typeof key !== "string" || !own(fields2, key)) fail4(p, "unknown field");
30
30
  for (const [key, f] of Object.entries(fields2)) {
31
31
  if (!own(source2, key)) {
32
32
  if ("optional" in f) continue;
33
- fail3(`${p}.${key}`, "required");
33
+ fail4(`${p}.${key}`, "required");
34
34
  }
35
35
  const descriptor = Object.getOwnPropertyDescriptor(source2, key);
36
- if (!own(descriptor, "value")) fail3(`${p}.${key}`, "accessors are not wire data");
36
+ if (!own(descriptor, "value")) fail4(`${p}.${key}`, "accessors are not wire data");
37
37
  result[key] = f.read(descriptor.value, `${p}.${key}`);
38
38
  }
39
39
  return result;
@@ -47,16 +47,35 @@ function createWireSchema(fail3, isValidationError) {
47
47
  if (!isValidationError(e)) throw e;
48
48
  }
49
49
  }
50
- return found.length === 1 ? found[0] : fail3(p, "must match exactly one supported shape");
50
+ return found.length === 1 ? found[0] : fail4(p, "must match exactly one supported shape");
51
51
  });
52
- const refine3 = (f, check) => field3(f.schema, (v, p) => {
52
+ const refine4 = (f, check) => field3(f.schema, (v, p) => {
53
53
  const result = f.read(v, p);
54
54
  check(result, p);
55
55
  return result;
56
56
  });
57
- return { field: field3, text: text3, choice: choice3, literal: literal3, integer: integer3, bool: bool2, optional: optional3, nullable: nullable3, list: list3, object: object3, union: union3, refine: refine3 };
57
+ return { field: field3, text: text4, choice: choice3, literal: literal3, integer: integer3, bool: bool2, optional: optional3, nullable: nullable3, list: list3, object: object3, union: union3, refine: refine4 };
58
58
  }
59
59
 
60
+ // src/contracts/wire-native-cas.ts
61
+ var NativeCasTimestampValidationError = class extends Error {
62
+ constructor(path2, reason) {
63
+ super(`${path2}: ${reason}`);
64
+ this.path = path2;
65
+ this.name = "NativeCasTimestampValidationError";
66
+ }
67
+ };
68
+ var fail = (path2, reason) => {
69
+ throw new NativeCasTimestampValidationError(path2, reason);
70
+ };
71
+ var { text, refine } = createWireSchema(fail, (error) => error instanceof NativeCasTimestampValidationError);
72
+ var timestamp = refine(text(32, /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,6})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/), (v, p) => {
73
+ const calendar = v.slice(0, 19) + "Z";
74
+ if (v.startsWith("0000") || !Number.isFinite(Date.parse(calendar)) || new Date(calendar).toISOString().slice(0, 19) !== v.slice(0, 19)) fail(p, "invalid native CAS calendar timestamp");
75
+ });
76
+ var parseNativeCasTimestamp = (v) => timestamp.read(v, "nativeCasTimestamp");
77
+ var NATIVE_CAS_TIMESTAMP_JSON_SCHEMA = timestamp.schema;
78
+
60
79
  // src/contracts/sites-normalize.ts
61
80
  function stripWww(host) {
62
81
  return host.startsWith("www.") ? host.slice(4) : host;
@@ -130,37 +149,37 @@ var SignalExperimentValidationError = class extends Error {
130
149
  this.name = "SignalExperimentValidationError";
131
150
  }
132
151
  };
133
- var fail = (path2, reason) => {
152
+ var fail2 = (path2, reason) => {
134
153
  throw new SignalExperimentValidationError(path2, reason);
135
154
  };
136
- var { field, text, choice, literal, integer, optional, nullable, list, object, union, refine } = createWireSchema(fail, (error) => error instanceof SignalExperimentValidationError);
137
- var percent = field({ type: "number", minimum: 0, maximum: 100 }, (v, p) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 100 ? v : fail(p, "must be a finite percentage from 0 to 100"));
138
- var page = refine(text(2048, /^\/(?!\/)[^?#\s\\]*$/), (v, p) => {
155
+ var { field, text: text2, choice, literal, integer, optional, nullable, list, object, union, refine: refine2 } = createWireSchema(fail2, (error) => error instanceof SignalExperimentValidationError);
156
+ var percent = field({ type: "number", minimum: 0, maximum: 100 }, (v, p) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 100 ? v : fail2(p, "must be a finite percentage from 0 to 100"));
157
+ var page = refine2(text2(2048, /^\/(?!\/)[^?#\s\\]*$/), (v, p) => {
139
158
  const parsed = new URL(v, "https://example.com");
140
- if (parsed.pathname !== v) fail(p, "must be a canonical page path");
159
+ if (parsed.pathname !== v) fail2(p, "must be a canonical page path");
141
160
  });
142
- var variant = object({ key: text(80), name: text(160), weight: percent, description: optional(text(1e3, void 0, 0)) });
143
- var variants = refine(list(variant, 50, 2), (v, p) => {
144
- if (new Set(v.map((x) => x.key)).size !== v.length) fail(p, "variant keys must be unique");
145
- if (Math.abs(v.reduce((sum, x) => sum + x.weight, 0) - 100) > 0.01) fail(p, "variant weights must sum to 100");
161
+ var variant = object({ key: text2(80), name: text2(160), weight: percent, description: optional(text2(1e3, void 0, 0)) });
162
+ var variants = refine2(list(variant, 50, 2), (v, p) => {
163
+ if (new Set(v.map((x) => x.key)).size !== v.length) fail2(p, "variant keys must be unique");
164
+ if (Math.abs(v.reduce((sum, x) => sum + x.weight, 0) - 100) > 0.01) fail2(p, "variant weights must sum to 100");
146
165
  });
147
- var targeting = object({ pages: optional(list(page, 100)), segments: optional(list(text(160), 100)), devices: optional(list(choice("desktop", "mobile", "tablet"), 3)), geo: optional(list(text(160), 100)) });
148
- var fields = { name: text(160), description: text(1e4, void 0, 0), variants, traffic_allocation: percent, targeting_rules: targeting };
166
+ var targeting = object({ pages: optional(list(page, 100)), segments: optional(list(text2(160), 100)), devices: optional(list(choice("desktop", "mobile", "tablet"), 3)), geo: optional(list(text2(160), 100)) });
167
+ var fields = { name: text2(160), description: text2(1e4, void 0, 0), variants, traffic_allocation: percent, targeting_rules: targeting };
149
168
  var create = object({ ...fields, description: optional(fields.description), traffic_allocation: optional(fields.traffic_allocation), targeting_rules: optional(fields.targeting_rules) });
150
169
  var update = object({ name: optional(fields.name), description: optional(fields.description), variants: optional(fields.variants), traffic_allocation: optional(fields.traffic_allocation), targeting_rules: optional(fields.targeting_rules) });
151
170
  var parseSignalExperimentCreate = (v) => create.read(v, "experimentCreate");
152
171
  var parseSignalExperimentUpdate = (v) => update.read(v, "experimentUpdate");
153
172
  var SIGNAL_EXPERIMENT_CREATE_JSON_SCHEMA = create.schema;
154
173
  var SIGNAL_EXPERIMENT_UPDATE_JSON_SCHEMA = update.schema;
155
- var measurementUuid = text(36, UUID_V1_TO_V8_PATTERN);
156
- var measurementRevision = text(128, /^[a-zA-Z0-9._:-]+$/);
157
- var measurementInstant = refine(text(30, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (v, p) => {
158
- if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().replace(".000Z", "Z") !== v.replace(".000Z", "Z")) fail(p, "invalid UTC instant");
174
+ var measurementUuid = text2(36, UUID_V1_TO_V8_PATTERN);
175
+ var measurementRevision = text2(128, /^[a-zA-Z0-9._:-]+$/);
176
+ var measurementInstant = refine2(text2(30, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (v, p) => {
177
+ if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().replace(".000Z", "Z") !== v.replace(".000Z", "Z")) fail2(p, "invalid UTC instant");
159
178
  });
160
- var measurementSite = refine(text(253), (v, p) => {
161
- if (!isNormalizedSiteHost(v) || isBlockedPublicUrlHost(v)) fail(p, "must be a normalized public site host");
179
+ var measurementSite = refine2(text2(253), (v, p) => {
180
+ if (!isNormalizedSiteHost(v) || isBlockedPublicUrlHost(v)) fail2(p, "must be a normalized public site host");
162
181
  });
163
- var measurementCount = text(30, /^(?:0|[1-9][0-9]*)$/);
182
+ var measurementCount = text2(30, /^(?:0|[1-9][0-9]*)$/);
164
183
  var measurementScope = object({
165
184
  projectId: measurementUuid,
166
185
  experimentId: measurementUuid,
@@ -173,7 +192,7 @@ var measurementScope = object({
173
192
  assignedTo: measurementInstant
174
193
  });
175
194
  var assignmentCounts = {
176
- variantKey: text(80),
195
+ variantKey: text2(80),
177
196
  assignedUnits: measurementCount,
178
197
  exposureEvents: measurementCount,
179
198
  exposedUnits: measurementCount,
@@ -203,7 +222,7 @@ var observedFields = {
203
222
  semanticRole: literal("accepted_form_diagnostic"),
204
223
  businessMetrics
205
224
  };
206
- var observedMeasurement = refine(union(
225
+ var observedMeasurement = refine2(union(
207
226
  object({
208
227
  ...observedFields,
209
228
  originalGoal: object({ ...originalGoalFields, sourceKind: formSourceKind }),
@@ -220,17 +239,17 @@ var observedMeasurement = refine(union(
220
239
  })
221
240
  ), (value, p) => {
222
241
  if (Date.parse(value.scope.assignedFrom) >= Date.parse(value.scope.assignedTo) || Date.parse(value.scope.assignedTo) > Date.parse(value.observedAt))
223
- fail(p + ".scope", "requires an increasing assignment cohort ending by the native observation");
224
- if (new Set(value.variants.map((v) => v.variantKey)).size !== value.variants.length) fail(p + ".variants", "variant keys must be unique");
242
+ fail2(p + ".scope", "requires an increasing assignment cohort ending by the native observation");
243
+ if (new Set(value.variants.map((v) => v.variantKey)).size !== value.variants.length) fail2(p + ".variants", "variant keys must be unique");
225
244
  for (const [index, v] of value.variants.entries()) {
226
245
  const assigned = BigInt(v.assignedUnits), exposed = BigInt(v.exposedUnits), mature = BigInt(v.matureAssignedUnits);
227
246
  const at = `${p}.variants[${index}]`;
228
247
  if (exposed > assigned || BigInt(v.exposureEvents) < exposed || BigInt(v.assignmentsWithoutExposure) !== assigned - exposed || mature + BigInt(v.immatureAssignedUnits) !== assigned)
229
- fail(at, "assignment, exposure and maturity counts are inconsistent");
248
+ fail2(at, "assignment, exposure and maturity counts are inconsistent");
230
249
  if (v.acceptedFormUnits !== null && v.acceptedFormEvents !== null && v.matureAcceptedFormUnits !== null) {
231
250
  const accepted = BigInt(v.acceptedFormUnits), matureAccepted = BigInt(v.matureAcceptedFormUnits);
232
251
  if (accepted > exposed || accepted > BigInt(v.acceptedFormEvents) || matureAccepted > mature || matureAccepted > accepted)
233
- fail(at, "accepted form units must remain within their exposed, event and mature cohorts");
252
+ fail2(at, "accepted form units must remain within their exposed, event and mature cohorts");
234
253
  }
235
254
  }
236
255
  });
@@ -249,11 +268,11 @@ var scopeOption = object({
249
268
  experimentId: measurementUuid,
250
269
  experimentRevision: integer(1),
251
270
  goalRevision: measurementRevision,
252
- goalLabel: nullable(text(200)),
271
+ goalLabel: nullable(text2(200)),
253
272
  assignmentExtent: nullable(object({ firstAssignedAt: measurementInstant, lastAssignedAt: measurementInstant })),
254
273
  suggestedCohort: nullable(object({ assignedFrom: measurementInstant, assignedTo: measurementInstant }))
255
274
  });
256
- var scopeOptions = refine(object({ observedAt: measurementInstant, items: list(scopeOption, 100), nextCursor: nullable(text(4096)) }), (value, p) => {
275
+ var scopeOptions = refine2(object({ observedAt: measurementInstant, items: list(scopeOption, 100), nextCursor: nullable(text2(4096)) }), (value, p) => {
257
276
  const observed = Date.parse(value.observedAt), tuples = /* @__PURE__ */ new Set();
258
277
  for (const [index, item] of value.items.entries()) {
259
278
  const at = `${p}.items[${index}]`, accepted = Date.parse(item.acceptedAt);
@@ -265,16 +284,16 @@ var scopeOptions = refine(object({ observedAt: measurementInstant, items: list(s
265
284
  item.experimentRevision,
266
285
  item.goalRevision
267
286
  ]);
268
- if (tuples.has(tuple)) fail(at, "original scope tuples must be unique");
287
+ if (tuples.has(tuple)) fail2(at, "original scope tuples must be unique");
269
288
  tuples.add(tuple);
270
- if (accepted > observed) fail(at + ".acceptedAt", "must not follow the native observation");
289
+ if (accepted > observed) fail2(at + ".acceptedAt", "must not follow the native observation");
271
290
  if (item.assignmentExtent) {
272
291
  const first = Date.parse(item.assignmentExtent.firstAssignedAt), last = Date.parse(item.assignmentExtent.lastAssignedAt);
273
- if (first > last || last > observed) fail(at + ".assignmentExtent", "requires first <= last <= native observation");
292
+ if (first > last || last > observed) fail2(at + ".assignmentExtent", "requires first <= last <= native observation");
274
293
  }
275
294
  if (item.suggestedCohort) {
276
295
  const from = Date.parse(item.suggestedCohort.assignedFrom), to = Date.parse(item.suggestedCohort.assignedTo);
277
- if (from !== accepted || from >= to || to > observed) fail(at + ".suggestedCohort", "requires original acceptance start and increasing cohort ending by native observation");
296
+ if (from !== accepted || from >= to || to > observed) fail2(at + ".suggestedCohort", "requires original acceptance start and increasing cohort ending by native observation");
278
297
  }
279
298
  }
280
299
  });
@@ -298,29 +317,29 @@ var ResonanceValidationError = class extends Error {
298
317
  this.name = "ResonanceValidationError";
299
318
  }
300
319
  };
301
- var fail2 = (path2, reason) => {
320
+ var fail3 = (path2, reason) => {
302
321
  throw new ResonanceValidationError(path2, reason);
303
322
  };
304
- var { field: field2, text: text2, choice: choice2, literal: literal2, integer: integer2, bool, optional: optional2, nullable: nullable2, list: list2, object: object2, union: union2, refine: refine2 } = createWireSchema(fail2, (error) => error instanceof ResonanceValidationError);
305
- var uuid = text2(36, UUID_V1_TO_V8_PATTERN);
306
- var digest = text2(64, /^[a-f0-9]{64}$/);
307
- var revision = text2(128, /^[a-zA-Z0-9._:-]+$/);
308
- var instant = refine2(text2(30, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (v, p) => {
309
- if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().replace(".000Z", "Z") !== v.replace(".000Z", "Z")) fail2(p, "invalid UTC instant");
323
+ var { field: field2, text: text3, choice: choice2, literal: literal2, integer: integer2, bool, optional: optional2, nullable: nullable2, list: list2, object: object2, union: union2, refine: refine3 } = createWireSchema(fail3, (error) => error instanceof ResonanceValidationError);
324
+ var uuid = text3(36, UUID_V1_TO_V8_PATTERN);
325
+ var digest = text3(64, /^[a-f0-9]{64}$/);
326
+ var revision = text3(128, /^[a-zA-Z0-9._:-]+$/);
327
+ var instant = refine3(text3(30, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (v, p) => {
328
+ if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().replace(".000Z", "Z") !== v.replace(".000Z", "Z")) fail3(p, "invalid UTC instant");
310
329
  });
311
- var timeZone = refine2(text2(80), (v, p) => {
330
+ var timeZone = refine3(text3(80), (v, p) => {
312
331
  try {
313
332
  new Intl.DateTimeFormat("en", { timeZone: v });
314
333
  } catch {
315
- fail2(p, "invalid IANA timezone");
334
+ fail3(p, "invalid IANA timezone");
316
335
  }
317
336
  });
318
- var site = refine2(text2(253), (v, p) => {
319
- if (!isNormalizedSiteHost(v) || isBlockedPublicUrlHost(v)) fail2(p, "must be a normalized public site host");
337
+ var site = refine3(text3(253), (v, p) => {
338
+ if (!isNormalizedSiteHost(v) || isBlockedPublicUrlHost(v)) fail3(p, "must be a normalized public site host");
320
339
  });
321
- var path = text2(2048, /^\/(?!\/)[^?#\s\\]*$/);
322
- var decimal = text2(30, /^(?:0|[1-9][0-9]{0,29})$/);
323
- var operationKey = text2(200, /^[a-zA-Z0-9._:-]+$/);
340
+ var path = text3(2048, /^\/(?!\/)[^?#\s\\]*$/);
341
+ var decimal = text3(30, /^(?:0|[1-9][0-9]{0,29})$/);
342
+ var operationKey = text3(200, /^[a-zA-Z0-9._:-]+$/);
324
343
  var objectiveCountingUnit = choice2("unique_source", "unique_qualified_contact", "net_order");
325
344
  var RESONANCE_CURRENCIES = ["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF", "CLP", "CNY", "COP", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLE", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XCD", "XCG", "XDR", "XOF", "XPF", "XSU", "YER", "ZAR", "ZMW", "ZWG", "ZWL"];
326
345
  var currency = choice2(...RESONANCE_CURRENCIES);
@@ -329,28 +348,28 @@ var parseMoney = (value) => money.read(value, "money");
329
348
  function addMoney(a, b) {
330
349
  a = parseMoney(a);
331
350
  b = parseMoney(b);
332
- if (a.currency !== b.currency) fail2("money.currency", "currency mismatch; no implicit FX");
351
+ if (a.currency !== b.currency) fail3("money.currency", "currency mismatch; no implicit FX");
333
352
  return parseMoney({ currency: a.currency, amountMicros: (BigInt(a.amountMicros) + BigInt(b.amountMicros)).toString() });
334
353
  }
335
354
  function moneyToProviderUnits(input, account) {
336
355
  const m = parseMoney(input);
337
356
  currency.read(account.currency, "account.currency");
338
357
  decimal.read(account.maxUnits, "account.maxUnits");
339
- if (m.currency !== account.currency) fail2("money.currency", "currency mismatch");
340
- if (![0, 2, 3, 6].includes(account.unitExponent)) fail2("account.unitExponent", "unsupported provider exponent");
358
+ if (m.currency !== account.currency) fail3("money.currency", "currency mismatch");
359
+ if (![0, 2, 3, 6].includes(account.unitExponent)) fail3("account.unitExponent", "unsupported provider exponent");
341
360
  const factor = 10n ** BigInt(6 - account.unitExponent), amount = BigInt(m.amountMicros);
342
- if (amount % factor !== 0n) fail2("money.amountMicros", "not exactly representable in provider units");
361
+ if (amount % factor !== 0n) fail3("money.amountMicros", "not exactly representable in provider units");
343
362
  const units = amount / factor;
344
- if (units > BigInt(account.maxUnits)) fail2("money.amountMicros", "provider overflow");
363
+ if (units > BigInt(account.maxUnits)) fail3("money.amountMicros", "provider overflow");
345
364
  return units.toString();
346
365
  }
347
366
  function moneyFromProviderUnits(units, account) {
348
367
  decimal.read(units, "provider.units");
349
- if (![0, 2, 3, 6].includes(account.unitExponent)) fail2("account.unitExponent", "unsupported provider exponent");
368
+ if (![0, 2, 3, 6].includes(account.unitExponent)) fail3("account.unitExponent", "unsupported provider exponent");
350
369
  return parseMoney({ currency: account.currency, amountMicros: (BigInt(units) * 10n ** BigInt(6 - account.unitExponent)).toString() });
351
370
  }
352
371
  var MONEY_JSON_SCHEMA = money.schema;
353
- var sourceMarker = text2(1536, /^rsm1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/);
372
+ var sourceMarker = text3(1536, /^rsm1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/);
354
373
  var parseResonanceSourceMarker = (v) => sourceMarker.read(v, "sourceMarker");
355
374
  var RESONANCE_SOURCE_MARKER_JSON_SCHEMA = sourceMarker.schema;
356
375
  var scope = { projectId: uuid, site };
@@ -360,13 +379,13 @@ var qualificationFields = { schemaVersion: literal2(1), semantics: literal2("cur
360
379
  var checkQualificationPartitions = (v, p) => {
361
380
  unique([...v.positiveStageKeys, ...v.finalNegativeStageKeys, ...v.pendingStageKeys], p + ".stagePartitions");
362
381
  };
363
- var qualificationRule = refine2(object2({ ...qualificationFields, attributionModel: literal2(RESONANCE_ATTRIBUTION_MODEL) }), checkQualificationPartitions);
382
+ var qualificationRule = refine3(object2({ ...qualificationFields, attributionModel: literal2(RESONANCE_ATTRIBUTION_MODEL) }), checkQualificationPartitions);
364
383
  var parseResonanceQualificationRule = (v) => qualificationRule.read(v, "qualificationRule");
365
384
  var RESONANCE_QUALIFICATION_RULE_JSON_SCHEMA = qualificationRule.schema;
366
- var resolvedQualificationRule = refine2(object2({
385
+ var resolvedQualificationRule = refine3(object2({
367
386
  ...qualificationFields,
368
387
  ref: resource,
369
- crmVariant: text2(128),
388
+ crmVariant: text3(128),
370
389
  ladderSnapshot: list2(object2({ id: nullable2(uuid), stage_key: revision, semantic_key: nullable2(revision), is_won: bool, is_lost: bool }), 500, 1),
371
390
  // eligibleBookingTypeIds: Sync booking types whose confirmed bookings also count, beside the one form. Absent means forms only.
372
391
  eligibleFormIds: list2(uuid, 500, 1),
@@ -375,18 +394,18 @@ var resolvedQualificationRule = refine2(object2({
375
394
  cohort: object2({ startAt: instant, endAt: instant, maturityDelaySeconds: integer2(0, 31536e3) })
376
395
  }), (v, p) => {
377
396
  checkQualificationPartitions(v, p);
378
- if (v.ref.module !== "crm" || v.ref.id !== v.ref.projectId) fail2(p + ".ref", "must reference the actual CRM project configuration");
397
+ if (v.ref.module !== "crm" || v.ref.id !== v.ref.projectId) fail3(p + ".ref", "must reference the actual CRM project configuration");
379
398
  unique(v.eligibleFormIds, p + ".eligibleFormIds");
380
399
  if (v.eligibleBookingTypeIds) unique(v.eligibleBookingTypeIds.map((x) => x.toLowerCase()), p + ".eligibleBookingTypeIds");
381
400
  unique(v.ladderSnapshot.flatMap((x) => x.id ? [x.id] : []), p + ".ladderSnapshot.id");
382
401
  unique(v.ladderSnapshot.map((x) => x.stage_key), p + ".ladderSnapshot.stage_key");
383
402
  const partitions = [...v.positiveStageKeys, ...v.finalNegativeStageKeys, ...v.pendingStageKeys], keys = new Set(v.ladderSnapshot.map((x) => x.stage_key));
384
- if (partitions.length !== keys.size || partitions.some((k) => !keys.has(k))) fail2(p + ".stagePartitions", "must exhaust the actual native ladder");
385
- if (Date.parse(v.cohort.endAt) <= Date.parse(v.cohort.startAt)) fail2(p + ".cohort", "invalid cohort interval");
403
+ if (partitions.length !== keys.size || partitions.some((k) => !keys.has(k))) fail3(p + ".stagePartitions", "must exhaust the actual native ladder");
404
+ if (Date.parse(v.cohort.endAt) <= Date.parse(v.cohort.startAt)) fail3(p + ".cohort", "invalid cohort interval");
386
405
  });
387
406
  var parseResonanceResolvedQualificationRule = (v) => resolvedQualificationRule.read(v, "resolvedQualificationRule");
388
407
  var RESONANCE_RESOLVED_QUALIFICATION_RULE_JSON_SCHEMA = resolvedQualificationRule.schema;
389
- var objective = refine2(object2({
408
+ var objective = refine3(object2({
390
409
  source,
391
410
  measurementRevision: revision,
392
411
  countingUnit: objectiveCountingUnit,
@@ -398,23 +417,23 @@ var objective = refine2(object2({
398
417
  eligibleBookingTypeIds: optional2(list2(uuid, 100, 1))
399
418
  }), (v, p) => {
400
419
  if (v.eligibleBookingTypeIds) {
401
- if (v.source.kind !== "qualified_lead") fail2(p + ".eligibleBookingTypeIds", "requires the native qualified-lead source");
420
+ if (v.source.kind !== "qualified_lead") fail3(p + ".eligibleBookingTypeIds", "requires the native qualified-lead source");
402
421
  unique(v.eligibleBookingTypeIds.map((x) => x.toLowerCase()), p + ".eligibleBookingTypeIds");
403
422
  }
404
- if (v.qualificationRule && v.source.kind !== "qualified_lead") fail2(p + ".qualificationRule", "requires the native qualified-lead source");
405
- if (v.qualificationRule && v.qualificationRuleRef && (v.qualificationRuleRef.module !== "crm" || v.qualificationRuleRef.id !== v.source.projectId)) fail2(p + ".qualificationRuleRef", "must reference actual CRM project configuration");
423
+ if (v.qualificationRule && v.source.kind !== "qualified_lead") fail3(p + ".qualificationRule", "requires the native qualified-lead source");
424
+ if (v.qualificationRule && v.qualificationRuleRef && (v.qualificationRuleRef.module !== "crm" || v.qualificationRuleRef.id !== v.source.projectId)) fail3(p + ".qualificationRuleRef", "must reference actual CRM project configuration");
406
425
  });
407
- var creative = object2({ id: uuid, assetRef: resource, preparedArtifactRef: nullable2(resource), headline: text2(160), body: text2(1e4), callToAction: text2(80), cropDigest: digest });
426
+ var creative = object2({ id: uuid, assetRef: resource, preparedArtifactRef: nullable2(resource), headline: text3(160), body: text3(1e4), callToAction: text3(80), cropDigest: digest });
408
427
  var destination = union2(
409
- object2({ kind: literal2("funnel"), id: uuid, ...scope, path, funnelRef: resource, formSlug: text2(80, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), installationRevision: revision }),
428
+ object2({ kind: literal2("funnel"), id: uuid, ...scope, path, funnelRef: resource, formSlug: text3(80, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), installationRevision: revision }),
410
429
  object2({ kind: literal2("existing_page"), id: uuid, ...scope, path, pageRevision: revision, evidenceDigest: digest })
411
430
  );
412
431
  var audience = object2({ ...scope, id: uuid, revision, policyRevision: revision, retentionDays: integer2(1, 540), exclusionRuleIds: list2(uuid, 50), minDaysSinceVisit: optional2(integer2(1, 179)), consentPurpose: literal2("ad_personalization") });
413
432
  var experiment = object2({ ...scope, id: uuid, revision: integer2(1), digest });
414
- var budget = refine2(object2({ total: money, dailyAllocationCeiling: nullable2(money), reserveMargin: money, startAt: instant, endAt: instant, timeZone, maxChange: money, maxChangeBasisPoints: integer2(0, 1e4), cooldownSeconds: integer2(0, 31536e3) }), (v, p) => {
415
- if (Date.parse(v.endAt) <= Date.parse(v.startAt)) fail2(p, "end must follow start");
416
- for (const m of [v.reserveMargin, v.maxChange, ...v.dailyAllocationCeiling ? [v.dailyAllocationCeiling] : []]) if (m.currency !== v.total.currency) fail2(p, "currency mismatch");
417
- if (BigInt(v.reserveMargin.amountMicros) > BigInt(v.total.amountMicros)) fail2(p, "reserve exceeds total");
433
+ var budget = refine3(object2({ total: money, dailyAllocationCeiling: nullable2(money), reserveMargin: money, startAt: instant, endAt: instant, timeZone, maxChange: money, maxChangeBasisPoints: integer2(0, 1e4), cooldownSeconds: integer2(0, 31536e3) }), (v, p) => {
434
+ if (Date.parse(v.endAt) <= Date.parse(v.startAt)) fail3(p, "end must follow start");
435
+ for (const m of [v.reserveMargin, v.maxChange, ...v.dailyAllocationCeiling ? [v.dailyAllocationCeiling] : []]) if (m.currency !== v.total.currency) fail3(p, "currency mismatch");
436
+ if (BigInt(v.reserveMargin.amountMicros) > BigInt(v.total.amountMicros)) fail3(p, "reserve exceeds total");
418
437
  });
419
438
  var allocationPolicyFields = {
420
439
  schemaVersion: literal2(1),
@@ -451,7 +470,7 @@ var finiteStopRule = choice2("exploration_cap", "flight_end", "policy_or_mandate
451
470
  var positiveMicrosPattern = /^[1-9][0-9]*(?![\s\S])/;
452
471
  var positiveMoneyShape = field2({ allOf: [money.schema, { properties: { amountMicros: { pattern: positiveMicrosPattern.source } } }] }, (v, p) => {
453
472
  const m = money.read(v, p);
454
- if (!positiveMicrosPattern.test(m.amountMicros)) fail2(p, "requires positive canonical money");
473
+ if (!positiveMicrosPattern.test(m.amountMicros)) fail3(p, "requires positive canonical money");
455
474
  return m;
456
475
  });
457
476
  var finiteMetaCandidatePolicy = object2({
@@ -479,27 +498,27 @@ function parseResonanceOptimizationPolicy(v) {
479
498
  return r;
480
499
  }
481
500
  const p = "optimizationPolicy", ids = r.candidateChannelIds, guard = r.measurementGuard;
482
- if (r.selection.candidateOrder.length !== ids.length || r.selection.candidateOrder.some((id) => !ids.includes(id))) fail2(p + ".selection.candidateOrder", "must be the exact candidate permutation");
501
+ if (r.selection.candidateOrder.length !== ids.length || r.selection.candidateOrder.some((id) => !ids.includes(id))) fail3(p + ".selection.candidateOrder", "must be the exact candidate permutation");
483
502
  unique(r.selection.eligibilitySchedule.map((s) => s.channelId), p + ".selection.eligibilitySchedule");
484
- if (r.selection.eligibilitySchedule.length !== ids.length || r.selection.eligibilitySchedule.some((s) => !ids.includes(s.channelId))) fail2(p + ".selection.eligibilitySchedule", "must cover exactly the original candidates");
485
- if (r.selection.eligibilitySchedule.some((s) => Date.parse(s.notAfter) <= Date.parse(s.notBefore) || Date.parse(s.notAfter) > Date.parse(r.expiresAt))) fail2(p + ".selection.eligibilitySchedule", "invalid policy selection window");
486
- if (r.maxConcurrentCandidates > ids.length) fail2(p + ".maxConcurrentCandidates", "exceeds finite candidate count");
487
- if (BigInt(r.totalExplorationCap.amountMicros) === 0n) fail2(p + ".totalExplorationCap", "requires a positive reviewed ceiling");
488
- if (guard.sourceRef.kind !== r.eligibleGoal || guard.qualificationRuleRef.module !== "crm" || guard.qualificationRuleRef.id !== guard.sourceRef.projectId || guard.qualificationRuleRef.projectId !== guard.sourceRef.projectId || guard.qualificationRuleRef.site !== guard.sourceRef.site) fail2(p + ".measurementGuard", "requires the original qualified source and CRM witness scope");
503
+ if (r.selection.eligibilitySchedule.length !== ids.length || r.selection.eligibilitySchedule.some((s) => !ids.includes(s.channelId))) fail3(p + ".selection.eligibilitySchedule", "must cover exactly the original candidates");
504
+ if (r.selection.eligibilitySchedule.some((s) => Date.parse(s.notAfter) <= Date.parse(s.notBefore) || Date.parse(s.notAfter) > Date.parse(r.expiresAt))) fail3(p + ".selection.eligibilitySchedule", "invalid policy selection window");
505
+ if (r.maxConcurrentCandidates > ids.length) fail3(p + ".maxConcurrentCandidates", "exceeds finite candidate count");
506
+ if (BigInt(r.totalExplorationCap.amountMicros) === 0n) fail3(p + ".totalExplorationCap", "requires a positive reviewed ceiling");
507
+ if (guard.sourceRef.kind !== r.eligibleGoal || guard.qualificationRuleRef.module !== "crm" || guard.qualificationRuleRef.id !== guard.sourceRef.projectId || guard.qualificationRuleRef.projectId !== guard.sourceRef.projectId || guard.qualificationRuleRef.site !== guard.sourceRef.site) fail3(p + ".measurementGuard", "requires the original qualified source and CRM witness scope");
489
508
  scoped(r, guard.sourceRef.projectId, [guard.sourceRef.site], p);
490
509
  return r;
491
510
  }
492
511
  var RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA = optimizationPolicy.schema;
493
512
  var optimization = object2({ enabled: bool, policy: optimizationPolicy, stopLoss: object2({ confirmedSpend: money, unreconciledExposure: money }) });
494
513
  var channelBase = { id: uuid, ...scope, destinationId: uuid, creativeIds: list2(uuid, 50, 1) };
495
- var search = object2({ ...channelBase, localCampaignKey: text2(80), kind: literal2("google_search"), provider: literal2("google_ads"), accountBindingId: uuid, capabilityRevision: revision, allocation: money, budgetMode: choice2("campaign_total", "average_daily"), keywords: list2(object2({ text: text2(80), match: choice2("exact", "phrase", "broad") }), 200, 1), negativeKeywords: list2(text2(80), 200), bidding: union2(object2({ strategy: literal2("maximize_conversions") }), object2({ strategy: literal2("target_cpa"), target: money })), locationIds: list2(text2(80), 100, 1), network: object2({ googleSearch: literal2(true), searchPartners: bool, displayExpansion: literal2(false) }), geoPresence: choice2("presence", "presence_or_interest"), excludedLocationIds: list2(text2(80), 100), adGroups: list2(object2({ localKey: text2(80), ads: list2(object2({ localKey: text2(80), creativeId: uuid, headlines: list2(text2(30), 15, 3), descriptions: list2(text2(90), 4, 2) }), 20, 1) }), 100, 1), assetAutomation: literal2("disabled") });
496
- var metaAgeConstraint = union2(refine2(object2({ mode: literal2("bounded"), min: integer2(1, 120), max: integer2(1, 120) }), (v, p) => {
497
- if (v.min > v.max) fail2(p, "minimum age exceeds maximum");
514
+ var search = object2({ ...channelBase, localCampaignKey: text3(80), kind: literal2("google_search"), provider: literal2("google_ads"), accountBindingId: uuid, capabilityRevision: revision, allocation: money, budgetMode: choice2("campaign_total", "average_daily"), keywords: list2(object2({ text: text3(80), match: choice2("exact", "phrase", "broad") }), 200, 1), negativeKeywords: list2(text3(80), 200), bidding: union2(object2({ strategy: literal2("maximize_conversions") }), object2({ strategy: literal2("target_cpa"), target: money })), locationIds: list2(text3(80), 100, 1), network: object2({ googleSearch: literal2(true), searchPartners: bool, displayExpansion: literal2(false) }), geoPresence: choice2("presence", "presence_or_interest"), excludedLocationIds: list2(text3(80), 100), adGroups: list2(object2({ localKey: text3(80), ads: list2(object2({ localKey: text3(80), creativeId: uuid, headlines: list2(text3(30), 15, 3), descriptions: list2(text3(90), 4, 2) }), 20, 1) }), 100, 1), assetAutomation: literal2("disabled") });
515
+ var metaAgeConstraint = union2(refine3(object2({ mode: literal2("bounded"), min: integer2(1, 120), max: integer2(1, 120) }), (v, p) => {
516
+ if (v.min > v.max) fail3(p, "minimum age exceeds maximum");
498
517
  }), object2({ mode: literal2("omitted") }), object2({ mode: literal2("provider_managed") }));
499
- var propertyKey = object2({ key: text2(40, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), label: text2(80) });
518
+ var propertyKey = object2({ key: text3(40, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), label: text3(80) });
500
519
  var meta = object2({
501
520
  ...channelBase,
502
- localCampaignKey: text2(80),
521
+ localCampaignKey: text3(80),
503
522
  kind: literal2("meta_retargeting"),
504
523
  provider: literal2("meta_ads"),
505
524
  accountBindingId: uuid,
@@ -508,34 +527,34 @@ var meta = object2({
508
527
  budgetMode: choice2("lifetime", "daily"),
509
528
  audienceRuleRefs: list2(audience, 50, 1),
510
529
  objective: choice2("OUTCOME_LEADS", "OUTCOME_SALES", "OUTCOME_TRAFFIC"),
511
- pageRef: object2({ connectionId: uuid, externalId: text2(160), revision }),
512
- instagramRef: nullable2(object2({ connectionId: uuid, externalId: text2(160), revision })),
513
- datasetRef: object2({ id: text2(160), revision }),
530
+ pageRef: object2({ connectionId: uuid, externalId: text3(160), revision }),
531
+ instagramRef: nullable2(object2({ connectionId: uuid, externalId: text3(160), revision })),
532
+ datasetRef: object2({ id: text3(160), revision }),
514
533
  conversionGoalRef: resource,
515
534
  optimization: choice2("landing_page_views", "lead", "purchase"),
516
535
  billing: literal2("impressions"),
517
536
  bid: union2(object2({ strategy: literal2("lowest_cost") }), object2({ strategy: literal2("cost_cap"), cap: money })),
518
- localAdSetKey: text2(80),
519
- localAdKey: text2(80),
537
+ localAdSetKey: text3(80),
538
+ localAdKey: text3(80),
520
539
  budgetOwner: choice2("campaign", "adset"),
521
540
  specialCategories: list2(choice2("housing", "employment", "financial_products_services"), 3),
522
- countryCodes: list2(text2(2, /^[A-Z]{2}$/), 30, 1),
541
+ countryCodes: list2(text3(2, /^[A-Z]{2}$/), 30, 1),
523
542
  placement: literal2("automatic"),
524
543
  ageConstraint: optional2(metaAgeConstraint),
525
544
  // Property retargeting (one channel per property under one group). Every field is optional and omitted from the canonical form when absent, so no existing reviewed digest changes.
526
545
  channelGroup: optional2(propertyKey),
527
546
  property: optional2(propertyKey),
528
- tier: optional2(object2({ label: text2(40) })),
529
- primaryText: optional2(text2(2200)),
547
+ tier: optional2(object2({ label: text3(40) })),
548
+ primaryText: optional2(text3(2200)),
530
549
  convertersAcknowledged: optional2(literal2(true))
531
550
  });
532
551
  var owned = object2({ ...channelBase, kind: choice2("funnel", "broadcast", "outreach"), resourceRef: resource });
533
552
  var channel = union2(search, meta, owned);
534
- var definitionFields = { schemaVersion: literal2(1), projectId: uuid, name: text2(160), slug: refine2(text2(80), (v, p) => {
535
- if (normalizeCampaignSlug(v) !== v) fail2(p, "must be canonical campaign slug");
553
+ var definitionFields = { schemaVersion: literal2(1), projectId: uuid, name: text3(160), slug: refine3(text3(80), (v, p) => {
554
+ if (normalizeCampaignSlug(v) !== v) fail3(p, "must be canonical campaign slug");
536
555
  }), sites: list2(site, 50, 1), objective, brandRef: resource, creativeRefs: list2(creative, 100, 1), destinations: list2(destination, 100, 1), channels: list2(channel, 100, 1), experimentRefs: list2(experiment, 50), budget, optimization };
537
556
  var definition = object2(definitionFields);
538
- var draft = object2({ schemaVersion: literal2(1), projectId: uuid, name: text2(160, void 0, 0), slug: definitionFields.slug, sites: list2(site, 50), objective: optional2(objective), brandRef: optional2(resource), creativeRefs: optional2(list2(creative, 100)), destinations: optional2(list2(destination, 100)), channels: optional2(list2(channel, 100)), experimentRefs: optional2(list2(experiment, 50)), budget: optional2(budget), optimization: optional2(optimization) });
557
+ var draft = object2({ schemaVersion: literal2(1), projectId: uuid, name: text3(160, void 0, 0), slug: definitionFields.slug, sites: list2(site, 50), objective: optional2(objective), brandRef: optional2(resource), creativeRefs: optional2(list2(creative, 100)), destinations: optional2(list2(destination, 100)), channels: optional2(list2(channel, 100)), experimentRefs: optional2(list2(experiment, 50)), budget: optional2(budget), optimization: optional2(optimization) });
539
558
  function scoped(value, projectId, sites, at) {
540
559
  if (!value || typeof value !== "object") return;
541
560
  if (Array.isArray(value)) {
@@ -543,36 +562,36 @@ function scoped(value, projectId, sites, at) {
543
562
  return;
544
563
  }
545
564
  const v = value;
546
- if ("projectId" in v && v.projectId !== projectId) fail2(at, "cross-project reference");
547
- if ("site" in v && !sites.includes(v.site)) fail2(at, "site outside campaign scope");
565
+ if ("projectId" in v && v.projectId !== projectId) fail3(at, "cross-project reference");
566
+ if ("site" in v && !sites.includes(v.site)) fail3(at, "site outside campaign scope");
548
567
  for (const [k, x] of Object.entries(v)) scoped(x, projectId, sites, `${at}.${k}`);
549
568
  }
550
569
  function unique(values, at) {
551
- if (new Set(values).size !== values.length) fail2(at, "duplicate identity");
570
+ if (new Set(values).size !== values.length) fail3(at, "duplicate identity");
552
571
  }
553
572
  function checkDefinition(v) {
554
573
  unique(v.sites, "campaign.sites");
555
574
  scoped(v, v.projectId, v.sites, "campaign");
556
575
  parseResonanceOptimizationPolicy(v.optimization.policy);
557
- if (v.optimization.enabled && v.objective.source.kind !== v.optimization.policy.eligibleGoal) fail2("campaign.optimization.policy", "policy is not eligible for this goal");
558
- if ([v.optimization.stopLoss.confirmedSpend, v.optimization.stopLoss.unreconciledExposure].some((m) => m.currency !== v.budget.total.currency)) fail2("campaign.optimization.stopLoss", "currency mismatch");
576
+ if (v.optimization.enabled && v.objective.source.kind !== v.optimization.policy.eligibleGoal) fail3("campaign.optimization.policy", "policy is not eligible for this goal");
577
+ if ([v.optimization.stopLoss.confirmedSpend, v.optimization.stopLoss.unreconciledExposure].some((m) => m.currency !== v.budget.total.currency)) fail3("campaign.optimization.stopLoss", "currency mismatch");
559
578
  unique(v.channels.map((c) => c.id), "campaign.channels");
560
579
  unique(v.creativeRefs.map((c) => c.id), "campaign.creativeRefs");
561
580
  unique(v.destinations.map((d) => d.id), "campaign.destinations");
562
- if (!["business_brain", "publication"].includes(v.brandRef.module)) fail2("campaign.brandRef", "must reference existing brand owner");
563
- for (const c of v.creativeRefs) if (c.assetRef.module !== "files" || c.preparedArtifactRef && !["files", "broadcast"].includes(c.preparedArtifactRef.module)) fail2("campaign.creativeRefs", "unsupported asset owner");
564
- for (const d of v.destinations) if (d.kind === "funnel" && d.funnelRef.module !== "funnel") fail2("campaign.destinations", "must reference funnel owner");
581
+ if (!["business_brain", "publication"].includes(v.brandRef.module)) fail3("campaign.brandRef", "must reference existing brand owner");
582
+ for (const c of v.creativeRefs) if (c.assetRef.module !== "files" || c.preparedArtifactRef && !["files", "broadcast"].includes(c.preparedArtifactRef.module)) fail3("campaign.creativeRefs", "unsupported asset owner");
583
+ for (const d of v.destinations) if (d.kind === "funnel" && d.funnelRef.module !== "funnel") fail3("campaign.destinations", "must reference funnel owner");
565
584
  for (const c of v.channels) {
566
- const dest = v.destinations.find((d) => d.id === c.destinationId) ?? fail2("campaign.channels.destinationId", "must reference a destination ID");
567
- if (dest.site !== c.site) fail2("campaign.channels.destinationId", "destination site mismatch");
568
- if (c.creativeIds.some((id) => !v.creativeRefs.some((x) => x.id === id))) fail2("campaign.channels.creativeIds", "unknown creative");
569
- if ("bid" in c && "cap" in c.bid && c.bid.cap.currency !== v.budget.total.currency) fail2("campaign.channels.bid", "currency mismatch");
585
+ const dest = v.destinations.find((d) => d.id === c.destinationId) ?? fail3("campaign.channels.destinationId", "must reference a destination ID");
586
+ if (dest.site !== c.site) fail3("campaign.channels.destinationId", "destination site mismatch");
587
+ if (c.creativeIds.some((id) => !v.creativeRefs.some((x) => x.id === id))) fail3("campaign.channels.creativeIds", "unknown creative");
588
+ if ("bid" in c && "cap" in c.bid && c.bid.cap.currency !== v.budget.total.currency) fail3("campaign.channels.bid", "currency mismatch");
570
589
  if ("adGroups" in c) {
571
- for (const g of c.adGroups) for (const a of g.ads) if (!c.creativeIds.includes(a.creativeId)) fail2("campaign.channels.adGroups", "ad creative outside channel");
590
+ for (const g of c.adGroups) for (const a of g.ads) if (!c.creativeIds.includes(a.creativeId)) fail3("campaign.channels.adGroups", "ad creative outside channel");
572
591
  }
573
- if ("resourceRef" in c && c.resourceRef.module !== c.kind) fail2("campaign.channels.resourceRef", "module owner mismatch");
574
- if ("bidding" in c && "target" in c.bidding && c.bidding.target.currency !== v.budget.total.currency) fail2("campaign.channels.bidding", "currency mismatch");
575
- if ("allocation" in c && c.allocation.currency !== v.budget.total.currency) fail2("campaign.channels.allocation", "currency mismatch");
592
+ if ("resourceRef" in c && c.resourceRef.module !== c.kind) fail3("campaign.channels.resourceRef", "module owner mismatch");
593
+ if ("bidding" in c && "target" in c.bidding && c.bidding.target.currency !== v.budget.total.currency) fail3("campaign.channels.bidding", "currency mismatch");
594
+ if ("allocation" in c && c.allocation.currency !== v.budget.total.currency) fail3("campaign.channels.allocation", "currency mismatch");
576
595
  }
577
596
  checkChannelGroups(v.channels);
578
597
  checkGroupedAllocations(v);
@@ -580,12 +599,12 @@ function checkDefinition(v) {
580
599
  const policy = v.optimization.policy;
581
600
  if (policy.algorithm === "finite_meta_candidates_v1") {
582
601
  const guard = policy.measurementGuard, goal = v.objective;
583
- if (canonical(guard.sourceRef) !== canonical(goal.source) || !goal.qualificationRuleRef || canonical(guard.qualificationRuleRef) !== canonical(goal.qualificationRuleRef) || guard.maturityDelaySeconds !== goal.maturityDelaySeconds || goal.countingUnit !== "unique_qualified_contact") fail2("campaign.optimization.policy.measurementGuard", "must match the original qualified objective");
584
- if (policy.totalExplorationCap.currency !== v.budget.total.currency || compareMoney(policy.totalExplorationCap, v.budget.total) > 0) fail2("campaign.optimization.policy.totalExplorationCap", "outside original budget ceiling");
585
- if (Date.parse(policy.expiresAt) > Date.parse(v.budget.endAt) || policy.selection.eligibilitySchedule.some((s) => Date.parse(s.notBefore) < Date.parse(v.budget.startAt) || Date.parse(s.notAfter) > Date.parse(v.budget.endAt))) fail2("campaign.optimization.policy.selection", "selection windows must stay inside the original flight");
602
+ if (canonical(guard.sourceRef) !== canonical(goal.source) || !goal.qualificationRuleRef || canonical(guard.qualificationRuleRef) !== canonical(goal.qualificationRuleRef) || guard.maturityDelaySeconds !== goal.maturityDelaySeconds || goal.countingUnit !== "unique_qualified_contact") fail3("campaign.optimization.policy.measurementGuard", "must match the original qualified objective");
603
+ if (policy.totalExplorationCap.currency !== v.budget.total.currency || compareMoney(policy.totalExplorationCap, v.budget.total) > 0) fail3("campaign.optimization.policy.totalExplorationCap", "outside original budget ceiling");
604
+ if (Date.parse(policy.expiresAt) > Date.parse(v.budget.endAt) || policy.selection.eligibilitySchedule.some((s) => Date.parse(s.notBefore) < Date.parse(v.budget.startAt) || Date.parse(s.notAfter) > Date.parse(v.budget.endAt))) fail3("campaign.optimization.policy.selection", "selection windows must stay inside the original flight");
586
605
  for (const id of policy.candidateChannelIds) {
587
606
  const c = v.channels.find((c2) => c2.id === id);
588
- if (!c || c.kind !== "meta_retargeting" || c.budgetMode !== "lifetime" || c.budgetOwner !== "adset" || BigInt(c.allocation.amountMicros) === 0n) fail2("campaign.optimization.policy.candidateChannelIds", "requires an original independently capped Meta adset channel");
607
+ if (!c || c.kind !== "meta_retargeting" || c.budgetMode !== "lifetime" || c.budgetOwner !== "adset" || BigInt(c.allocation.amountMicros) === 0n) fail3("campaign.optimization.policy.candidateChannelIds", "requires an original independently capped Meta adset channel");
589
608
  }
590
609
  }
591
610
  }
@@ -602,10 +621,10 @@ function parseResonanceCampaignDraft(v) {
602
621
  }
603
622
  var RESONANCE_CAMPAIGN_DEFINITION_JSON_SCHEMA = definition.schema;
604
623
  var RESONANCE_CAMPAIGN_DRAFT_JSON_SCHEMA = draft.schema;
605
- var capability = object2({ id: uuid, projectId: uuid, connectionId: uuid, provider: choice2("google_ads", "meta_ads"), externalAccountId: text2(160), currency, timeZone, connectionRevision: revision, capabilityRevision: revision, observedAt: instant, expiresAt: instant, advertiserState: choice2("eligible", "blocked", "unknown"), operations: list2(object2({ operation: choice2("discover", "prepare", "launch", "update", "pause", "resume", "finish", "reconcile", "measure", "audience", "conversion", "experiment"), state: choice2("supported", "blocked", "unknown"), reasonCodes: list2(text2(80), 30), prerequisites: list2(text2(100), 30) }), 20), profiles: list2(object2({ profile: choice2("google_search", "meta_retargeting"), state: choice2("supported", "blocked", "unknown"), reasonCodes: list2(text2(80), 30), budgetModes: list2(choice2("campaign_total", "average_daily", "lifetime", "daily"), 4), providerApiVersion: text2(30) }), 2) });
624
+ var capability = object2({ id: uuid, projectId: uuid, connectionId: uuid, provider: choice2("google_ads", "meta_ads"), externalAccountId: text3(160), currency, timeZone, connectionRevision: revision, capabilityRevision: revision, observedAt: instant, expiresAt: instant, advertiserState: choice2("eligible", "blocked", "unknown"), operations: list2(object2({ operation: choice2("discover", "prepare", "launch", "update", "pause", "resume", "finish", "reconcile", "measure", "audience", "conversion", "experiment"), state: choice2("supported", "blocked", "unknown"), reasonCodes: list2(text3(80), 30), prerequisites: list2(text3(100), 30) }), 20), profiles: list2(object2({ profile: choice2("google_search", "meta_retargeting"), state: choice2("supported", "blocked", "unknown"), reasonCodes: list2(text3(80), 30), budgetModes: list2(choice2("campaign_total", "average_daily", "lifetime", "daily"), 4), providerApiVersion: text3(30) }), 2) });
606
625
  var parseResonanceAccountCapability = (v) => {
607
626
  const r = capability.read(v, "account");
608
- if (Date.parse(r.expiresAt) <= Date.parse(r.observedAt)) fail2("account.expiresAt", "must follow observation");
627
+ if (Date.parse(r.expiresAt) <= Date.parse(r.observedAt)) fail3("account.expiresAt", "must follow observation");
609
628
  return r;
610
629
  };
611
630
  var mandateRef = object2({ ledgerActionId: uuid, campaignId: uuid, preparedPlanId: uuid, reviewDigest: digest, mandateDigest: digest, expectedKillRevision: integer2(0) });
@@ -633,23 +652,110 @@ var websiteVisitFeed = object2({ profile: literal2(RESONANCE_WEBSITE_VISIT_PROFI
633
652
  matchingProfileRef
634
653
  }), 100, 1) });
635
654
  var RESONANCE_WEBSITE_VISIT_FEED_JSON_SCHEMA = websiteVisitFeed.schema;
636
- var providerReportingChannelIds = refine2(uniqueList(uuid, 100, 1), (ids, p) => unique(ids.map((id) => id.toLowerCase()), p));
655
+ var providerReportingChannelIds = refine3(uniqueList(uuid, 100, 1), (ids, p) => unique(ids.map((id) => id.toLowerCase()), p));
637
656
  var RESONANCE_META_QUERY_ATTRIBUTION_WINDOWS = ["1d_click", "7d_click", "1d_view"];
638
657
  var metaReportingQuery = object2({ channelId: uuid, attributionWindow: choice2(...RESONANCE_META_QUERY_ATTRIBUTION_WINDOWS), actionReportTime: literal2("conversion"), basis: literal2("explicit_query") });
639
- var providerReportingMetaQueries = refine2(list2(metaReportingQuery, 100, 1), (queries, p) => unique(queries.map((query) => query.channelId.toLowerCase()), p));
658
+ var providerReportingMetaQueries = refine3(list2(metaReportingQuery, 100, 1), (queries, p) => unique(queries.map((query) => query.channelId.toLowerCase()), p));
640
659
  function checkReportingQuerySubset(v, p) {
641
- if (v.metaQueries?.some((query) => !v.channelIds.some((id) => id.toLowerCase() === query.channelId.toLowerCase()))) fail2(p + ".metaQueries", "query channel must be selected");
660
+ if (v.metaQueries?.some((query) => !v.channelIds.some((id) => id.toLowerCase() === query.channelId.toLowerCase()))) fail3(p + ".metaQueries", "query channel must be selected");
642
661
  }
643
- var providerReportingSelection = refine2(object2({ agentContactId: uuid, channelIds: providerReportingChannelIds, metaQueries: optional2(providerReportingMetaQueries) }), checkReportingQuerySubset);
644
- var providerReportingGrant = refine2(object2({ purpose: literal2("provider_reporting_refresh"), orgId: uuid, projectId: uuid, agentContactId: uuid, principalContactId: uuid, channelIds: providerReportingChannelIds, metaQueries: optional2(providerReportingMetaQueries) }), (v, p) => {
645
- if (v.agentContactId.toLowerCase() === v.principalContactId.toLowerCase()) fail2(p + ".principalContactId", "agent and human principal must remain distinct");
662
+ var providerReportingSelection = refine3(object2({ agentContactId: uuid, channelIds: providerReportingChannelIds, metaQueries: optional2(providerReportingMetaQueries) }), checkReportingQuerySubset);
663
+ var providerReportingGrant = refine3(object2({ purpose: literal2("provider_reporting_refresh"), orgId: uuid, projectId: uuid, agentContactId: uuid, principalContactId: uuid, channelIds: providerReportingChannelIds, metaQueries: optional2(providerReportingMetaQueries), reportingUntil: optional2(instant) }), (v, p) => {
664
+ if (v.agentContactId.toLowerCase() === v.principalContactId.toLowerCase()) fail3(p + ".principalContactId", "agent and human principal must remain distinct");
646
665
  checkReportingQuerySubset(v, p);
647
666
  });
648
667
  var parseResonanceProviderReportingSelection = (v) => providerReportingSelection.read(v, "providerReportingSelection");
649
668
  var parseResonanceProviderReportingGrant = (v) => providerReportingGrant.read(v, "providerReportingGrant");
650
669
  var RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA = providerReportingSelection.schema;
651
670
  var RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA = providerReportingGrant.schema;
652
- var mandateScope = object2({ projectId: uuid, campaignId: uuid, preparedPlanId: uuid, reviewDigest: digest, accountBindingIds: list2(uuid, 100), sites: list2(site, 50, 1), budget, creativeRefs: list2(creative, 100, 1), audienceRuleRefs: list2(audience, 100), goal: objective, allowedOperations: mandateAllowedOperations, allowedTransformationRef: nullable2(resource), expiresAt: instant, websiteVisitFeed: optional2(websiteVisitFeed), providerReporting: optional2(providerReportingGrant) });
671
+ var RESONANCE_PROVIDER_REPORTING_MAX_TAIL_DAYS = 92;
672
+ var googleContentTarget = { channelId: uuid, adGroupLocalKey: text3(80), adLocalKey: text3(80) };
673
+ var normalizeResonanceGoogleCriterionText = (value) => value.trim().replace(/\s+/gu, " ").toLowerCase().normalize("NFC");
674
+ var googleCriterionText = text3(80, /^(?! +$)[^\x00-\x1f\x7f]+$/);
675
+ var googleExactText = text3(80, /^(?! +$)[^\x00-\x1f\x7f\\\[\]"]+$/);
676
+ var googleContentKeywords = (criterion) => refine3(list2(criterion, 20), (items, p) => {
677
+ const normalized = items.map(normalizeResonanceGoogleCriterionText);
678
+ if (normalized.some((value) => !value || value.length > 80)) fail3(p, "requires nonempty bounded criterion text");
679
+ unique(normalized, p);
680
+ items.splice(0, items.length, ...normalized.sort());
681
+ });
682
+ var rsaAsset = (length) => refine3(text3(length, /^[^\x00-\x1f\x7f]+$/), (asset, p) => {
683
+ if (!asset.trim() || asset.trim() !== asset) fail3(p, "requires trimmed, nonempty asset text");
684
+ });
685
+ var googleContentRsa = object2({
686
+ creativeRef: resource,
687
+ headlines: uniqueList(rsaAsset(30), 15, 3),
688
+ descriptions: uniqueList(rsaAsset(90), 4, 2)
689
+ });
690
+ var googleContentMaterial = {
691
+ negativeRemovals: googleContentKeywords(googleCriterionText),
692
+ exactAdditions: googleContentKeywords(googleExactText),
693
+ rsa: nullable2(googleContentRsa)
694
+ };
695
+ var googleContentEntry = refine3(object2({ ...googleContentTarget, ...googleContentMaterial }), (entry, p) => {
696
+ if (!entry.negativeRemovals.length && !entry.exactAdditions.length && !entry.rsa) fail3(p, "must select at least one bounded content effect");
697
+ });
698
+ var googleSearchContent = refine3(list2(googleContentEntry, 100), (entries, p) => {
699
+ const identity = (entry) => JSON.stringify([entry.channelId.toLowerCase(), entry.adGroupLocalKey, entry.adLocalKey]);
700
+ unique(entries.map(identity), p);
701
+ entries.sort((a, b) => identity(a) < identity(b) ? -1 : identity(a) > identity(b) ? 1 : 0);
702
+ });
703
+ var operatingPolicyFields = {
704
+ schemaVersion: literal2(1),
705
+ agentContactId: uuid,
706
+ googleSearchContent,
707
+ cooldownSeconds: integer2(3600, 2592e3)
708
+ };
709
+ var operatingPolicySelection = object2(operatingPolicyFields);
710
+ var operatingPolicy = refine3(object2({ ...operatingPolicyFields, principalContactId: uuid }), (policy, p) => {
711
+ if (policy.agentContactId.toLowerCase() === policy.principalContactId.toLowerCase()) {
712
+ fail3(p + ".principalContactId", "agent and human principal must remain distinct");
713
+ }
714
+ });
715
+ var operatingPolicyRef = object2({ ledgerActionId: uuid, receiptId: uuid, digest });
716
+ var operatingPolicyBase = object2({
717
+ ledgerActionId: uuid,
718
+ acceptanceReceiptId: uuid,
719
+ expectedKillRevision: integer2(0),
720
+ previousOperatingPolicyRef: nullable2(operatingPolicyRef)
721
+ });
722
+ var operatingPolicyActionIdentity = object2({ mandateDigest: digest, operatingPolicyBase });
723
+ var googleContentUpdateSelection = object2(googleContentTarget);
724
+ var googleContentUpdate = refine3(object2({ ...googleContentTarget, ...googleContentMaterial, policyRef: operatingPolicyRef, beforeDigest: digest }), (update2, p) => {
725
+ if (!update2.negativeRemovals.length && !update2.exactAdditions.length && !update2.rsa) fail3(p, "must select at least one bounded content effect");
726
+ });
727
+ var parseResonanceOperatingPolicy = (v) => operatingPolicy.read(v, "operatingPolicy");
728
+ var parseResonanceOperatingPolicySelection = (v) => operatingPolicySelection.read(v, "operatingPolicySelection");
729
+ var parseResonanceOperatingPolicyBase = (v) => operatingPolicyBase.read(v, "operatingPolicyBase");
730
+ var parseResonanceOperatingPolicyRef = (v) => operatingPolicyRef.read(v, "operatingPolicyRef");
731
+ var parseResonanceGoogleContentUpdateSelection = (v) => googleContentUpdateSelection.read(v, "googleContentUpdateSelection");
732
+ var parseResonanceGoogleContentUpdate = (v) => googleContentUpdate.read(v, "googleContentUpdate");
733
+ var resonanceOperatingPolicyDigestInput = (v) => canonical(parseResonanceOperatingPolicy(v));
734
+ function resonanceOperatingPolicyActionDigestInput(v) {
735
+ const { mandateDigest, operatingPolicyBase: base } = operatingPolicyActionIdentity.read(v, "operatingPolicyActionIdentity");
736
+ const previous = base.previousOperatingPolicyRef;
737
+ return canonical({
738
+ kind: "resonance_operating_policy_activation_v1",
739
+ mandateDigest,
740
+ operatingPolicyBase: {
741
+ ...base,
742
+ ledgerActionId: base.ledgerActionId.toLowerCase(),
743
+ acceptanceReceiptId: base.acceptanceReceiptId.toLowerCase(),
744
+ previousOperatingPolicyRef: previous && {
745
+ ...previous,
746
+ ledgerActionId: previous.ledgerActionId.toLowerCase(),
747
+ receiptId: previous.receiptId.toLowerCase()
748
+ }
749
+ }
750
+ });
751
+ }
752
+ var RESONANCE_OPERATING_POLICY_JSON_SCHEMA = operatingPolicy.schema;
753
+ var RESONANCE_OPERATING_POLICY_SELECTION_JSON_SCHEMA = operatingPolicySelection.schema;
754
+ var RESONANCE_OPERATING_POLICY_BASE_JSON_SCHEMA = operatingPolicyBase.schema;
755
+ var RESONANCE_OPERATING_POLICY_REF_JSON_SCHEMA = operatingPolicyRef.schema;
756
+ var RESONANCE_GOOGLE_CONTENT_UPDATE_SELECTION_JSON_SCHEMA = googleContentUpdateSelection.schema;
757
+ var RESONANCE_GOOGLE_CONTENT_UPDATE_JSON_SCHEMA = googleContentUpdate.schema;
758
+ var mandateScope = object2({ projectId: uuid, campaignId: uuid, preparedPlanId: uuid, reviewDigest: digest, accountBindingIds: list2(uuid, 100), sites: list2(site, 50, 1), budget, creativeRefs: list2(creative, 100, 1), audienceRuleRefs: list2(audience, 100), goal: objective, allowedOperations: mandateAllowedOperations, allowedTransformationRef: nullable2(resource), expiresAt: instant, websiteVisitFeed: optional2(websiteVisitFeed), providerReporting: optional2(providerReportingGrant), operatingPolicy: optional2(operatingPolicy) });
653
759
  function parseResonanceMandateScope(v, preparedPlan) {
654
760
  const r = mandateScope.read(v, "mandateScope");
655
761
  scoped(r, r.projectId, r.sites, "mandateScope");
@@ -657,17 +763,43 @@ function parseResonanceMandateScope(v, preparedPlan) {
657
763
  unique(r.websiteVisitFeed.channels.map((c) => c.channelId), "mandateScope.websiteVisitFeed.channels");
658
764
  for (const c of r.websiteVisitFeed.channels) unique(c.resourceRuleRefs.map((rule) => rule.id), "mandateScope.websiteVisitFeed.resourceRuleRefs");
659
765
  }
766
+ if (r.operatingPolicy) {
767
+ const p = "mandateScope.operatingPolicy";
768
+ if (Date.parse(r.expiresAt) <= Date.parse(r.budget.startAt) || Date.parse(r.expiresAt) > Date.parse(r.budget.endAt)) {
769
+ fail3(p, "operating policy remains inside the original mandate flight and expiry");
770
+ }
771
+ if (r.operatingPolicy.googleSearchContent.length && !r.allowedOperations.includes("update")) {
772
+ fail3(p, "Google content requires the update operation");
773
+ }
774
+ if (preparedPlan !== void 0) {
775
+ const plan = parseResonancePreparedPlan(preparedPlan);
776
+ if (r.projectId !== plan.projectId || r.campaignId !== plan.campaignId || r.preparedPlanId !== plan.id || r.reviewDigest !== plan.reviewDigest || canonical(r.goal) !== canonical(plan.definition.objective) || canonical(r.budget) !== canonical(plan.definition.budget)) fail3(p, "requires the exact original plan, review, goal and flight");
777
+ for (const entry of r.operatingPolicy.googleSearchContent) {
778
+ const channel2 = plan.definition.channels.find((item) => item.id.toLowerCase() === entry.channelId.toLowerCase());
779
+ if (channel2?.kind !== "google_search") return fail3(p, "requires an original Google Search channel");
780
+ const group = channel2.adGroups.find((item) => item.localKey === entry.adGroupLocalKey);
781
+ if (!r.sites.includes(channel2.site) || !r.accountBindingIds.includes(channel2.accountBindingId) || !group?.ads.some((ad) => ad.localKey === entry.adLocalKey) || entry.rsa && entry.rsa.creativeRef.site !== channel2.site) fail3(p, "requires the original account, site, ad group and ad");
782
+ }
783
+ }
784
+ }
660
785
  if (r.providerReporting) {
661
786
  const grant = r.providerReporting, p = "mandateScope.providerReporting";
662
- if (grant.projectId !== r.projectId) fail2(p + ".projectId", "must match the original mandate project");
663
- if (Date.parse(r.expiresAt) <= Date.parse(r.budget.startAt) || Date.parse(r.expiresAt) > Date.parse(r.budget.endAt)) fail2(p, "reporting remains inside the original mandate flight and expiry");
787
+ if (grant.projectId !== r.projectId) fail3(p + ".projectId", "must match the original mandate project");
788
+ const flightEnd = Date.parse(r.budget.endAt);
789
+ if (Date.parse(r.expiresAt) <= Date.parse(r.budget.startAt) || Date.parse(r.expiresAt) > flightEnd) fail3(p, "mandate expiry remains inside the original flight");
790
+ if (grant.reportingUntil !== void 0) {
791
+ const deadline = Date.parse(grant.reportingUntil);
792
+ if (deadline <= flightEnd || deadline > flightEnd + RESONANCE_PROVIDER_REPORTING_MAX_TAIL_DAYS * 864e5) {
793
+ fail3(p + ".reportingUntil", "must follow the original flight by no more than 92 elapsed days");
794
+ }
795
+ }
664
796
  if (preparedPlan !== void 0) {
665
797
  const plan = parseResonancePreparedPlan(preparedPlan);
666
- if (r.projectId !== plan.projectId || r.campaignId !== plan.campaignId || r.preparedPlanId !== plan.id || r.reviewDigest !== plan.reviewDigest || canonical(r.goal) !== canonical(plan.definition.objective) || canonical(r.budget) !== canonical(plan.definition.budget)) fail2(p, "requires the exact original plan, review, goal and flight");
667
- if (r.sites.some((site2) => !plan.definition.sites.includes(site2)) || r.accountBindingIds.some((id) => !plan.accounts.some((account) => account.id === id))) fail2(p, "mandate sites and accounts must stay inside the original plan");
798
+ if (r.projectId !== plan.projectId || r.campaignId !== plan.campaignId || r.preparedPlanId !== plan.id || r.reviewDigest !== plan.reviewDigest || canonical(r.goal) !== canonical(plan.definition.objective) || canonical(r.budget) !== canonical(plan.definition.budget)) fail3(p, "requires the exact original plan, review, goal and flight");
799
+ if (r.sites.some((site2) => !plan.definition.sites.includes(site2)) || r.accountBindingIds.some((id) => !plan.accounts.some((account) => account.id === id))) fail3(p, "mandate sites and accounts must stay inside the original plan");
668
800
  for (const id of grant.channelIds) {
669
801
  const channel2 = plan.definition.channels.find((c) => c.id.toLowerCase() === id.toLowerCase());
670
- if (!channel2 || !("provider" in channel2) || !r.sites.includes(channel2.site) || !r.accountBindingIds.includes(channel2.accountBindingId)) fail2(p + ".channelIds", "requires an explicit original paid channel inside mandate sites and accounts");
802
+ if (!channel2 || !("provider" in channel2) || !r.sites.includes(channel2.site) || !r.accountBindingIds.includes(channel2.accountBindingId)) fail3(p + ".channelIds", "requires an explicit original paid channel inside mandate sites and accounts");
671
803
  }
672
804
  }
673
805
  }
@@ -678,7 +810,7 @@ function resonanceWebsiteVisitEventTime(value, context) {
678
810
  const input = websiteVisitTimes.read(value, "websiteVisitTime");
679
811
  const actual = object2({ mandate: mandateScope, approvedAt: instant, now: instant }).read(context, "websiteVisitTime.context");
680
812
  const grant = parseResonanceMandateScope(actual.mandate);
681
- if (!grant.websiteVisitFeed) fail2("websiteVisitTime.context.mandate.websiteVisitFeed", "requires an explicit original feed selection");
813
+ if (!grant.websiteVisitFeed) fail3("websiteVisitTime.context.mandate.websiteVisitFeed", "requires an explicit original feed selection");
682
814
  const start = Math.max(Date.parse(grant.budget.startAt), Date.parse(actual.approvedAt));
683
815
  const end = Math.min(Date.parse(grant.budget.endAt), Date.parse(grant.expiresAt));
684
816
  return websiteVisitEventTime(input, start, end, Date.parse(actual.now));
@@ -686,8 +818,8 @@ function resonanceWebsiteVisitEventTime(value, context) {
686
818
  function websiteVisitEventTime(input, start, end, now) {
687
819
  const occurred = Date.parse(input.occurredAt), received = Date.parse(input.receivedAt);
688
820
  const policy = RESONANCE_WEBSITE_VISIT_PROFILE;
689
- if (received < occurred - policy.maxFutureSkewMs || received - occurred > policy.maxCaptureAgeMs || now < received || now < occurred - policy.maxFutureSkewMs || now - occurred > policy.maxDispatchAgeMs) fail2("websiteVisitTime", "outside the local original observation freshness profile");
690
- if (occurred < start || received < start || occurred >= end || received >= end || now >= end) fail2("websiteVisitTime", "outside the original approval and dispatch window");
821
+ if (received < occurred - policy.maxFutureSkewMs || received - occurred > policy.maxCaptureAgeMs || now < received || now < occurred - policy.maxFutureSkewMs || now - occurred > policy.maxDispatchAgeMs) fail3("websiteVisitTime", "outside the local original observation freshness profile");
822
+ if (occurred < start || received < start || occurred >= end || received >= end || now >= end) fail3("websiteVisitTime", "outside the original approval and dispatch window");
691
823
  return Math.floor(occurred / 1e3);
692
824
  }
693
825
  var RESONANCE_GOOGLE_SIGNAL_SEMANTICS = "qualified_at_observation_v1";
@@ -701,13 +833,13 @@ function googleConversionActionSemantics(input) {
701
833
  var googleSetupPolicyInput = object2({ source, countingUnit: objectiveCountingUnit, attributionWindowDays: integer2(1, 365) });
702
834
  function googleUploadClicksSetupSemantics(input) {
703
835
  const v = googleSetupPolicyInput.read(input, "googleSetupPolicy");
704
- if (v.source.kind !== "qualified_lead" || v.countingUnit !== "unique_qualified_contact") fail2("googleSetupPolicy", "unsupported_counting_policy");
705
- if (v.attributionWindowDays > 90) fail2("googleSetupPolicy.attributionWindowDays", "unsupported_attribution_window");
836
+ if (v.source.kind !== "qualified_lead" || v.countingUnit !== "unique_qualified_contact") fail3("googleSetupPolicy", "unsupported_counting_policy");
837
+ if (v.attributionWindowDays > 90) fail3("googleSetupPolicy.attributionWindowDays", "unsupported_attribution_window");
706
838
  return { ...googleConversionActionSemantics({ sourceKind: v.source.kind, counting: "one", clickWindowDays: v.attributionWindowDays }), category: RESONANCE_GOOGLE_SOURCE_CATEGORIES.qualified_lead, countingType: "ONE_PER_CLICK" };
707
839
  }
708
840
  var googleGoalChoiceFields = {
709
- externalId: text2(160, /^customers\/[0-9]+\/customConversionGoals\/[0-9]+$/),
710
- actionIds: list2(text2(160, /^customers\/[0-9]+\/conversionActions\/[0-9]+$/), 100, 1)
841
+ externalId: text3(160, /^customers\/[0-9]+\/customConversionGoals\/[0-9]+$/),
842
+ actionIds: list2(text3(160, /^customers\/[0-9]+\/conversionActions\/[0-9]+$/), 100, 1)
711
843
  };
712
844
  var googleDeclarationChoiceFields = {
713
845
  statement: literal2("DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING"),
@@ -723,10 +855,10 @@ var googleSetupSpec = object2({
723
855
  kind: literal2("google_upload_clicks_custom_goal_v1"),
724
856
  signalSemantics: googleSignalSemantics,
725
857
  goalLocalKey: literal2("setup:custom-goal"),
726
- requestedGoalName: text2(160),
858
+ requestedGoalName: text3(160),
727
859
  action: object2({
728
860
  localKey: literal2("setup:conversion-action"),
729
- requestedActionName: text2(160),
861
+ requestedActionName: text3(160),
730
862
  type: literal2("UPLOAD_CLICKS"),
731
863
  category: literal2(RESONANCE_GOOGLE_SOURCE_CATEGORIES.qualified_lead),
732
864
  countingType: literal2("ONE_PER_CLICK"),
@@ -741,20 +873,20 @@ var resonanceGoogleSetupDigestInput = (value) => canonical(parseResonanceGoogleU
741
873
  var googleSaveCommonFields = { schemaVersion: literal2(1), expectedCampaignRevision: integer2(1), expectedRevision: integer2(0), idempotencyKey: operationKey, signalSemantics: googleSignalSemantics, declaration: object2(googleDeclarationChoiceFields) };
742
874
  var googleSave = union2(
743
875
  object2({ ...googleSaveCommonFields, mode: literal2("existing"), nativeGoal: object2(googleGoalChoiceFields) }),
744
- object2({ ...googleSaveCommonFields, mode: literal2("admitted_setup"), setupIntent: object2({ requestedGoalName: text2(160), requestedActionName: text2(160) }) })
876
+ object2({ ...googleSaveCommonFields, mode: literal2("admitted_setup"), setupIntent: object2({ requestedGoalName: text3(160), requestedActionName: text3(160) }) })
745
877
  );
746
878
  function parseResonanceGoogleConfigurationSaveCommand(value) {
747
879
  const result = googleSave.read(value, "googleConfigurationSave");
748
880
  if (result.mode === "existing") normalizeGoogleGoal(result.nativeGoal, "googleConfigurationSave.nativeGoal");
749
881
  return result;
750
882
  }
751
- var googleGoalDraft = object2({ ...googleGoalChoiceFields, name: nullable2(text2(200, void 0, 0)), revision: nullable2(digest) });
752
- var googleGoalReviewed = object2({ ...googleGoalChoiceFields, name: text2(200, void 0, 0), revision: digest });
883
+ var googleGoalDraft = object2({ ...googleGoalChoiceFields, name: nullable2(text3(200, void 0, 0)), revision: nullable2(digest) });
884
+ var googleGoalReviewed = object2({ ...googleGoalChoiceFields, name: text3(200, void 0, 0), revision: digest });
753
885
  var googleDeclared = object2({
754
886
  ...googleDeclarationChoiceFields,
755
887
  creativeDigest: digest,
756
- locationIds: list2(text2(80), 100, 1),
757
- excludedLocationIds: list2(text2(80), 100),
888
+ locationIds: list2(text3(80), 100, 1),
889
+ excludedLocationIds: list2(text3(80), 100),
758
890
  declaredByActorId: uuid,
759
891
  declaredAt: instant,
760
892
  declaredForCampaignRevision: integer2(1)
@@ -777,7 +909,7 @@ var googleConfigurationFields = {
777
909
  var googleExistingChoiceFields = { mode: literal2("existing"), nativeGoal: googleGoalDraft };
778
910
  var googleSetupChoiceFields = { mode: literal2("admitted_setup"), setupSpec: googleSetupSpec, setupDigest: digest };
779
911
  function checkGoogleConfiguration(value, at) {
780
- if (value.source.projectId !== value.projectId || value.source.site !== value.site) fail2(at + ".source", "source scope mismatch");
912
+ if (value.source.projectId !== value.projectId || value.source.site !== value.site) fail3(at + ".source", "source scope mismatch");
781
913
  unique(value.declaration.locationIds, at + ".declaration.locationIds");
782
914
  unique(value.declaration.excludedLocationIds, at + ".declaration.excludedLocationIds");
783
915
  value.declaration.locationIds.sort();
@@ -787,28 +919,28 @@ function checkGoogleConfiguration(value, at) {
787
919
  normalizeGoogleGoal(value.nativeGoal, at + ".nativeGoal");
788
920
  return;
789
921
  }
790
- if (canonical({ type: value.setupSpec.action.type, category: value.setupSpec.action.category, countingType: value.setupSpec.action.countingType, clickThroughLookbackWindowDays: value.setupSpec.action.clickThroughLookbackWindowDays, primaryForGoal: value.setupSpec.action.primaryForGoal }) !== canonical(expected)) fail2(at + ".setupSpec.action", "canonical setup semantics mismatch");
922
+ if (canonical({ type: value.setupSpec.action.type, category: value.setupSpec.action.category, countingType: value.setupSpec.action.countingType, clickThroughLookbackWindowDays: value.setupSpec.action.clickThroughLookbackWindowDays, primaryForGoal: value.setupSpec.action.primaryForGoal }) !== canonical(expected)) fail3(at + ".setupSpec.action", "canonical setup semantics mismatch");
791
923
  }
792
924
  var googleSnapshotBase = union2(object2({ ...googleConfigurationFields, ...googleExistingChoiceFields }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields }));
793
- var googleConfigurationSnapshot = refine2(googleSnapshotBase, checkGoogleConfiguration);
794
- var googleConfigurationReview = refine2(union2(object2({ ...googleConfigurationFields, mode: literal2("existing"), nativeGoal: googleGoalReviewed }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields })), checkGoogleConfiguration);
925
+ var googleConfigurationSnapshot = refine3(googleSnapshotBase, checkGoogleConfiguration);
926
+ var googleConfigurationReview = refine3(union2(object2({ ...googleConfigurationFields, mode: literal2("existing"), nativeGoal: googleGoalReviewed }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields })), checkGoogleConfiguration);
795
927
  var parseResonanceGoogleConfigurationSnapshot = (value) => googleConfigurationSnapshot.read(value, "googleConfiguration");
796
928
  var parseResonanceGoogleConfigurationReview = (value) => googleConfigurationReview.read(value, "googleConfigurationReview");
797
929
  var { configurationRevision: _configurationRevisionField, ...googleViewContentFields } = googleConfigurationFields;
798
- var googleReadinessFields = { ready: bool, activationReadiness: choice2("blocked", "pending_setup", "requires_final_verification", "verified"), reasonCodes: list2(text2(200), 100) };
930
+ var googleReadinessFields = { ready: bool, activationReadiness: choice2("blocked", "pending_setup", "requires_final_verification", "verified"), reasonCodes: list2(text3(200), 100) };
799
931
  var googleViewFields = { ...googleViewContentFields, revision: integer2(1), ...googleReadinessFields };
800
932
  var googleViewBase = union2(object2({ ...googleViewFields, ...googleExistingChoiceFields }), object2({ ...googleViewFields, ...googleSetupChoiceFields }));
801
933
  function checkGoogleView(value, at) {
802
934
  checkGoogleConfiguration(value, at);
803
- if (!value.ready && value.activationReadiness !== "blocked") fail2(at + ".activationReadiness", "unready configuration must be blocked");
935
+ if (!value.ready && value.activationReadiness !== "blocked") fail3(at + ".activationReadiness", "unready configuration must be blocked");
804
936
  if (value.mode === "existing") {
805
- if (value.ready && (value.nativeGoal.name === null || value.nativeGoal.revision === null)) fail2(at + ".ready", "unavailable native evidence cannot be ready");
806
- if (value.ready && value.activationReadiness !== "requires_final_verification" && value.activationReadiness !== "verified") fail2(at + ".activationReadiness", "existing native setup needs current verification");
807
- } else if (value.ready && value.activationReadiness !== "pending_setup") fail2(at + ".activationReadiness", "reviewed setup intent is not native activation");
937
+ if (value.ready && (value.nativeGoal.name === null || value.nativeGoal.revision === null)) fail3(at + ".ready", "unavailable native evidence cannot be ready");
938
+ if (value.ready && value.activationReadiness !== "requires_final_verification" && value.activationReadiness !== "verified") fail3(at + ".activationReadiness", "existing native setup needs current verification");
939
+ } else if (value.ready && value.activationReadiness !== "pending_setup") fail3(at + ".activationReadiness", "reviewed setup intent is not native activation");
808
940
  }
809
- var googleConfigurationView = refine2(googleViewBase, checkGoogleView);
941
+ var googleConfigurationView = refine3(googleViewBase, checkGoogleView);
810
942
  var googleSaveResultFields = { operationId: uuid, replayed: bool, campaignRevision: integer2(1) };
811
- var googleConfigurationSaveResponse = refine2(union2(object2({ ...googleViewFields, ...googleExistingChoiceFields, ...googleSaveResultFields }), object2({ ...googleViewFields, ...googleSetupChoiceFields, ...googleSaveResultFields })), checkGoogleView);
943
+ var googleConfigurationSaveResponse = refine3(union2(object2({ ...googleViewFields, ...googleExistingChoiceFields, ...googleSaveResultFields }), object2({ ...googleViewFields, ...googleSetupChoiceFields, ...googleSaveResultFields })), checkGoogleView);
812
944
  var parseResonanceGoogleConfigurationView = (value) => googleConfigurationView.read(value, "googleConfigurationView");
813
945
  var parseResonanceGoogleConfigurationSaveResponse = (value) => googleConfigurationSaveResponse.read(value, "googleConfigurationSaveResponse");
814
946
  function projectResonanceGoogleConfiguration(value, readiness) {
@@ -821,7 +953,7 @@ function projectResonanceGoogleConfiguration(value, readiness) {
821
953
  function googleReadiness() {
822
954
  return object2(googleReadinessFields);
823
955
  }
824
- var googleConfigurationDigestValue = refine2(union2(object2({ ...googleConfigurationFields, ...googleExistingChoiceFields, configurationDigest: optional2(digest) }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields, configurationDigest: optional2(digest) })), checkGoogleConfiguration);
956
+ var googleConfigurationDigestValue = refine3(union2(object2({ ...googleConfigurationFields, ...googleExistingChoiceFields, configurationDigest: optional2(digest) }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields, configurationDigest: optional2(digest) })), checkGoogleConfiguration);
825
957
  function resonanceGoogleConfigurationDigestInput(value) {
826
958
  const { configurationDigest: _self, ...content } = googleConfigurationDigestValue.read(value, "googleConfigurationDigestInput");
827
959
  return canonical(content);
@@ -832,9 +964,9 @@ var RESONANCE_GOOGLE_CONFIGURATION_SNAPSHOT_JSON_SCHEMA = googleConfigurationSna
832
964
  var RESONANCE_GOOGLE_CONFIGURATION_REVIEW_JSON_SCHEMA = googleConfigurationReview.schema;
833
965
  var RESONANCE_GOOGLE_CONFIGURATION_VIEW_JSON_SCHEMA = googleConfigurationView.schema;
834
966
  var RESONANCE_GOOGLE_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA = googleConfigurationSaveResponse.schema;
835
- var preparedManifestRef = object2({ id: uuid, digest, providerVersion: text2(30), revision });
836
- var preview = object2({ channelId: uuid, site, accountBindingId: nullable2(uuid), accountName: text2(200), accountTimeZone: timeZone, destinationUrl: text2(4096), attributionMarker: optional2(object2({ parameter: literal2(RESONANCE_SOURCE_MARKER_PARAMETER), value: sourceMarker })), orderedCreatives: list2(creative, 50, 1), audienceRuleRefs: list2(audience, 100), allocation: nullable2(money), capabilityRevision: revision, snapshotDigest: digest, manifestRef: preparedManifestRef, conversionRevision: revision, policyRevision: revision, googleConfiguration: nullable2(googleConfigurationReview) });
837
- var prepared = object2({ schemaVersion: literal2(1), id: uuid, campaignId: uuid, projectId: uuid, expectedRevision: integer2(1), definitionDigest: digest, reviewDigest: digest, definition, resolvedEvidencePolicy: optimizationPolicy, resolvedQualificationRule: nullable2(resolvedQualificationRule), accounts: list2(capability, 100), channelPreviews: list2(preview, 100, 1), preparedAt: instant, expiresAt: instant, blockingReasons: list2(text2(200), 100) });
967
+ var preparedManifestRef = object2({ id: uuid, digest, providerVersion: text3(30), revision });
968
+ var preview = object2({ channelId: uuid, site, accountBindingId: nullable2(uuid), accountName: text3(200), accountTimeZone: timeZone, destinationUrl: text3(4096), attributionMarker: optional2(object2({ parameter: literal2(RESONANCE_SOURCE_MARKER_PARAMETER), value: sourceMarker })), orderedCreatives: list2(creative, 50, 1), audienceRuleRefs: list2(audience, 100), allocation: nullable2(money), capabilityRevision: revision, snapshotDigest: digest, manifestRef: preparedManifestRef, conversionRevision: revision, policyRevision: revision, googleConfiguration: nullable2(googleConfigurationReview) });
969
+ var prepared = object2({ schemaVersion: literal2(1), id: uuid, campaignId: uuid, projectId: uuid, expectedRevision: integer2(1), definitionDigest: digest, reviewDigest: digest, definition, resolvedEvidencePolicy: optimizationPolicy, resolvedQualificationRule: nullable2(resolvedQualificationRule), accounts: list2(capability, 100), channelPreviews: list2(preview, 100, 1), preparedAt: instant, expiresAt: instant, blockingReasons: list2(text3(200), 100) });
838
970
  function bookingTypesMatch(goalIds, witnessIds) {
839
971
  const norm = (ids) => ids === void 0 ? null : [...ids].map((id) => id.toLowerCase()).sort();
840
972
  return canonical(norm(goalIds)) === canonical(norm(witnessIds));
@@ -843,139 +975,167 @@ function parseResonancePreparedPlan(v) {
843
975
  const r = prepared.read(v, "preparedPlan");
844
976
  checkDefinition(r.definition);
845
977
  scoped(r, r.projectId, r.definition.sites, "preparedPlan");
846
- if (Date.parse(r.expiresAt) <= Date.parse(r.preparedAt)) fail2("preparedPlan.expiresAt", "must follow preparation");
978
+ if (Date.parse(r.expiresAt) <= Date.parse(r.preparedAt)) fail3("preparedPlan.expiresAt", "must follow preparation");
847
979
  const goal = r.definition.objective, witness = r.resolvedQualificationRule;
848
980
  if (goal.source.kind === "qualified_lead") {
849
- if (!goal.qualificationRule || !goal.qualificationRuleRef || !witness) fail2("preparedPlan.resolvedQualificationRule", "qualified-lead preparation requires actual configured native witness");
981
+ if (!goal.qualificationRule || !goal.qualificationRuleRef || !witness) fail3("preparedPlan.resolvedQualificationRule", "qualified-lead preparation requires actual configured native witness");
850
982
  const w = witness, selected = goal.qualificationRule;
851
- if (goal.countingUnit !== "unique_qualified_contact" || canonical(w.ref) !== canonical(goal.qualificationRuleRef) || w.eligibleFormIds.length !== 1 || w.eligibleFormIds[0] !== goal.source.id || !bookingTypesMatch(goal.eligibleBookingTypeIds, w.eligibleBookingTypeIds) || w.cohort.maturityDelaySeconds !== goal.maturityDelaySeconds) fail2("preparedPlan.resolvedQualificationRule", "source, counting unit, reference or maturity mismatch");
852
- for (const key of ["schemaVersion", "semantics", "positiveStageKeys", "finalNegativeStageKeys", "pendingStageKeys", "existingContactPolicy"]) if (canonical(w[key]) !== canonical(selected[key])) fail2("preparedPlan.resolvedQualificationRule", "selected qualification snapshot mismatch");
853
- } else if (witness !== null) fail2("preparedPlan.resolvedQualificationRule", "nonqualified objectives require explicit null");
854
- if (canonical(r.resolvedEvidencePolicy) !== canonical(r.definition.optimization.policy)) fail2("preparedPlan.resolvedEvidencePolicy", "policy snapshot mismatch");
983
+ if (goal.countingUnit !== "unique_qualified_contact" || canonical(w.ref) !== canonical(goal.qualificationRuleRef) || w.eligibleFormIds.length !== 1 || w.eligibleFormIds[0] !== goal.source.id || !bookingTypesMatch(goal.eligibleBookingTypeIds, w.eligibleBookingTypeIds) || w.cohort.maturityDelaySeconds !== goal.maturityDelaySeconds) fail3("preparedPlan.resolvedQualificationRule", "source, counting unit, reference or maturity mismatch");
984
+ for (const key of ["schemaVersion", "semantics", "positiveStageKeys", "finalNegativeStageKeys", "pendingStageKeys", "existingContactPolicy"]) if (canonical(w[key]) !== canonical(selected[key])) fail3("preparedPlan.resolvedQualificationRule", "selected qualification snapshot mismatch");
985
+ } else if (witness !== null) fail3("preparedPlan.resolvedQualificationRule", "nonqualified objectives require explicit null");
986
+ if (canonical(r.resolvedEvidencePolicy) !== canonical(r.definition.optimization.policy)) fail3("preparedPlan.resolvedEvidencePolicy", "policy snapshot mismatch");
855
987
  parseResonanceOptimizationPolicy(r.resolvedEvidencePolicy);
856
- if (r.resolvedEvidencePolicy.algorithm === "finite_meta_candidates_v1" && Date.parse(r.resolvedEvidencePolicy.expiresAt) <= Date.parse(r.preparedAt)) fail2("preparedPlan.resolvedEvidencePolicy.expiresAt", "finite policy expired before preparation");
988
+ if (r.resolvedEvidencePolicy.algorithm === "finite_meta_candidates_v1" && Date.parse(r.resolvedEvidencePolicy.expiresAt) <= Date.parse(r.preparedAt)) fail3("preparedPlan.resolvedEvidencePolicy.expiresAt", "finite policy expired before preparation");
857
989
  unique(r.accounts.map((a) => a.id), "preparedPlan.accounts");
858
990
  unique(r.channelPreviews.map((p) => p.channelId), "preparedPlan.channelPreviews");
859
- if (r.channelPreviews.length !== r.definition.channels.length) fail2("preparedPlan.channelPreviews", "must cover every channel");
991
+ if (r.channelPreviews.length !== r.definition.channels.length) fail3("preparedPlan.channelPreviews", "must cover every channel");
860
992
  for (const a of r.accounts) parseResonanceAccountCapability(a);
861
993
  for (const p of r.channelPreviews) {
862
- const c = r.definition.channels.find((c2) => c2.id === p.channelId) ?? fail2("preparedPlan.channelPreviews", "unknown channel");
863
- if (c.site !== p.site) fail2("preparedPlan.channelPreviews", "channel scope mismatch");
994
+ const c = r.definition.channels.find((c2) => c2.id === p.channelId) ?? fail3("preparedPlan.channelPreviews", "unknown channel");
995
+ if (c.site !== p.site) fail3("preparedPlan.channelPreviews", "channel scope mismatch");
864
996
  const google = p.googleConfiguration;
865
997
  if (c.kind === "google_search") {
866
- if (!google) fail2("preparedPlan.channelPreviews.googleConfiguration", "Google requires the actual reviewed configuration");
998
+ if (!google) fail3("preparedPlan.channelPreviews.googleConfiguration", "Google requires the actual reviewed configuration");
867
999
  const g = google;
868
- if (g.projectId !== r.projectId || g.campaignId !== r.campaignId || g.channelId !== c.id || g.site !== c.site || g.accountBindingId !== c.accountBindingId) fail2("preparedPlan.channelPreviews.googleConfiguration", "configuration scope mismatch");
869
- if (canonical(g.source) !== canonical(goal.source) || g.measurementRevision !== goal.measurementRevision || g.countingUnit !== goal.countingUnit || g.attributionWindowDays !== goal.attributionWindowDays) fail2("preparedPlan.channelPreviews.googleConfiguration.source", "objective measurement mismatch");
1000
+ if (g.projectId !== r.projectId || g.campaignId !== r.campaignId || g.channelId !== c.id || g.site !== c.site || g.accountBindingId !== c.accountBindingId) fail3("preparedPlan.channelPreviews.googleConfiguration", "configuration scope mismatch");
1001
+ if (canonical(g.source) !== canonical(goal.source) || g.measurementRevision !== goal.measurementRevision || g.countingUnit !== goal.countingUnit || g.attributionWindowDays !== goal.attributionWindowDays) fail3("preparedPlan.channelPreviews.googleConfiguration.source", "objective measurement mismatch");
870
1002
  unique(c.locationIds, "preparedPlan.channelPreviews.googleConfiguration.locationIds");
871
1003
  unique(c.excludedLocationIds, "preparedPlan.channelPreviews.googleConfiguration.excludedLocationIds");
872
- if (canonical(g.declaration.locationIds) !== canonical([...c.locationIds].sort()) || canonical(g.declaration.excludedLocationIds) !== canonical([...c.excludedLocationIds].sort())) fail2("preparedPlan.channelPreviews.googleConfiguration.declaration", "region scope mismatch");
873
- if (g.declaration.declaredForCampaignRevision > r.expectedRevision || Date.parse(g.declaration.declaredAt) > Date.parse(r.preparedAt)) fail2("preparedPlan.channelPreviews.googleConfiguration.declaration", "declaration follows preparation scope");
874
- } else if (google !== null) fail2("preparedPlan.channelPreviews.googleConfiguration", "non-Google channels require explicit null");
1004
+ if (canonical(g.declaration.locationIds) !== canonical([...c.locationIds].sort()) || canonical(g.declaration.excludedLocationIds) !== canonical([...c.excludedLocationIds].sort())) fail3("preparedPlan.channelPreviews.googleConfiguration.declaration", "region scope mismatch");
1005
+ if (g.declaration.declaredForCampaignRevision > r.expectedRevision || Date.parse(g.declaration.declaredAt) > Date.parse(r.preparedAt)) fail3("preparedPlan.channelPreviews.googleConfiguration.declaration", "declaration follows preparation scope");
1006
+ } else if (google !== null) fail3("preparedPlan.channelPreviews.googleConfiguration", "non-Google channels require explicit null");
875
1007
  const d = r.definition.destinations.find((d2) => d2.id === c.destinationId);
876
1008
  const expectedUrl = p.attributionMarker ? new URL(`https://${p.site}${d.path}`) : null;
877
1009
  if (expectedUrl && p.attributionMarker) expectedUrl.searchParams.set(RESONANCE_SOURCE_MARKER_PARAMETER, p.attributionMarker.value);
878
- if (!sameSite(hostFromUrl(p.destinationUrl), p.site) || p.destinationUrl !== (expectedUrl?.toString() ?? `https://${p.site}${d.path}`)) fail2("preparedPlan.channelPreviews.destinationUrl", "must be exact HTTPS destination and reviewed source marker on the owned site");
879
- if (canonical(p.orderedCreatives) !== canonical(c.creativeIds.map((id) => r.definition.creativeRefs.find((x) => x.id === id)))) fail2("preparedPlan.channelPreviews.orderedCreatives", "creative order/content mismatch");
1010
+ if (!sameSite(hostFromUrl(p.destinationUrl), p.site) || p.destinationUrl !== (expectedUrl?.toString() ?? `https://${p.site}${d.path}`)) fail3("preparedPlan.channelPreviews.destinationUrl", "must be exact HTTPS destination and reviewed source marker on the owned site");
1011
+ if (canonical(p.orderedCreatives) !== canonical(c.creativeIds.map((id) => r.definition.creativeRefs.find((x) => x.id === id)))) fail3("preparedPlan.channelPreviews.orderedCreatives", "creative order/content mismatch");
880
1012
  if ("provider" in c) {
881
- if (p.accountBindingId !== c.accountBindingId || !r.accounts.some((a) => a.id === c.accountBindingId)) fail2("preparedPlan.channelPreviews.accountBindingId", "account binding mismatch");
882
- if (canonical(p.allocation) !== canonical(c.allocation)) fail2("preparedPlan.channelPreviews.allocation", "allocation mismatch");
883
- } else if (p.accountBindingId !== null || p.allocation !== null) fail2("preparedPlan.channelPreviews", "nonpaid child cannot select paid account/allocation");
1013
+ if (p.accountBindingId !== c.accountBindingId || !r.accounts.some((a) => a.id === c.accountBindingId)) fail3("preparedPlan.channelPreviews.accountBindingId", "account binding mismatch");
1014
+ if (canonical(p.allocation) !== canonical(c.allocation)) fail3("preparedPlan.channelPreviews.allocation", "allocation mismatch");
1015
+ } else if (p.accountBindingId !== null || p.allocation !== null) fail3("preparedPlan.channelPreviews", "nonpaid child cannot select paid account/allocation");
884
1016
  }
885
1017
  return r;
886
1018
  }
887
1019
  var commandBase = { schemaVersion: literal2(1), campaignId: uuid, expectedRevision: integer2(1), idempotencyKey: operationKey, channelIds: list2(uuid, 100) };
888
1020
  var effect = object2({ ...commandBase, operation: choice2("launch", "update", "resume"), preparedPlanId: uuid, reviewDigest: digest, mandateRef, expectedRemoteSnapshots: list2(object2({ channelId: uuid, digest }), 100) });
1021
+ var googleContentEffect = refine3(object2({
1022
+ ...commandBase,
1023
+ operation: literal2("update"),
1024
+ preparedPlanId: uuid,
1025
+ reviewDigest: digest,
1026
+ mandateRef,
1027
+ channelIds: list2(uuid, 1, 1),
1028
+ expectedRemoteSnapshots: list2(object2({ channelId: uuid, digest }), 1, 1),
1029
+ googleContentUpdate
1030
+ }), (command2, p) => {
1031
+ const update2 = command2.googleContentUpdate, remote = command2.expectedRemoteSnapshots[0];
1032
+ if (command2.channelIds[0] !== update2.channelId || remote.channelId !== update2.channelId || remote.digest !== update2.beforeDigest) {
1033
+ fail3(p + ".googleContentUpdate", "requires the same single channel and before snapshot");
1034
+ }
1035
+ });
889
1036
  var optimize = object2({ ...commandBase, operation: literal2("optimize"), preparedPlanId: uuid, reviewDigest: digest, mandateRef, decisionRef: object2({ id: uuid, revision, evidenceDigest: digest }), expectedRemoteSnapshots: list2(object2({ channelId: uuid, digest }), 100) });
890
1037
  var safety = object2({ ...commandBase, operation: choice2("pause", "finish", "reconcile") });
891
1038
  var deliverConversion = object2({ ...commandBase, operation: literal2("deliver_conversion"), channelIds: list2(uuid, 1, 1), preparedPlanId: uuid, reviewDigest: digest, mandateRef, conversionId: uuid });
892
1039
  var deliverWebsiteVisit = object2({ ...commandBase, operation: literal2("deliver_website_visit"), channelIds: list2(uuid, 1, 1), preparedPlanId: uuid, reviewDigest: digest, mandateRef, occurrenceId: uuid });
893
- var command = union2(effect, optimize, safety, deliverConversion, deliverWebsiteVisit);
1040
+ var command = union2(effect, googleContentEffect, optimize, safety, deliverConversion, deliverWebsiteVisit);
894
1041
  function parseResonanceCommand(v, context) {
895
1042
  const r = command.read(v, "command");
896
1043
  unique(r.channelIds, "command.channelIds");
897
- if ("mandateRef" in r && (r.mandateRef.campaignId !== r.campaignId || r.mandateRef.preparedPlanId !== r.preparedPlanId || r.mandateRef.reviewDigest !== r.reviewDigest)) fail2("command.mandateRef", "snapshot mismatch");
1044
+ if ("mandateRef" in r && (r.mandateRef.campaignId !== r.campaignId || r.mandateRef.preparedPlanId !== r.preparedPlanId || r.mandateRef.reviewDigest !== r.reviewDigest)) fail3("command.mandateRef", "snapshot mismatch");
1045
+ if ("googleContentUpdate" in r && context) {
1046
+ const p = "command.googleContentUpdate", update2 = r.googleContentUpdate;
1047
+ const plan = parseResonancePreparedPlan(context.preparedPlan);
1048
+ const grant = parseResonanceMandateScope(context.mandate, plan);
1049
+ const now = Date.parse(instant.read(context.now, "command.context.now"));
1050
+ if (r.expectedRevision !== plan.expectedRevision || r.campaignId !== plan.campaignId || r.preparedPlanId !== plan.id || r.reviewDigest !== plan.reviewDigest || grant.projectId !== plan.projectId || grant.campaignId !== plan.campaignId || grant.preparedPlanId !== plan.id || grant.reviewDigest !== plan.reviewDigest || !grant.allowedOperations.includes("update") || canonical(grant.goal) !== canonical(plan.definition.objective) || canonical(grant.budget) !== canonical(plan.definition.budget) || now < Date.parse(grant.budget.startAt) || now >= Date.parse(grant.budget.endAt) || now >= Date.parse(grant.expiresAt)) {
1051
+ fail3(p, "requires the current original Google mandate and flight");
1052
+ }
1053
+ const channel2 = plan.definition.channels.find((item) => item.id === update2.channelId);
1054
+ if (channel2?.kind !== "google_search" || !grant.sites.includes(channel2.site) || !grant.accountBindingIds.includes(channel2.accountBindingId) || !channel2.adGroups.some((group) => group.localKey === update2.adGroupLocalKey && group.ads.some((ad) => ad.localKey === update2.adLocalKey))) {
1055
+ fail3(p, "requires an original Google Search group and ad in scope");
1056
+ } else if (update2.rsa) scoped(update2.rsa, plan.projectId, [channel2.site], p + ".rsa");
1057
+ }
898
1058
  if ((r.operation === "deliver_conversion" || r.operation === "deliver_website_visit") && context) {
899
1059
  const plan = parseResonancePreparedPlan(context.preparedPlan), grant = parseResonanceMandateScope(context.mandate);
900
1060
  const now = Date.parse(instant.read(context.now, "command.context.now"));
901
- if (r.expectedRevision !== plan.expectedRevision) fail2("command.expectedRevision", "requires the original prepared definition revision");
902
- if (r.campaignId !== plan.campaignId || r.preparedPlanId !== plan.id || r.reviewDigest !== plan.reviewDigest || grant.projectId !== plan.projectId || grant.campaignId !== plan.campaignId || grant.preparedPlanId !== plan.id || grant.reviewDigest !== plan.reviewDigest) fail2("command.context", "requires the exact original plan and mandate scope");
903
- if (canonical(grant.goal) !== canonical(plan.definition.objective) || canonical(grant.budget) !== canonical(plan.definition.budget)) fail2("command.context.mandate", "original goal or budget mismatch");
1061
+ if (r.expectedRevision !== plan.expectedRevision) fail3("command.expectedRevision", "requires the original prepared definition revision");
1062
+ if (r.campaignId !== plan.campaignId || r.preparedPlanId !== plan.id || r.reviewDigest !== plan.reviewDigest || grant.projectId !== plan.projectId || grant.campaignId !== plan.campaignId || grant.preparedPlanId !== plan.id || grant.reviewDigest !== plan.reviewDigest) fail3("command.context", "requires the exact original plan and mandate scope");
1063
+ if (canonical(grant.goal) !== canonical(plan.definition.objective) || canonical(grant.budget) !== canonical(plan.definition.budget)) fail3("command.context.mandate", "original goal or budget mismatch");
904
1064
  const channel2 = plan.definition.channels.find((c) => c.id === r.channelIds[0]);
905
1065
  if (r.operation === "deliver_conversion") {
906
- if (!grant.allowedOperations.includes("deliver_conversion")) fail2("command.context.mandate.allowedOperations", "requires the explicit original delivery grant");
907
- if (!channel2 || channel2.kind !== "google_search") fail2("command.channelIds", "requires one original Google channel");
1066
+ if (!grant.allowedOperations.includes("deliver_conversion")) fail3("command.context.mandate.allowedOperations", "requires the explicit original delivery grant");
1067
+ if (!channel2 || channel2.kind !== "google_search") fail3("command.channelIds", "requires one original Google channel");
908
1068
  const c = channel2;
909
1069
  const goal = plan.definition.objective, witness = plan.resolvedQualificationRule;
910
- if (goal.source.kind !== "qualified_lead" || goal.countingUnit !== "unique_qualified_contact" || !witness || witness.eligibleFormIds.length !== 1 || witness.eligibleFormIds[0] !== goal.source.id || !bookingTypesMatch(goal.eligibleBookingTypeIds, witness.eligibleBookingTypeIds) || goal.source.site !== c.site) fail2("command.context.goal", "requires the original single managed-form qualified source");
1070
+ if (goal.source.kind !== "qualified_lead" || goal.countingUnit !== "unique_qualified_contact" || !witness || witness.eligibleFormIds.length !== 1 || witness.eligibleFormIds[0] !== goal.source.id || !bookingTypesMatch(goal.eligibleBookingTypeIds, witness.eligibleBookingTypeIds) || goal.source.site !== c.site) fail3("command.context.goal", "requires the original single managed-form qualified source");
911
1071
  const account = plan.accounts.find((a) => a.id === c.accountBindingId);
912
- if (!account || account.provider !== "google_ads" || !grant.accountBindingIds.includes(c.accountBindingId) || !grant.sites.includes(c.site)) fail2("command.context.account", "requires the original granted Google account and site");
1072
+ if (!account || account.provider !== "google_ads" || !grant.accountBindingIds.includes(c.accountBindingId) || !grant.sites.includes(c.site)) fail3("command.context.account", "requires the original granted Google account and site");
913
1073
  const configuration = plan.channelPreviews.find((p) => p.channelId === c.id)?.googleConfiguration;
914
- if (!configuration || configuration.signalSemantics !== RESONANCE_GOOGLE_SIGNAL_SEMANTICS) fail2("command.context.googleConfiguration", "requires the reviewed qualified-at-observation profile");
1074
+ if (!configuration || configuration.signalSemantics !== RESONANCE_GOOGLE_SIGNAL_SEMANTICS) fail3("command.context.googleConfiguration", "requires the reviewed qualified-at-observation profile");
915
1075
  const g = configuration;
916
- if (g.mode === "existing" && (g.nativeGoal.actionIds.length !== 1 || g.nativeGoal.actionIds[0].split("/")[1] !== account.externalAccountId || g.nativeGoal.externalId.split("/")[1] !== account.externalAccountId)) fail2("command.context.googleConfiguration.nativeGoal", "requires one action owned by the original account; cross-account delivery is unsupported");
917
- if (g.mode === "admitted_setup" && (g.setupSpec.goalStrategy !== "exclusive_custom_goal_v1" || g.setupSpec.goalActionKey !== g.setupSpec.action.localKey)) fail2("command.context.googleConfiguration.setupSpec", "requires the original single-action setup intent");
1076
+ if (g.mode === "existing" && (g.nativeGoal.actionIds.length !== 1 || g.nativeGoal.actionIds[0].split("/")[1] !== account.externalAccountId || g.nativeGoal.externalId.split("/")[1] !== account.externalAccountId)) fail3("command.context.googleConfiguration.nativeGoal", "requires one action owned by the original account; cross-account delivery is unsupported");
1077
+ if (g.mode === "admitted_setup" && (g.setupSpec.goalStrategy !== "exclusive_custom_goal_v1" || g.setupSpec.goalActionKey !== g.setupSpec.action.localKey)) fail3("command.context.googleConfiguration.setupSpec", "requires the original single-action setup intent");
918
1078
  } else {
919
1079
  const selected = grant.websiteVisitFeed?.channels.find((c2) => c2.channelId === r.channelIds[0]);
920
- if (!selected) fail2("command.context.mandate.websiteVisitFeed", "requires the explicit original feed channel");
921
- if (!channel2 || channel2.kind !== "meta_retargeting") fail2("command.channelIds", "requires one original Meta channel");
1080
+ if (!selected) fail3("command.context.mandate.websiteVisitFeed", "requires the explicit original feed channel");
1081
+ if (!channel2 || channel2.kind !== "meta_retargeting") fail3("command.channelIds", "requires one original Meta channel");
922
1082
  const c = channel2;
923
1083
  const account = plan.accounts.find((a) => a.id === c.accountBindingId);
924
- if (!account || account.provider !== "meta_ads" || !grant.accountBindingIds.includes(c.accountBindingId) || !grant.sites.includes(c.site)) fail2("command.context.account", "requires the original granted Meta account and site");
925
- if (c.audienceRuleRefs.some((rule) => !grant.audienceRuleRefs.some((original) => canonical(original) === canonical(rule)))) fail2("command.context.audienceRuleRefs", "requires the original granted audience rules");
1084
+ if (!account || account.provider !== "meta_ads" || !grant.accountBindingIds.includes(c.accountBindingId) || !grant.sites.includes(c.site)) fail3("command.context.account", "requires the original granted Meta account and site");
1085
+ if (c.audienceRuleRefs.some((rule) => !grant.audienceRuleRefs.some((original) => canonical(original) === canonical(rule)))) fail3("command.context.audienceRuleRefs", "requires the original granted audience rules");
926
1086
  }
927
- if (now < Date.parse(grant.budget.startAt) || now >= Date.parse(grant.budget.endAt) || now >= Date.parse(grant.expiresAt)) fail2("command.context.now", "outside the original mandate and budget dispatch window");
1087
+ if (now < Date.parse(grant.budget.startAt) || now >= Date.parse(grant.budget.endAt) || now >= Date.parse(grant.expiresAt)) fail3("command.context.now", "outside the original mandate and budget dispatch window");
928
1088
  }
929
1089
  return r;
930
1090
  }
931
1091
  var RESONANCE_COMMAND_JSON_SCHEMA = command.schema;
932
- var step = object2({ id: uuid, channelId: uuid, state: choice2("planned", "admitted", "confirmed", "failed", "uncertain"), providerRequestId: nullable2(text2(200)), admission: choice2("not_dispatched", "accepted", "rejected", "unknown"), configuredStatus: nullable2(text2(80)), effectiveStatus: nullable2(text2(80)), reviewStatus: nullable2(text2(80)), retryAfter: nullable2(instant), errorSubcode: nullable2(text2(80)), errorFieldPath: nullable2(text2(200)), resourceRefs: list2(object2({ type: text2(80), externalId: text2(200) }), 100), evidenceDigest: nullable2(digest), errorCode: nullable2(text2(80)), observedAt: nullable2(instant) });
933
- var receipt = object2({ schemaVersion: literal2(1), id: uuid, projectId: uuid, campaignId: uuid, preparedPlanId: nullable2(uuid), effectKey: text2(200), requestDigest: digest, ledgerActionId: uuid, actorId: text2(160), state: choice2("pending", "applying", "accepted", "failed", "needs_reconciliation"), steps: list2(step, 1e3), reservedExposure: money, unreconciledExposure: money, providerSemanticsNotice: list2(text2(500), 30), nextActions: list2(choice2("read", "reconcile", "retry_same_operation", "pause", "escalate"), 5) });
1092
+ var step = object2({ id: uuid, channelId: uuid, state: choice2("planned", "admitted", "confirmed", "failed", "uncertain"), providerRequestId: nullable2(text3(200)), admission: choice2("not_dispatched", "accepted", "rejected", "unknown"), configuredStatus: nullable2(text3(80)), effectiveStatus: nullable2(text3(80)), reviewStatus: nullable2(text3(80)), retryAfter: nullable2(instant), errorSubcode: nullable2(text3(80)), errorFieldPath: nullable2(text3(200)), resourceRefs: list2(object2({ type: text3(80), externalId: text3(200) }), 100), evidenceDigest: nullable2(digest), errorCode: nullable2(text3(80)), observedAt: nullable2(instant) });
1093
+ var receipt = object2({ schemaVersion: literal2(1), id: uuid, projectId: uuid, campaignId: uuid, preparedPlanId: nullable2(uuid), effectKey: text3(200), requestDigest: digest, ledgerActionId: uuid, actorId: text3(160), state: choice2("pending", "applying", "accepted", "failed", "needs_reconciliation"), steps: list2(step, 1e3), reservedExposure: money, unreconciledExposure: money, providerSemanticsNotice: list2(text3(500), 30), nextActions: list2(choice2("read", "reconcile", "retry_same_operation", "pause", "escalate"), 5) });
934
1094
  function parseResonanceReceipt(v) {
935
1095
  const r = receipt.read(v, "receipt");
936
- if (r.reservedExposure.currency !== r.unreconciledExposure.currency) fail2("receipt", "currency mismatch");
1096
+ if (r.reservedExposure.currency !== r.unreconciledExposure.currency) fail3("receipt", "currency mismatch");
937
1097
  const uncertain = r.steps.some((s) => s.state === "uncertain" || s.admission === "unknown");
938
- if (uncertain && r.state !== "needs_reconciliation") fail2("receipt.state", "uncertain child requires reconciliation state");
939
- if ((uncertain || r.state === "needs_reconciliation") && r.nextActions.includes("retry_same_operation")) fail2("receipt.nextActions", "unknown admission must reconcile before retry");
1098
+ if (uncertain && r.state !== "needs_reconciliation") fail3("receipt.state", "uncertain child requires reconciliation state");
1099
+ if ((uncertain || r.state === "needs_reconciliation") && r.nextActions.includes("retry_same_operation")) fail3("receipt.nextActions", "unknown admission must reconcile before retry");
940
1100
  return r;
941
1101
  }
942
1102
  var lifecycle = choice2("not_materialized", "pending", "partially_live", "live", "pausing", "paused", "finished", "needs_attention", "unknown");
943
- var view = object2({ id: uuid, projectId: uuid, managementMode: choice2("tracking_only", "managed"), revision: integer2(0), definition: nullable2(draft), acceptedPlanId: nullable2(uuid), desiredLifecycle: choice2("draft", "running", "paused", "finished"), effectiveLifecycle: lifecycle, blockingReasons: list2(text2(200), 100), activeOperation: nullable2(receipt), unresolvedExposure: nullable2(money) });
1103
+ var view = object2({ id: uuid, projectId: uuid, managementMode: choice2("tracking_only", "managed"), revision: integer2(0), definition: nullable2(draft), acceptedPlanId: nullable2(uuid), desiredLifecycle: choice2("draft", "running", "paused", "finished"), effectiveLifecycle: lifecycle, blockingReasons: list2(text3(200), 100), activeOperation: nullable2(receipt), unresolvedExposure: nullable2(money) });
944
1104
  function parseResonanceCampaignView(v) {
945
1105
  const r = view.read(v, "campaignView");
946
- if (r.managementMode === "managed" && r.revision < 1) fail2("campaignView.revision", "managed campaigns require revision >=1");
1106
+ if (r.managementMode === "managed" && r.revision < 1) fail3("campaignView.revision", "managed campaigns require revision >=1");
947
1107
  if (r.definition) parseResonanceCampaignDraft(r.definition);
948
1108
  if (r.activeOperation) parseResonanceReceipt(r.activeOperation);
949
- if (r.definition && r.definition.projectId !== r.projectId) fail2("campaignView.definition", "cross-project reference");
950
- if (r.activeOperation && (r.activeOperation.projectId !== r.projectId || r.activeOperation.campaignId !== r.id)) fail2("campaignView.activeOperation", "scope mismatch");
1109
+ if (r.definition && r.definition.projectId !== r.projectId) fail3("campaignView.definition", "cross-project reference");
1110
+ if (r.activeOperation && (r.activeOperation.projectId !== r.projectId || r.activeOperation.campaignId !== r.id)) fail3("campaignView.activeOperation", "scope mismatch");
951
1111
  return r;
952
1112
  }
953
- var metricValue = union2(object2({ kind: literal2("count"), count: decimal }), object2({ kind: literal2("money"), money }), object2({ kind: literal2("ratio"), numerator: decimal, denominator: refine2(decimal, (v, p) => {
954
- if (v === "0") fail2(p, "zero denominator");
1113
+ var metricValue = union2(object2({ kind: literal2("count"), count: decimal }), object2({ kind: literal2("money"), money }), object2({ kind: literal2("ratio"), numerator: decimal, denominator: refine3(decimal, (v, p) => {
1114
+ if (v === "0") fail3(p, "zero denominator");
955
1115
  }) }));
956
- var metricBase = { ...scope, campaignId: uuid, name: choice2("impressions", "clicks", "spend", "accepted_goals", "qualified_goals", "revenue", "conversion_rate", "reach", "results"), source: choice2("first_party", "provider", "experiment"), sourceRef: revision, goalRevision: nullable2(revision), countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order", "provider_aggregate", "provider_unique_reach"), windowStart: instant, windowEnd: instant, timeZone, attributionModel: nullable2(text2(100)), asOf: instant, dataThrough: nullable2(instant), maturityDelaySeconds: integer2(0), coverageBasisPoints: nullable2(integer2(0, 1e4)), eligibleExposures: nullable2(decimal), matureOutcomes: nullable2(decimal), native: nullable2(object2({ unit: text2(80), amount: decimal, currency: nullable2(currency), unitExponent: integer2(0, 9), providerVersion: text2(30) })) };
957
- var metric = union2(object2({ ...metricBase, state: literal2("observed"), value: metricValue }), object2({ ...metricBase, state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text2(80) }));
1116
+ var metricBase = { ...scope, campaignId: uuid, name: choice2("impressions", "clicks", "spend", "accepted_goals", "qualified_goals", "revenue", "conversion_rate", "reach", "results"), source: choice2("first_party", "provider", "experiment"), sourceRef: revision, goalRevision: nullable2(revision), countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order", "provider_aggregate", "provider_unique_reach"), windowStart: instant, windowEnd: instant, timeZone, attributionModel: nullable2(text3(100)), asOf: instant, dataThrough: nullable2(instant), maturityDelaySeconds: integer2(0), coverageBasisPoints: nullable2(integer2(0, 1e4)), eligibleExposures: nullable2(decimal), matureOutcomes: nullable2(decimal), native: nullable2(object2({ unit: text3(80), amount: decimal, currency: nullable2(currency), unitExponent: integer2(0, 9), providerVersion: text3(30) })) };
1117
+ var metric = union2(object2({ ...metricBase, state: literal2("observed"), value: metricValue }), object2({ ...metricBase, state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text3(80) }));
958
1118
  function parseResonanceMetricObservation(v) {
959
1119
  const r = metric.read(v, "metric");
960
- if (["accepted_goals", "qualified_goals", "revenue", "conversion_rate"].includes(r.name) && r.goalRevision === null) fail2("metric.goalRevision", "goal measurement requires explicit revision");
961
- if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart)) fail2("metric.window", "invalid window");
962
- if (r.name === "reach" !== (r.countingUnit === "provider_unique_reach")) fail2("metric.countingUnit", "reach, and only reach, counts unique provider reach");
1120
+ if (["accepted_goals", "qualified_goals", "revenue", "conversion_rate"].includes(r.name) && r.goalRevision === null) fail3("metric.goalRevision", "goal measurement requires explicit revision");
1121
+ if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart)) fail3("metric.window", "invalid window");
1122
+ if (r.name === "reach" !== (r.countingUnit === "provider_unique_reach")) fail3("metric.countingUnit", "reach, and only reach, counts unique provider reach");
963
1123
  if (r.state === "observed") {
964
1124
  const expected = r.name === "spend" || r.name === "revenue" ? "money" : r.name === "conversion_rate" ? "ratio" : "count";
965
- if (r.value.kind !== expected) fail2("metric.value", "metric unit mismatch");
1125
+ if (r.value.kind !== expected) fail3("metric.value", "metric unit mismatch");
966
1126
  }
967
1127
  return r;
968
1128
  }
969
1129
  var purpose = choice2("analytics_storage", "ad_storage", "ad_user_data", "ad_personalization");
970
- var consent = object2({ ...scope, receiptId: uuid, visitorNamespace: text2(160), configRevision: revision, policyRevision: revision, consentRevision: integer2(1), state: choice2("unknown", "granted", "denied", "withdrawn"), purpose, observedAt: instant, evidenceRef: revision });
1130
+ var consent = object2({ ...scope, receiptId: uuid, visitorNamespace: text3(160), configRevision: revision, policyRevision: revision, consentRevision: integer2(1), state: choice2("unknown", "granted", "denied", "withdrawn"), purpose, observedAt: instant, evidenceRef: revision });
971
1131
  var parseResonanceConsentSnapshot = (v) => consent.read(v, "consent");
972
- var exposure = object2({ ...scope, experimentId: uuid, experimentRevision: integer2(1), assignmentId: uuid, variantKey: text2(80), exposureId: uuid, occurredAt: instant });
973
- var conversion = object2({ schemaVersion: literal2(1), ...scope, eventId: uuid, sourceRef: source, campaignId: nullable2(uuid), goalRevision: revision, occurredAt: instant, receivedAt: instant, value: union2(object2({ state: literal2("observed"), money }), object2({ state: choice2("unknown", "unavailable"), money: literal2(null), reasonCode: text2(80) })), consent: list2(consent, 4), experiment: nullable2(exposure) });
1132
+ var exposure = object2({ ...scope, experimentId: uuid, experimentRevision: integer2(1), assignmentId: uuid, variantKey: text3(80), exposureId: uuid, occurredAt: instant });
1133
+ var conversion = object2({ schemaVersion: literal2(1), ...scope, eventId: uuid, sourceRef: source, campaignId: nullable2(uuid), goalRevision: revision, occurredAt: instant, receivedAt: instant, value: union2(object2({ state: literal2("observed"), money }), object2({ state: choice2("unknown", "unavailable"), money: literal2(null), reasonCode: text3(80) })), consent: list2(consent, 4), experiment: nullable2(exposure) });
974
1134
  function parseResonanceConversionEnvelope(v) {
975
1135
  const r = conversion.read(v, "conversion");
976
1136
  unique(r.consent.map((c) => c.purpose), "conversion.consent");
977
1137
  scoped(r, r.projectId, [r.site], "conversion");
978
- if (Date.parse(r.receivedAt) < Date.parse(r.occurredAt)) fail2("conversion.receivedAt", "precedes occurrence");
1138
+ if (Date.parse(r.receivedAt) < Date.parse(r.occurredAt)) fail3("conversion.receivedAt", "precedes occurrence");
979
1139
  return r;
980
1140
  }
981
1141
  var RESONANCE_CONVERSION_JSON_SCHEMA = conversion.schema;
@@ -989,14 +1149,17 @@ var RESONANCE_METRIC_JSON_SCHEMA = metric.schema;
989
1149
  var RESONANCE_CONSENT_JSON_SCHEMA = consent.schema;
990
1150
  var parseResonanceExperimentExposure = (v) => exposure.read(v, "exposure");
991
1151
  var mandateTarget = object2({ project_id: uuid, campaign_id: uuid });
992
- var mandateApproval = object2({ schemaVersion: literal2(1), expectedRevision: integer2(1), preparedPlanId: uuid, reviewDigest: digest, mandateDigest: digest, mandate: mandateScope });
1152
+ var mandateApproval = object2({ schemaVersion: literal2(1), expectedRevision: integer2(1), preparedPlanId: uuid, reviewDigest: digest, mandateDigest: digest, mandate: mandateScope, operatingPolicyBase: optional2(operatingPolicyBase) });
993
1153
  var RESONANCE_MANDATE_APPROVAL_JSON_SCHEMA = mandateApproval.schema;
994
1154
  var RESONANCE_MANDATE_TARGET_JSON_SCHEMA = mandateTarget.schema;
995
1155
  var RESONANCE_MANDATE_ACTION_KIND = "resonance_mandate";
996
1156
  function parseResonanceMandateApprovalPayload(v, target) {
997
1157
  const r = mandateApproval.read(v, "mandateApproval"), t = mandateTarget.read(target, "target_ref");
998
1158
  parseResonanceMandateScope(r.mandate);
999
- if (r.mandate.projectId !== t.project_id || r.mandate.campaignId !== t.campaign_id || r.preparedPlanId !== r.mandate.preparedPlanId || r.reviewDigest !== r.mandate.reviewDigest) fail2("mandateApproval", "target or snapshot mismatch");
1159
+ if (r.operatingPolicyBase && !r.mandate.operatingPolicy && !r.mandate.providerReporting) {
1160
+ fail3("mandateApproval.operatingPolicyBase", "requires explicit prospective operating or reporting scope");
1161
+ }
1162
+ if (r.mandate.projectId !== t.project_id || r.mandate.campaignId !== t.campaign_id || r.preparedPlanId !== r.mandate.preparedPlanId || r.reviewDigest !== r.mandate.reviewDigest) fail3("mandateApproval", "target or snapshot mismatch");
1000
1163
  return r;
1001
1164
  }
1002
1165
  function canonical(value) {
@@ -1010,7 +1173,7 @@ var parseResonanceMandateTarget = (v) => mandateTarget.read(v, "target_ref");
1010
1173
  var positioningTarget = union2(
1011
1174
  object2({ kind: literal2("broadcast"), channelId: uuid }),
1012
1175
  object2({ kind: literal2("meta"), channelId: uuid, creativeId: uuid }),
1013
- object2({ kind: literal2("google_search"), channelId: uuid, adGroupKey: text2(80), adKey: text2(80) })
1176
+ object2({ kind: literal2("google_search"), channelId: uuid, adGroupKey: text3(80), adKey: text3(80) })
1014
1177
  );
1015
1178
  var positioningRequest = object2({
1016
1179
  schemaVersion: literal2(1),
@@ -1023,46 +1186,46 @@ var positioningRequest = object2({
1023
1186
  var positioningWitnessFields = {
1024
1187
  id: operationKey,
1025
1188
  kind: choice2("page", "funnel", "offer", "brain", "buyer", "proof"),
1026
- sourceId: text2(160),
1189
+ sourceId: text3(160),
1027
1190
  revision,
1028
1191
  observedAt: instant,
1029
1192
  expiresAt: instant,
1030
1193
  permission: choice2("private", "public"),
1031
1194
  certainty: choice2("verified", "reported", "conflicting")
1032
1195
  };
1033
- var positioningWitness = refine2(object2(positioningWitnessFields), checkPositioningWitness);
1034
- var positioningText = (max) => refine2(text2(max), (value, at) => {
1035
- if (!value.trim() || /[\x00-\x08\x0b-\x1f\x7f]/.test(value)) fail2(at, "requires nonblank text without control characters");
1196
+ var positioningWitness = refine3(object2(positioningWitnessFields), checkPositioningWitness);
1197
+ var positioningText = (max) => refine3(text3(max), (value, at) => {
1198
+ if (!value.trim() || /[\x00-\x08\x0b-\x1f\x7f]/.test(value)) fail3(at, "requires nonblank text without control characters");
1036
1199
  });
1037
- var positioningEvidence = refine2(object2({ ...positioningWitnessFields, text: positioningText(1600) }), checkPositioningWitness);
1200
+ var positioningEvidence = refine3(object2({ ...positioningWitnessFields, text: positioningText(1600) }), checkPositioningWitness);
1038
1201
  function checkPositioningWitness(value, at) {
1039
- if (Date.parse(value.observedAt) >= Date.parse(value.expiresAt)) fail2(at, "requires a positive witness lifetime");
1202
+ if (Date.parse(value.observedAt) >= Date.parse(value.expiresAt)) fail3(at, "requires a positive witness lifetime");
1040
1203
  }
1041
1204
  var positioningScopeFields = { schemaVersion: literal2(1), projectId: uuid, campaignId: uuid, request: positioningRequest, observedAt: instant, expiresAt: instant };
1042
1205
  function checkPositioningWindow(value, at) {
1043
- if (Date.parse(value.observedAt) >= Date.parse(value.expiresAt)) fail2(at, "requires a positive review lifetime");
1206
+ if (Date.parse(value.observedAt) >= Date.parse(value.expiresAt)) fail3(at, "requires a positive review lifetime");
1044
1207
  unique(value.evidence.map((item) => item.id), at + ".evidence");
1045
- if (value.evidence.some((item) => Date.parse(item.observedAt) > Date.parse(value.observedAt))) fail2(at + ".evidence", "witness observation postdates the preview");
1208
+ if (value.evidence.some((item) => Date.parse(item.observedAt) > Date.parse(value.observedAt))) fail3(at + ".evidence", "witness observation postdates the preview");
1046
1209
  }
1047
- var positioningContext = refine2(object2({
1210
+ var positioningContext = refine3(object2({
1048
1211
  ...positioningScopeFields,
1049
1212
  orgId: uuid,
1050
1213
  evidence: list2(positioningEvidence, 32)
1051
1214
  }), (value, at) => {
1052
1215
  checkPositioningWindow(value, at);
1053
1216
  if (value.evidence.reduce((total, witness) => total + witness.text.length, 0) > 16e3) {
1054
- fail2(at + ".evidence", "exceeds the combined source text budget");
1217
+ fail3(at + ".evidence", "exceeds the combined source text budget");
1055
1218
  }
1056
1219
  });
1057
1220
  var positioningEvidenceIds = uniqueList(operationKey, 8);
1058
1221
  var positioningSupportedText = object2({ text: positioningText(320), evidenceIds: positioningEvidenceIds });
1059
- var positioningAlternative = refine2(object2({
1222
+ var positioningAlternative = refine3(object2({
1060
1223
  text: positioningText(320),
1061
1224
  kind: choice2("status_quo", "alternative"),
1062
1225
  basis: choice2("evidence", "hypothesis"),
1063
1226
  evidenceIds: positioningEvidenceIds
1064
1227
  }), (value, at) => {
1065
- if (value.basis === "evidence" !== value.evidenceIds.length > 0) fail2(at, "requires evidence references exactly for evidenced alternatives");
1228
+ if (value.basis === "evidence" !== value.evidenceIds.length > 0) fail3(at, "requires evidence references exactly for evidenced alternatives");
1066
1229
  });
1067
1230
  var positioningClaim = object2({
1068
1231
  attribute: positioningText(320),
@@ -1103,7 +1266,7 @@ var positioningReasonCodes = choice2(
1103
1266
  "generation_unavailable"
1104
1267
  );
1105
1268
  var RESONANCE_POSITIONING_METHOD_VERSION = "positioning_v1";
1106
- var positioningResult = refine2(object2({
1269
+ var positioningResult = refine3(object2({
1107
1270
  methodVersion: literal2(RESONANCE_POSITIONING_METHOD_VERSION),
1108
1271
  state: choice2("ready", "provisional", "no_fit"),
1109
1272
  reasonCodes: uniqueList(positioningReasonCodes, 12),
@@ -1117,15 +1280,15 @@ var positioningResult = refine2(object2({
1117
1280
  copy: nullable2(positioningCopy)
1118
1281
  }), (value, at) => {
1119
1282
  if (value.state !== "ready") {
1120
- if (value.copy || !value.reasonCodes.length) fail2(at, "requires a reason and no draft copy when held");
1283
+ if (value.copy || !value.reasonCodes.length) fail3(at, "requires a reason and no draft copy when held");
1121
1284
  return;
1122
1285
  }
1123
1286
  const { copy, claims, category, bestFit, alternatives } = value;
1124
1287
  if (!copy || value.reasonCodes.length || !claims.length || !category || !bestFit.length || !alternatives.length) {
1125
- return fail2(at, "requires a supported ready brief and channel draft");
1288
+ return fail3(at, "requires a supported ready brief and channel draft");
1126
1289
  }
1127
1290
  unique(copy.claimIndexes.map(String), at + ".copy.claimIndexes");
1128
- if (copy.claimIndexes.some((index) => index >= claims.length)) fail2(at + ".copy.claimIndexes", "requires an existing claim index");
1291
+ if (copy.claimIndexes.some((index) => index >= claims.length)) fail3(at + ".copy.claimIndexes", "requires an existing claim index");
1129
1292
  });
1130
1293
  function checkPositioningEvidence(result, context, at) {
1131
1294
  const evidence = new Map(context.evidence.map((witness) => [witness.id, witness]));
@@ -1137,37 +1300,37 @@ function checkPositioningEvidence(result, context, at) {
1137
1300
  ...result.category ? [result.category] : [],
1138
1301
  ...result.timelyContext ? [result.timelyContext] : []
1139
1302
  ];
1140
- if (cited.some((item) => item.evidenceIds.some((id) => !evidence.has(id)))) fail2(at, "references unknown evidence");
1303
+ if (cited.some((item) => item.evidenceIds.some((id) => !evidence.has(id)))) fail3(at, "references unknown evidence");
1141
1304
  for (const claim of result.claims) {
1142
1305
  for (const id of claim.publicProofIds) {
1143
1306
  const witness = evidence.get(id);
1144
- if (!witness || witness.permission !== "public" || !current(witness)) fail2(at, "public proof requires a current permitted witness");
1307
+ if (!witness || witness.permission !== "public" || !current(witness)) fail3(at, "public proof requires a current permitted witness");
1145
1308
  }
1146
1309
  }
1147
1310
  if (result.timelyContext && (!result.timelyContext.evidenceIds.length || result.timelyContext.evidenceIds.some((id) => {
1148
1311
  const witness = evidence.get(id);
1149
1312
  return !witness || !current(witness);
1150
- }))) fail2(at, "timely context requires current verified evidence");
1313
+ }))) fail3(at, "timely context requires current verified evidence");
1151
1314
  if (!result.copy) return;
1152
- if (result.copy.kind !== context.request.target.kind) fail2(at, "copy target differs from the request");
1315
+ if (result.copy.kind !== context.request.target.kind) fail3(at, "copy target differs from the request");
1153
1316
  const { destination: selected, offerId } = context.request;
1154
1317
  const owns = (kind, id) => {
1155
1318
  const witnesses = context.evidence.filter((w) => w.kind === kind && (!id || w.sourceId.toLowerCase() === id.toLowerCase()));
1156
1319
  return witnesses.some(current) && !witnesses.some((w) => w.certainty === "conflicting");
1157
1320
  };
1158
1321
  if (!selected || !owns(selected.kind === "existing_page" ? "page" : "funnel", selected.id) || !owns("brain") || offerId && !owns("offer", offerId)) {
1159
- fail2(at, "ready copy requires current destination, Brain and selected offer witnesses");
1322
+ fail3(at, "ready copy requires current destination, Brain and selected offer witnesses");
1160
1323
  }
1161
1324
  for (const index of result.copy.claimIndexes) {
1162
1325
  const claim = result.claims[index];
1163
1326
  if (![...claim.evidenceIds, ...claim.publicProofIds].every((id) => {
1164
1327
  const witness = evidence.get(id);
1165
1328
  return witness && witness.permission === "public" && current(witness);
1166
- })) fail2(at, "selected copy requires current verified public claim evidence");
1329
+ })) fail3(at, "selected copy requires current verified public claim evidence");
1167
1330
  }
1168
1331
  }
1169
- var positioningApplicationToken = text2(32e3, /^[a-zA-Z0-9._-]+$/);
1170
- var positioningPreview = refine2(object2({
1332
+ var positioningApplicationToken = text3(32e3, /^[a-zA-Z0-9._-]+$/);
1333
+ var positioningPreview = refine3(object2({
1171
1334
  ...positioningScopeFields,
1172
1335
  evidence: list2(positioningWitness, 32),
1173
1336
  result: positioningResult,
@@ -1175,7 +1338,7 @@ var positioningPreview = refine2(object2({
1175
1338
  }), (value, at) => {
1176
1339
  checkPositioningWindow(value, at);
1177
1340
  checkPositioningEvidence(value.result, value, at + ".result");
1178
- if (value.result.state === "ready" !== (value.applicationToken !== null)) fail2(at, "requires an application token exactly for ready copy");
1341
+ if (value.result.state === "ready" !== (value.applicationToken !== null)) fail3(at, "requires an application token exactly for ready copy");
1179
1342
  });
1180
1343
  var positioningApplyRequest = object2({ applicationToken: positioningApplicationToken });
1181
1344
  var parseResonancePositioningPreviewRequest = (value) => positioningRequest.read(value, "positioningPreviewRequest");
@@ -1215,26 +1378,281 @@ function parseResonancePositioningConsistencyAssessment(value, expected) {
1215
1378
  const at = "positioningConsistencyAssessment";
1216
1379
  const assessment = positioningConsistencyAssessment.read(value, at);
1217
1380
  if (assessment.evidenceDigest !== digest.read(expected.evidenceDigest, at + ".expectedEvidenceDigest")) {
1218
- fail2(at + ".evidenceDigest", "requires the exact current permitted evidence digest");
1381
+ fail3(at + ".evidenceDigest", "requires the exact current permitted evidence digest");
1219
1382
  }
1220
1383
  const eligibleIds = new Set(projectResonancePositioningConsistencyEvidence(expected.context).map((witness) => witness.id));
1221
1384
  const { state, coveredSourceIds } = assessment;
1222
1385
  if (coveredSourceIds.some((id) => !eligibleIds.has(id)) || state !== "unknown" && coveredSourceIds.length !== eligibleIds.size || state === "compatible" && coveredSourceIds.length < 1 || state === "conflicting" && coveredSourceIds.length < 2) {
1223
- fail2(at + ".coveredSourceIds", "coverage does not support this consistency state");
1386
+ fail3(at + ".coveredSourceIds", "coverage does not support this consistency state");
1224
1387
  }
1225
1388
  return assessment;
1226
1389
  }
1227
1390
  var RESONANCE_POSITIONING_CONSISTENCY_ASSESSMENT_JSON_SCHEMA = positioningConsistencyAssessment.schema;
1228
- var prepareCommand = object2({ expectedRevision: integer2(1), idempotencyKey: operationKey });
1391
+ var prepareCommand = object2({ expectedRevision: integer2(1), idempotencyKey: operationKey, googleContentUpdate: optional2(googleContentUpdateSelection) });
1229
1392
  var parseResonancePrepareCommand = (v) => prepareCommand.read(v, "prepare");
1230
1393
  var parseResonanceCommandPrepareRequest = parseResonancePrepareCommand;
1231
- var commandPreparation = object2({ command: nullable2(command), covered: bool, approvalRequirement: nullable2(choice2("existing_mandate", "current_owner")), reasonCodes: list2(text2(200), 100) });
1394
+ var commandPreparation = object2({ command: nullable2(command), covered: bool, approvalRequirement: nullable2(choice2("existing_mandate", "current_owner")), reasonCodes: list2(text3(200), 100) });
1232
1395
  function parseResonanceCommandPrepareResponse(v) {
1233
1396
  const r = commandPreparation.read(v, "commandPreparation");
1234
1397
  if (r.command) parseResonanceCommand(r.command);
1235
1398
  return r;
1236
1399
  }
1237
1400
  var RESONANCE_COMMAND_PREPARE_REQUEST_JSON_SCHEMA = prepareCommand.schema;
1401
+ var preparationLookupRequest = object2({ expectedRevision: integer2(1), idempotencyKey: operationKey });
1402
+ var preparationLookupOperation = object2({
1403
+ operationId: uuid,
1404
+ preparedPlanId: uuid,
1405
+ executionState: choice2("reserved", "claimed", "dispatched", "succeeded", "rejected", "uncertain", "cancelled"),
1406
+ createdAt: instant,
1407
+ hasAdDispatch: bool,
1408
+ artifactCount: integer2(0, 512),
1409
+ completedArtifactCount: integer2(0, 512),
1410
+ originalActorMatches: bool,
1411
+ originalPrincipalMatches: bool
1412
+ });
1413
+ var preparationLookupResponse = object2({
1414
+ schemaVersion: literal2(1),
1415
+ projectId: uuid,
1416
+ campaignId: uuid,
1417
+ request: preparationLookupRequest,
1418
+ state: choice2("not_found", "working", "recovery_required", "succeeded", "rejected", "cancelled"),
1419
+ currentRevision: integer2(1),
1420
+ operation: nullable2(preparationLookupOperation),
1421
+ preparedPlan: nullable2(prepared),
1422
+ readiness: object2({ reasonCodes: list2(choice2(
1423
+ "PREPARATION_NOT_FOUND",
1424
+ "PREPARATION_WORKING",
1425
+ "PREPARATION_RECOVERY_REQUIRED",
1426
+ "PREPARATION_REJECTED",
1427
+ "PREPARATION_CANCELLED",
1428
+ "PREPARATION_OWNER_MISMATCH",
1429
+ "PREPARATION_REVISION_CHANGED",
1430
+ "PREPARATION_HAS_AD_DISPATCH",
1431
+ "PREPARATION_INVENTORY_UNAVAILABLE",
1432
+ "PREPARATION_TERMINAL_PROVIDER_REJECTION",
1433
+ "PREPARATION_ACCEPTED_REVIEW_AVAILABLE",
1434
+ "PREPARATION_FINANCIAL_EXPOSURE",
1435
+ "OWNER_STEP_FAILED",
1436
+ "OWNER_SOURCE_CHANGED",
1437
+ "SIGNER_CHANGED"
1438
+ ), 30), canResume: bool })
1439
+ });
1440
+ var parseResonancePreparationLookupRequest = (v) => preparationLookupRequest.read(v, "preparationLookupRequest");
1441
+ function parseResonancePreparationLookupResponse(v) {
1442
+ const r = preparationLookupResponse.read(v, "preparationLookupResponse"), p = "preparationLookupResponse";
1443
+ if (r.state === "not_found") {
1444
+ if (r.operation || r.preparedPlan || r.readiness.canResume) fail3(p, "absence cannot carry a saved operation, plan or recovery permission");
1445
+ return r;
1446
+ }
1447
+ const o = r.operation;
1448
+ if (!o || o.completedArtifactCount > o.artifactCount) return fail3(p + ".operation", "requires the original operation and consistent artifact counts");
1449
+ const terminal = ["succeeded", "rejected", "cancelled"].includes(r.state);
1450
+ if (terminal ? o.executionState !== r.state : !["reserved", "claimed", "dispatched", "uncertain"].includes(o.executionState)) fail3(p + ".state", "does not match the original execution state");
1451
+ if (r.readiness.canResume && (r.state !== "recovery_required" || o.hasAdDispatch || !o.originalActorMatches || !o.originalPrincipalMatches || r.currentRevision !== r.request.expectedRevision)) fail3(p + ".readiness", "requires the same original caller and a recoverable pre-dispatch outcome");
1452
+ if (r.state === "succeeded") {
1453
+ if (!r.preparedPlan) return fail3(p + ".preparedPlan", "requires the saved original plan");
1454
+ const plan = parseResonancePreparedPlan(r.preparedPlan);
1455
+ if (plan.projectId !== r.projectId || plan.campaignId !== r.campaignId || plan.expectedRevision !== r.request.expectedRevision || plan.id !== o.preparedPlanId) fail3(p + ".preparedPlan", "must match the exact original request and operation");
1456
+ } else if (r.preparedPlan) fail3(p + ".preparedPlan", "an unfinished preparation cannot return a successful plan");
1457
+ return r;
1458
+ }
1459
+ var RESONANCE_PREPARATION_LOOKUP_REQUEST_JSON_SCHEMA = preparationLookupRequest.schema;
1460
+ var RESONANCE_PREPARATION_LOOKUP_RESPONSE_JSON_SCHEMA = preparationLookupResponse.schema;
1461
+ var preparationRetireRequest = object2({ expectedRevision: integer2(1), reason: literal2("retain_unpublished_artifacts") });
1462
+ var preparationRetireResponse = refine3(object2({
1463
+ schemaVersion: literal2(1),
1464
+ projectId: uuid,
1465
+ campaignId: uuid,
1466
+ preparationOperationId: uuid,
1467
+ state: literal2("cancelled"),
1468
+ replayed: bool,
1469
+ retainedArtifactCount: integer2(0, 512),
1470
+ unrecordedSlotCount: integer2(0, 512),
1471
+ retiredAt: instant,
1472
+ reasonCodes: list2(text3(100), 0)
1473
+ }), (v, p) => {
1474
+ if (v.retainedArtifactCount + v.unrecordedSlotCount > 512) fail3(p, "artifact and unrecorded slot total exceeds bound");
1475
+ });
1476
+ var parseResonancePreparationRetireRequest = (v) => preparationRetireRequest.read(v, "preparationRetireRequest");
1477
+ var parseResonancePreparationRetireResponse = (v) => preparationRetireResponse.read(v, "preparationRetireResponse");
1478
+ var RESONANCE_PREPARATION_RETIRE_REQUEST_JSON_SCHEMA = preparationRetireRequest.schema;
1479
+ var RESONANCE_PREPARATION_RETIRE_RESPONSE_JSON_SCHEMA = preparationRetireResponse.schema;
1480
+ var diagnosticsCode = text3(100, /^[A-Za-z][A-Za-z0-9_]*$/);
1481
+ var diagnosticsReasons = list2(diagnosticsCode, 64);
1482
+ var diagnosticsId = text3(30, /^[1-9][0-9]*$/);
1483
+ var diagnosticsResource = text3(200, /^customers\/[0-9]+\/(?:conversionActions|customConversionGoals)\/[0-9]+$/);
1484
+ var diagnosticsDay = refine3(text3(10, /^\d{4}-\d{2}-\d{2}$/), (v, p) => {
1485
+ if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().slice(0, 10) !== v || v.startsWith("0000")) fail3(p, "invalid calendar date");
1486
+ });
1487
+ var RESONANCE_GOOGLE_DIAGNOSTICS_SECTIONS = ["campaign", "totals", "daily", "keywords", "searchTerms", "goals", "uploadDiagnostics"];
1488
+ var googleDiagnosticsRequestFields = {
1489
+ channelId: uuid,
1490
+ startDate: diagnosticsDay,
1491
+ endDate: diagnosticsDay,
1492
+ sections: list2(choice2(...RESONANCE_GOOGLE_DIAGNOSTICS_SECTIONS), 7, 1),
1493
+ directive: text3(2e3)
1494
+ };
1495
+ var checkDiagnosticsRequest = (v, p) => {
1496
+ unique(v.sections, p + ".sections");
1497
+ const days = (Date.parse(v.endDate) - Date.parse(v.startDate)) / 864e5 + 1;
1498
+ if (days < 1 || days > 31) fail3(p, "requires one to 31 calendar days");
1499
+ if (!v.directive.trim()) fail3(p + ".directive", "requires an explicit command");
1500
+ };
1501
+ var googleDiagnosticsRequest = refine3(object2(googleDiagnosticsRequestFields), checkDiagnosticsRequest);
1502
+ var parseResonanceGoogleCampaignDiagnosticsRequest = (v) => googleDiagnosticsRequest.read(v, "googleCampaignDiagnosticsRequest");
1503
+ var RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_REQUEST_JSON_SCHEMA = googleDiagnosticsRequest.schema;
1504
+ var googleDiagnosticsPayload = refine3(object2({
1505
+ schemaVersion: literal2(1),
1506
+ campaignId: uuid,
1507
+ expectedRevision: integer2(1),
1508
+ ...googleDiagnosticsRequestFields,
1509
+ accountBindingId: uuid,
1510
+ site,
1511
+ idempotencyKey: operationKey
1512
+ }), checkDiagnosticsRequest);
1513
+ var parseResonanceGoogleCampaignDiagnosticsPayload = (v) => googleDiagnosticsPayload.read(v, "googleCampaignDiagnosticsPayload");
1514
+ var RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_PAYLOAD_JSON_SCHEMA = googleDiagnosticsPayload.schema;
1515
+ var diagnosticsMetricsFields = {
1516
+ spendMicros: nullable2(decimal),
1517
+ impressions: nullable2(decimal),
1518
+ clicks: nullable2(decimal),
1519
+ conversions: nullable2(text3(61, /^(?:0|[1-9][0-9]{0,29})(?:\.[0-9]{0,29}[1-9])?$/)),
1520
+ allConversions: nullable2(text3(61, /^(?:0|[1-9][0-9]{0,29})(?:\.[0-9]{0,29}[1-9])?$/))
1521
+ };
1522
+ var diagnosticsMetrics = object2(diagnosticsMetricsFields);
1523
+ var diagnosticsCampaignRow = object2({
1524
+ status: diagnosticsCode,
1525
+ primaryStatus: nullable2(diagnosticsCode),
1526
+ primaryStatusReasons: diagnosticsReasons,
1527
+ servingStatus: nullable2(diagnosticsCode),
1528
+ biddingStrategyType: nullable2(diagnosticsCode),
1529
+ startDate: nullable2(diagnosticsDay),
1530
+ endDate: nullable2(diagnosticsDay),
1531
+ budgetAmountMicros: nullable2(decimal),
1532
+ budgetPeriod: nullable2(diagnosticsCode),
1533
+ searchNetwork: nullable2(bool),
1534
+ searchPartners: nullable2(bool),
1535
+ displayNetwork: nullable2(bool),
1536
+ positiveGeoTargetType: nullable2(diagnosticsCode),
1537
+ negativeGeoTargetType: nullable2(diagnosticsCode),
1538
+ locationCriterionIds: list2(diagnosticsId, 100)
1539
+ });
1540
+ var diagnosticsKeywordRow = object2({
1541
+ criterionId: diagnosticsId,
1542
+ adGroupId: diagnosticsId,
1543
+ matchType: nullable2(diagnosticsCode),
1544
+ status: nullable2(diagnosticsCode),
1545
+ negative: bool,
1546
+ ...diagnosticsMetricsFields
1547
+ });
1548
+ var diagnosticsTermRow = object2({
1549
+ rowId: digest,
1550
+ adGroupId: diagnosticsId,
1551
+ status: nullable2(diagnosticsCode),
1552
+ keywordCriterionId: nullable2(diagnosticsId),
1553
+ matchType: nullable2(diagnosticsCode),
1554
+ ...diagnosticsMetricsFields
1555
+ });
1556
+ var diagnosticsGoalRow = object2({
1557
+ goalConfigLevel: nullable2(diagnosticsCode),
1558
+ customGoalResourceName: nullable2(diagnosticsResource),
1559
+ customGoalStatus: nullable2(diagnosticsCode),
1560
+ actionResourceName: diagnosticsResource,
1561
+ actionStatus: nullable2(diagnosticsCode),
1562
+ type: nullable2(diagnosticsCode),
1563
+ category: nullable2(diagnosticsCode),
1564
+ primaryForGoal: nullable2(bool),
1565
+ countingType: nullable2(diagnosticsCode),
1566
+ clickThroughLookbackWindowDays: nullable2(integer2(1, 365))
1567
+ });
1568
+ var diagnosticsUploadRow = object2({
1569
+ actionResourceName: diagnosticsResource,
1570
+ client: nullable2(diagnosticsCode),
1571
+ status: nullable2(diagnosticsCode),
1572
+ lastUploadDateTime: nullable2(text3(40, /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})?$/)),
1573
+ totalEventCount: nullable2(decimal),
1574
+ successfulEventCount: nullable2(decimal),
1575
+ pendingEventCount: nullable2(decimal),
1576
+ alertCodes: diagnosticsReasons
1577
+ });
1578
+ function diagnosticsSection(row, max) {
1579
+ return refine3(object2({
1580
+ state: choice2("available", "unavailable", "capped"),
1581
+ reasonCodes: diagnosticsReasons,
1582
+ rows: list2(row, max),
1583
+ pagesRead: integer2(0, 100)
1584
+ }), (v, p) => {
1585
+ if (v.state === "unavailable" && v.rows.length) fail3(p, "unavailable sections cannot assert observed rows");
1586
+ if (v.state !== "available" && !v.reasonCodes.length) fail3(p, "incomplete sections require a reason");
1587
+ });
1588
+ }
1589
+ var googleDiagnosticsReport = object2({
1590
+ schemaVersion: literal2(1),
1591
+ provider: literal2("google_ads"),
1592
+ projectId: uuid,
1593
+ campaignId: uuid,
1594
+ channelId: uuid,
1595
+ site,
1596
+ accountBindingId: uuid,
1597
+ externalCampaignId: diagnosticsId,
1598
+ currency,
1599
+ accountTimeZone: timeZone,
1600
+ window: object2({ startDate: diagnosticsDay, endDate: diagnosticsDay, completeness: literal2("completed_days") }),
1601
+ observedAt: instant,
1602
+ sections: object2({
1603
+ campaign: diagnosticsSection(diagnosticsCampaignRow, 1),
1604
+ totals: diagnosticsSection(diagnosticsMetrics, 1),
1605
+ daily: diagnosticsSection(object2({ localDate: diagnosticsDay, ...diagnosticsMetricsFields }), 31),
1606
+ keywords: diagnosticsSection(diagnosticsKeywordRow, 500),
1607
+ searchTerms: diagnosticsSection(diagnosticsTermRow, 1e3),
1608
+ goals: diagnosticsSection(diagnosticsGoalRow, 100),
1609
+ uploadDiagnostics: diagnosticsSection(diagnosticsUploadRow, 300)
1610
+ }),
1611
+ searchTermCoverage: object2({
1612
+ state: choice2("available", "unavailable"),
1613
+ reasonCodes: diagnosticsReasons,
1614
+ disclosed: nullable2(diagnosticsMetrics),
1615
+ remainder: nullable2(diagnosticsMetrics)
1616
+ }),
1617
+ providerAuthored: object2({
1618
+ campaignName: nullable2(text3(300)),
1619
+ keywords: list2(object2({ adGroupId: diagnosticsId, criterionId: diagnosticsId, text: text3(500) }), 500),
1620
+ searchTerms: list2(object2({ rowId: digest, text: text3(500) }), 1e3),
1621
+ locations: list2(object2({ criterionId: diagnosticsId, name: text3(300) }), 100)
1622
+ })
1623
+ });
1624
+ function parseResonanceGoogleCampaignDiagnosticsReport(v) {
1625
+ const r = googleDiagnosticsReport.read(v, "googleCampaignDiagnosticsReport"), p = "googleCampaignDiagnosticsReport";
1626
+ const { startDate, endDate } = r.window;
1627
+ if (endDate < startDate || Date.parse(endDate) - Date.parse(startDate) > 30 * 864e5) fail3(p + ".window", "requires at most 31 calendar days");
1628
+ const local = new Intl.DateTimeFormat("en-CA", { timeZone: r.accountTimeZone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(new Date(r.observedAt));
1629
+ const today = ["year", "month", "day"].map((type) => local.find((part) => part.type === type).value).join("-");
1630
+ if (endDate >= today) fail3(p + ".window", "requires completed advertiser-local days");
1631
+ const days = r.sections.daily.rows.map((row) => row.localDate);
1632
+ if (days.some((day) => day < startDate || day > endDate)) fail3(p + ".daily", "row outside requested window");
1633
+ unique(days, p + ".daily");
1634
+ const keywordKey = (row) => row.adGroupId + ":" + row.criterionId;
1635
+ unique(r.sections.keywords.rows.map(keywordKey), p + ".keywords");
1636
+ unique(r.sections.searchTerms.rows.map((row) => row.rowId), p + ".searchTerms");
1637
+ const coverage = r.searchTermCoverage;
1638
+ if (coverage.state === "unavailable" && (coverage.remainder || !coverage.reasonCodes.length)) fail3(p + ".searchTermCoverage", "unknown coverage must not assert a remainder");
1639
+ if (coverage.state === "available" && (r.sections.searchTerms.state !== "available" || r.sections.totals.state !== "available" || !coverage.disclosed || !coverage.remainder)) fail3(p + ".searchTermCoverage", "requires complete compatible totals and disclosed rows");
1640
+ if (coverage.state === "available") {
1641
+ const total = r.sections.totals.rows[0];
1642
+ if (!total) fail3(p + ".searchTermCoverage", "requires campaign totals");
1643
+ for (const metric2 of ["spendMicros", "impressions", "clicks"]) {
1644
+ const all = total[metric2], disclosed = coverage.disclosed[metric2], remainder = coverage.remainder[metric2];
1645
+ if (remainder !== null && (all === null || disclosed === null || BigInt(all) - BigInt(disclosed) !== BigInt(remainder))) fail3(p + ".searchTermCoverage", "remainder must match compatible disclosed and campaign totals");
1646
+ }
1647
+ if (coverage.remainder.conversions !== null || coverage.remainder.allConversions !== null) fail3(p + ".searchTermCoverage", "conversion remainder is not established by this profile");
1648
+ }
1649
+ const keywordIds = new Set(r.sections.keywords.rows.map(keywordKey)), termIds = new Set(r.sections.searchTerms.rows.map((row) => row.rowId));
1650
+ unique(r.providerAuthored.keywords.map(keywordKey), p + ".providerAuthored.keywords");
1651
+ unique(r.providerAuthored.searchTerms.map((row) => row.rowId), p + ".providerAuthored.searchTerms");
1652
+ if (r.providerAuthored.keywords.some((row) => !keywordIds.has(keywordKey(row))) || r.providerAuthored.searchTerms.some((row) => !termIds.has(row.rowId))) fail3(p + ".providerAuthored", "text must identify an observed row");
1653
+ return r;
1654
+ }
1655
+ var RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_REPORT_JSON_SCHEMA = googleDiagnosticsReport.schema;
1238
1656
  var RESONANCE_COMMAND_PREPARE_RESPONSE_JSON_SCHEMA = commandPreparation.schema;
1239
1657
  function resonancePlanIssues(input, at) {
1240
1658
  const plan = parseResonancePreparedPlan(input), issues = [];
@@ -1268,12 +1686,12 @@ function resonancePlanIssues(input, at) {
1268
1686
  function compareMoney(a, b) {
1269
1687
  a = parseMoney(a);
1270
1688
  b = parseMoney(b);
1271
- if (a.currency !== b.currency) fail2("money.currency", "currency mismatch");
1689
+ if (a.currency !== b.currency) fail3("money.currency", "currency mismatch");
1272
1690
  const left = BigInt(a.amountMicros), right = BigInt(b.amountMicros);
1273
1691
  return left < right ? -1 : left > right ? 1 : 0;
1274
1692
  }
1275
1693
  function subtractMoney(a, b) {
1276
- if (compareMoney(a, b) < 0) fail2("money.amountMicros", "negative result");
1694
+ if (compareMoney(a, b) < 0) fail3("money.amountMicros", "negative result");
1277
1695
  return parseMoney({ currency: a.currency, amountMicros: (BigInt(a.amountMicros) - BigInt(b.amountMicros)).toString() });
1278
1696
  }
1279
1697
  function formatMoney(input) {
@@ -1285,21 +1703,21 @@ var saveCommand = object2({ definition: draft, expectedRevision: optional2(integ
1285
1703
  function parseResonanceCampaignSaveCommand(v, mode = "update") {
1286
1704
  const r = saveCommand.read(v, "save");
1287
1705
  parseResonanceCampaignDraft(r.definition);
1288
- if (mode !== "create" && mode !== "update") fail2("save.mode", "unsupported mode");
1289
- if (mode === "update" && (r.expectedRevision === void 0 || r.expectedRevision < 1)) fail2("save.expectedRevision", "required for update");
1706
+ if (mode !== "create" && mode !== "update") fail3("save.mode", "unsupported mode");
1707
+ if (mode === "update" && (r.expectedRevision === void 0 || r.expectedRevision < 1)) fail3("save.expectedRevision", "required for update");
1290
1708
  return r;
1291
1709
  }
1292
1710
  var acceptCommand = object2({ expectedRevision: integer2(1), ledgerActionId: uuid });
1293
1711
  var parseResonanceAcceptCommand = (v) => acceptCommand.read(v, "accept");
1294
- var bindingCommand = object2({ connectionId: uuid, provider: choice2("google_ads", "meta_ads"), externalAccountId: text2(160), expectedConnectionRevision: revision, idempotencyKey: operationKey });
1712
+ var bindingCommand = object2({ connectionId: uuid, provider: choice2("google_ads", "meta_ads"), externalAccountId: text3(160), expectedConnectionRevision: revision, idempotencyKey: operationKey });
1295
1713
  var parseResonanceBindingCommand = (v) => bindingCommand.read(v, "binding");
1296
1714
  var RESONANCE_SAVE_COMMAND_JSON_SCHEMA = saveCommand.schema;
1297
1715
  var RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA = acceptCommand.schema;
1298
1716
  var RESONANCE_BINDING_COMMAND_JSON_SCHEMA = bindingCommand.schema;
1299
1717
  var RESONANCE_CPQL_UNCERTAINTY_METHOD = "observational_cpql_missing_outcome_bound_v1";
1300
1718
  var allocationHorizon = union2(
1301
- refine2(object2({ kind: literal2("finite_period"), startAt: instant, endAt: instant, timeZone, sourceRef: revision }), (r, p) => {
1302
- if (Date.parse(r.endAt) <= Date.parse(r.startAt)) fail2(p, "invalid finite horizon");
1719
+ refine3(object2({ kind: literal2("finite_period"), startAt: instant, endAt: instant, timeZone, sourceRef: revision }), (r, p) => {
1720
+ if (Date.parse(r.endAt) <= Date.parse(r.startAt)) fail3(p, "invalid finite horizon");
1303
1721
  }),
1304
1722
  object2({ kind: literal2("daily_average"), timeZone, sourceRef: revision })
1305
1723
  );
@@ -1311,7 +1729,7 @@ function conditionalCpqlOutcomeBound(input, spend) {
1311
1729
  const n = BigInt(decimal.read(input.eligibleContacts, "bound.eligibleContacts"));
1312
1730
  const c = BigInt(decimal.read(input.fullyResolvedContacts, "bound.fullyResolvedContacts"));
1313
1731
  const k = BigInt(decimal.read(input.qualifiedContacts, "bound.qualifiedContacts"));
1314
- if (c > n || k > c) fail2("bound", "inconsistent unique-contact source universe");
1732
+ if (c > n || k > c) fail3("bound", "inconsistent unique-contact source universe");
1315
1733
  if (n === 0n || k === 0n || parseMoney(spend).amountMicros === "0") return null;
1316
1734
  const u = n - c, denominator = 2n * k + u;
1317
1735
  return Number((10000n * u + denominator - 1n) / denominator);
@@ -1339,17 +1757,17 @@ var allocationEvidenceFields = {
1339
1757
  assignmentCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1340
1758
  powerCheck: choice2("pass", "failed", "unknown", "not_applicable")
1341
1759
  };
1342
- var allocationChannelFields = { channelId: uuid, site, accountBindingId: uuid, trackingState: choice2("healthy", "blocked", "unknown"), coverageBasisPoints: nullable2(integer2(0, 1e4)), coverageFamily: choice2("crm_attribution", "provider_import", "experiment_exposure"), coverageDefinitionRef: resource, coveredNumerator: nullable2(decimal), eligibleDenominator: nullable2(decimal), uncertaintyBasisPoints: nullable2(integer2(0, 1e4)), uncertaintySource: nullable2(uncertaintySource), dedupeCheck: choice2("pass", "failed", "unknown", "not_applicable"), qualificationCheck: choice2("pass", "failed", "unknown", "not_applicable"), reasonCodes: list2(text2(80), 50), capabilityRevision: revision, budgetMode: choice2("campaign_total", "average_daily", "lifetime", "daily"), allocationHorizon: nullable2(allocationHorizon), matureThrough: nullable2(instant), dataThrough: nullable2(instant), goalRevision: revision, countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order"), attributionModel: text2(100), attributionWindowDays: integer2(1, 365), policyRevision: revision, currentAllocation: money, remoteSnapshotDigest: digest, observations: list2(metric, 100), providerUnitExponent: refine2(integer2(0, 6), (v, p) => {
1343
- if (![0, 2, 3, 6].includes(v)) fail2(p, "unsupported provider exponent");
1760
+ var allocationChannelFields = { channelId: uuid, site, accountBindingId: uuid, trackingState: choice2("healthy", "blocked", "unknown"), coverageBasisPoints: nullable2(integer2(0, 1e4)), coverageFamily: choice2("crm_attribution", "provider_import", "experiment_exposure"), coverageDefinitionRef: resource, coveredNumerator: nullable2(decimal), eligibleDenominator: nullable2(decimal), uncertaintyBasisPoints: nullable2(integer2(0, 1e4)), uncertaintySource: nullable2(uncertaintySource), dedupeCheck: choice2("pass", "failed", "unknown", "not_applicable"), qualificationCheck: choice2("pass", "failed", "unknown", "not_applicable"), reasonCodes: list2(text3(80), 50), capabilityRevision: revision, budgetMode: choice2("campaign_total", "average_daily", "lifetime", "daily"), allocationHorizon: nullable2(allocationHorizon), matureThrough: nullable2(instant), dataThrough: nullable2(instant), goalRevision: revision, countingUnit: choice2("unique_source", "unique_qualified_contact", "net_order"), attributionModel: text3(100), attributionWindowDays: integer2(1, 365), policyRevision: revision, currentAllocation: money, remoteSnapshotDigest: digest, observations: list2(metric, 100), providerUnitExponent: refine3(integer2(0, 6), (v, p) => {
1761
+ if (![0, 2, 3, 6].includes(v)) fail3(p, "unsupported provider exponent");
1344
1762
  }), providerMaxUnits: decimal };
1345
1763
  var { uncertaintySource: _legacyUncertaintyField, ...reportedChannelFields } = allocationChannelFields;
1346
1764
  var matureOptimizationEvidence = object2({ ...allocationEvidenceFields, resolvedPolicy: matureOptimizationPolicy, channels: list2(object2({ ...allocationChannelFields, uncertaintySource: nullable2(uncertaintySource) }), 100, 1) });
1347
1765
  var reportedCostFields = { basis: literal2("provider_reported_snapshot_v1"), observationId: uuid, sourceEvidenceDigest: digest, reportedSpend: money, queriedFrom: instant, queriedThrough: instant, firstReceivedAt: instant, receivedAt: instant, recordedAt: instant, providerFinality: literal2("unknown"), correctionsPossible: literal2(true) };
1348
1766
  var reportedOutcomeSource = object2({ method: literal2(RESONANCE_CPQL_UNCERTAINTY_METHOD), eligibleContacts: decimal, fullyResolvedContacts: decimal, qualifiedContacts: decimal, sourceRevision: revision, qualificationRuleRef: resource, universeComplete: literal2(true) });
1349
- var nativeSqlReadInstant = refine2(text2(32, /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/), (v, p) => {
1767
+ var nativeSqlReadInstant = refine3(text3(32, /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/), (v, p) => {
1350
1768
  const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(v);
1351
1769
  const projected = match[1] + "." + (match[2] ?? "").padEnd(3, "0").slice(0, 3) + "Z";
1352
- if (!Number.isFinite(Date.parse(projected)) || new Date(projected).toISOString() !== projected) fail2(p, "invalid native SQL UTC instant");
1770
+ if (!Number.isFinite(Date.parse(projected)) || new Date(projected).toISOString() !== projected) fail3(p, "invalid native SQL UTC instant");
1353
1771
  });
1354
1772
  var providerReadClock = object2({ kind: literal2("sql_before_provider_read_lower_bound_v1"), notBeforeAt: nativeSqlReadInstant });
1355
1773
  var channelReportedCost = object2({ ...reportedCostFields, readClock: providerReadClock });
@@ -1366,34 +1784,34 @@ function parseMatureOptimizationEvidence(v) {
1366
1784
  const r = matureOptimizationEvidence.read(v, "optimizationEvidence");
1367
1785
  for (const c of r.channels) {
1368
1786
  if (c.uncertaintySource === null) {
1369
- if (c.uncertaintyBasisPoints !== null) fail2("optimizationEvidence.channels.uncertainty", "no bound without source witness");
1370
- } else if (c.uncertaintySource.verifiedSpend.currency !== c.currentAllocation.currency || c.uncertaintyBasisPoints !== cpqlMissingOutcomeBound(c.uncertaintySource)) fail2("optimizationEvidence.channels.uncertainty", "source bound mismatch");
1787
+ if (c.uncertaintyBasisPoints !== null) fail3("optimizationEvidence.channels.uncertainty", "no bound without source witness");
1788
+ } else if (c.uncertaintySource.verifiedSpend.currency !== c.currentAllocation.currency || c.uncertaintyBasisPoints !== cpqlMissingOutcomeBound(c.uncertaintySource)) fail3("optimizationEvidence.channels.uncertainty", "source bound mismatch");
1371
1789
  }
1372
1790
  checkAllocationEvidence(r);
1373
1791
  return r;
1374
1792
  }
1375
1793
  function checkAllocationEvidence(r) {
1376
- if (r.objective.measurementRevision !== r.goalRevision) fail2("optimizationEvidence.goalRevision", "goal snapshot mismatch");
1377
- if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart) || r.dataThrough !== null && Date.parse(r.dataThrough) > Date.parse(r.observedAt)) fail2("optimizationEvidence.window", "invalid observed window");
1794
+ if (r.objective.measurementRevision !== r.goalRevision) fail3("optimizationEvidence.goalRevision", "goal snapshot mismatch");
1795
+ if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart) || r.dataThrough !== null && Date.parse(r.dataThrough) > Date.parse(r.observedAt)) fail3("optimizationEvidence.window", "invalid observed window");
1378
1796
  const sites = r.channels.map((c) => c.site);
1379
1797
  scoped(r, r.projectId, sites, "optimizationEvidence");
1380
1798
  unique(r.channels.map((c) => c.channelId), "optimizationEvidence.channels");
1381
1799
  const currency2 = r.channels[0].currentAllocation.currency;
1382
1800
  for (const c of r.channels) {
1383
- if (c.allocationHorizon !== null && (["campaign_total", "lifetime"].includes(c.budgetMode) ? c.allocationHorizon.kind !== "finite_period" : c.allocationHorizon.kind !== "daily_average")) fail2("optimizationEvidence.channels.allocationHorizon", "unapproved budget period normalization");
1801
+ if (c.allocationHorizon !== null && (["campaign_total", "lifetime"].includes(c.budgetMode) ? c.allocationHorizon.kind !== "finite_period" : c.allocationHorizon.kind !== "daily_average")) fail3("optimizationEvidence.channels.allocationHorizon", "unapproved budget period normalization");
1384
1802
  if (c.coveredNumerator === null || c.eligibleDenominator === null || c.eligibleDenominator === "0") {
1385
- if (c.coverageBasisPoints !== null) fail2("optimizationEvidence.channels.coverage", "unknown denominator means unknown coverage");
1803
+ if (c.coverageBasisPoints !== null) fail3("optimizationEvidence.channels.coverage", "unknown denominator means unknown coverage");
1386
1804
  } else {
1387
1805
  const numerator = BigInt(c.coveredNumerator), denominator = BigInt(c.eligibleDenominator);
1388
- if (numerator > denominator || c.coverageBasisPoints !== Number(numerator * 10000n / denominator)) fail2("optimizationEvidence.channels.coverage", "coverage ratio mismatch");
1806
+ if (numerator > denominator || c.coverageBasisPoints !== Number(numerator * 10000n / denominator)) fail3("optimizationEvidence.channels.coverage", "coverage ratio mismatch");
1389
1807
  }
1390
- if (r.resolvedPolicy.sourceRef === null && c.policyRevision !== r.policyDigest) fail2("optimizationEvidence.channels.policyRevision", "inline policy digest mismatch");
1391
- if (c.goalRevision !== r.goalRevision || c.countingUnit !== r.objective.countingUnit || c.attributionWindowDays !== r.objective.attributionWindowDays) fail2("optimizationEvidence.channels", "measurement semantics mismatch");
1392
- if (c.currentAllocation.currency !== currency2) fail2("optimizationEvidence.channels", "currency mismatch");
1808
+ if (r.resolvedPolicy.sourceRef === null && c.policyRevision !== r.policyDigest) fail3("optimizationEvidence.channels.policyRevision", "inline policy digest mismatch");
1809
+ if (c.goalRevision !== r.goalRevision || c.countingUnit !== r.objective.countingUnit || c.attributionWindowDays !== r.objective.attributionWindowDays) fail3("optimizationEvidence.channels", "measurement semantics mismatch");
1810
+ if (c.currentAllocation.currency !== currency2) fail3("optimizationEvidence.channels", "currency mismatch");
1393
1811
  moneyToProviderUnits(c.currentAllocation, { currency: currency2, unitExponent: c.providerUnitExponent, maxUnits: c.providerMaxUnits });
1394
1812
  for (const observation of c.observations) {
1395
1813
  parseResonanceMetricObservation(observation);
1396
- if (observation.campaignId !== r.campaignId || observation.site !== c.site) fail2("optimizationEvidence.channels.observations", "scope mismatch");
1814
+ if (observation.campaignId !== r.campaignId || observation.site !== c.site) fail3("optimizationEvidence.channels.observations", "scope mismatch");
1397
1815
  }
1398
1816
  }
1399
1817
  }
@@ -1405,37 +1823,37 @@ function parseReportedOptimizationEvidence(v) {
1405
1823
  function checkReportedAllocationEvidence(r) {
1406
1824
  const p = "optimizationEvidence";
1407
1825
  parseResonanceOptimizationPolicy(r.resolvedPolicy);
1408
- if (r.objective.source.kind !== "qualified_lead" || r.objective.countingUnit !== "unique_qualified_contact" || !r.objective.qualificationRuleRef || r.objective.qualificationRuleRef.module !== "crm") fail2(p + ".objective", "requires the original independent qualified-contact source");
1409
- if (r.dataThrough !== null) fail2(p + ".dataThrough", "query coverage cannot become mature provider dataThrough");
1826
+ if (r.objective.source.kind !== "qualified_lead" || r.objective.countingUnit !== "unique_qualified_contact" || !r.objective.qualificationRuleRef || r.objective.qualificationRuleRef.module !== "crm") fail3(p + ".objective", "requires the original independent qualified-contact source");
1827
+ if (r.dataThrough !== null) fail3(p + ".dataThrough", "query coverage cannot become mature provider dataThrough");
1410
1828
  unique(r.channels.map((c) => c.channelReportedCost.observationId), p + ".channels.channelReportedCost.observationId");
1411
1829
  const observedAt = Date.parse(r.observedAt), windowStart = Date.parse(r.windowStart), windowEnd = Date.parse(r.windowEnd);
1412
- if (windowEnd <= windowStart || windowEnd > observedAt) fail2(p + ".window", "requires a completed observed interval");
1830
+ if (windowEnd <= windowStart || windowEnd > observedAt) fail3(p + ".window", "requires a completed observed interval");
1413
1831
  let commonZone;
1414
1832
  for (const c of r.channels) {
1415
1833
  const cost = c.channelReportedCost, outcome = c.outcomeSource;
1416
- if (c.dataThrough !== null) fail2(p + ".channels.dataThrough", "query coverage cannot become mature provider dataThrough");
1417
- if (Date.parse(cost.queriedFrom) !== windowStart || Date.parse(cost.queriedThrough) !== windowEnd) fail2(p + ".channels.channelReportedCost", "requires the exact common query interval");
1834
+ if (c.dataThrough !== null) fail3(p + ".channels.dataThrough", "query coverage cannot become mature provider dataThrough");
1835
+ if (Date.parse(cost.queriedFrom) !== windowStart || Date.parse(cost.queriedThrough) !== windowEnd) fail3(p + ".channels.channelReportedCost", "requires the exact common query interval");
1418
1836
  const firstReceived = Date.parse(cost.firstReceivedAt), received = Date.parse(cost.receivedAt), recorded = Date.parse(cost.recordedAt);
1419
1837
  const anchor = Date.parse(cost.readClock.notBeforeAt);
1420
- if (received < firstReceived) fail2(p + ".channels.channelReportedCost", "HTTP receipts must retain internal ordering");
1421
- if (anchor < windowEnd || anchor > recorded || recorded > observedAt || observedAt - anchor > r.resolvedPolicy.maxEvidenceAgeSeconds * 1e3) fail2(p + ".channels.channelReportedCost.readClock", "requires the original fresh SQL-before-HTTP lower bound and SQL receipt order");
1422
- if (cost.reportedSpend.currency !== c.currentAllocation.currency || canonical(outcome.qualificationRuleRef) !== canonical(r.objective.qualificationRuleRef)) fail2(p + ".channels.outcomeSource", "requires original qualification reference and currency");
1423
- if (c.uncertaintyBasisPoints !== reportedCpqlMissingOutcomeBound({ ...outcome, reportedSpend: cost.reportedSpend })) fail2(p + ".channels.uncertainty", "conditional source bound mismatch");
1838
+ if (received < firstReceived) fail3(p + ".channels.channelReportedCost", "HTTP receipts must retain internal ordering");
1839
+ if (anchor < windowEnd || anchor > recorded || recorded > observedAt || observedAt - anchor > r.resolvedPolicy.maxEvidenceAgeSeconds * 1e3) fail3(p + ".channels.channelReportedCost.readClock", "requires the original fresh SQL-before-HTTP lower bound and SQL receipt order");
1840
+ if (cost.reportedSpend.currency !== c.currentAllocation.currency || canonical(outcome.qualificationRuleRef) !== canonical(r.objective.qualificationRuleRef)) fail3(p + ".channels.outcomeSource", "requires original qualification reference and currency");
1841
+ if (c.uncertaintyBasisPoints !== reportedCpqlMissingOutcomeBound({ ...outcome, reportedSpend: cost.reportedSpend })) fail3(p + ".channels.uncertainty", "conditional source bound mismatch");
1424
1842
  const spends = c.observations.filter((o) => o.name === "spend");
1425
- if (spends.length !== 1) fail2(p + ".channels.observations", "requires one exact provider spend snapshot, never overlapping sums");
1843
+ if (spends.length !== 1) fail3(p + ".channels.observations", "requires one exact provider spend snapshot, never overlapping sums");
1426
1844
  const spend = spends[0];
1427
- if (spend.state !== "observed" || spend.source !== "provider" || spend.countingUnit !== "provider_aggregate" || spend.attributionModel !== "provider_reported" || spend.value.kind !== "money" || canonical(spend.value.money) !== canonical(cost.reportedSpend) || Date.parse(spend.windowStart) !== windowStart || Date.parse(spend.windowEnd) !== windowEnd || spend.dataThrough !== null || Date.parse(spend.asOf) !== recorded) fail2(p + ".channels.observations", "reported spend must match the exact nonfinal provider snapshot");
1845
+ if (spend.state !== "observed" || spend.source !== "provider" || spend.countingUnit !== "provider_aggregate" || spend.attributionModel !== "provider_reported" || spend.value.kind !== "money" || canonical(spend.value.money) !== canonical(cost.reportedSpend) || Date.parse(spend.windowStart) !== windowStart || Date.parse(spend.windowEnd) !== windowEnd || spend.dataThrough !== null || Date.parse(spend.asOf) !== recorded) fail3(p + ".channels.observations", "reported spend must match the exact nonfinal provider snapshot");
1428
1846
  const outcomes = c.observations.filter((o) => o.name === "qualified_goals");
1429
- if (outcomes.length !== 1) fail2(p + ".channels.observations", "requires one independent qualified-contact source");
1847
+ if (outcomes.length !== 1) fail3(p + ".channels.observations", "requires one independent qualified-contact source");
1430
1848
  const qualified = outcomes[0];
1431
- if (qualified.state !== "observed" || qualified.source !== "first_party" || qualified.sourceRef !== outcome.sourceRevision || qualified.goalRevision !== r.goalRevision || qualified.countingUnit !== "unique_qualified_contact" || qualified.attributionModel !== r.resolvedPolicy.attributionModel || qualified.value.kind !== "count" || qualified.value.count !== outcome.qualifiedContacts || qualified.eligibleExposures !== outcome.eligibleContacts || qualified.matureOutcomes !== outcome.qualifiedContacts || qualified.dataThrough === null || Date.parse(qualified.dataThrough) < windowEnd || Date.parse(qualified.dataThrough) > observedAt || c.matureThrough === null || Date.parse(c.matureThrough) < windowEnd || Date.parse(c.matureThrough) > observedAt) fail2(p + ".channels.outcomeSource", "requires independent mature qualified-contact evidence");
1849
+ if (qualified.state !== "observed" || qualified.source !== "first_party" || qualified.sourceRef !== outcome.sourceRevision || qualified.goalRevision !== r.goalRevision || qualified.countingUnit !== "unique_qualified_contact" || qualified.attributionModel !== r.resolvedPolicy.attributionModel || qualified.value.kind !== "count" || qualified.value.count !== outcome.qualifiedContacts || qualified.eligibleExposures !== outcome.eligibleContacts || qualified.matureOutcomes !== outcome.qualifiedContacts || qualified.dataThrough === null || Date.parse(qualified.dataThrough) < windowEnd || Date.parse(qualified.dataThrough) > observedAt || c.matureThrough === null || Date.parse(c.matureThrough) < windowEnd || Date.parse(c.matureThrough) > observedAt) fail3(p + ".channels.outcomeSource", "requires independent mature qualified-contact evidence");
1432
1850
  const formatter = new Intl.DateTimeFormat("en-GB", { timeZone: spend.timeZone, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
1433
- if ([r.windowStart, r.windowEnd].some((t) => new Date(t).getUTCMilliseconds() !== 0 || formatter.format(new Date(t)) !== "00:00:00") || commonZone !== void 0 && commonZone !== spend.timeZone) fail2(p + ".channels.observations", "requires common advertiser-local completed days without rounding");
1851
+ if ([r.windowStart, r.windowEnd].some((t) => new Date(t).getUTCMilliseconds() !== 0 || formatter.format(new Date(t)) !== "00:00:00") || commonZone !== void 0 && commonZone !== spend.timeZone) fail3(p + ".channels.observations", "requires common advertiser-local completed days without rounding");
1434
1852
  commonZone = spend.timeZone;
1435
1853
  for (const o of c.observations) {
1436
1854
  parseResonanceMetricObservation(o);
1437
- if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site || Date.parse(o.windowStart) !== windowStart || Date.parse(o.windowEnd) !== windowEnd || o.timeZone !== spend.timeZone || Date.parse(o.asOf) > observedAt) fail2(p + ".channels.observations", "foreign or mismatched observation interval");
1438
- if (o.source === "provider" && o.dataThrough !== null) fail2(p + ".channels.observations", "reported provider observation remains nonfinal");
1855
+ if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site || Date.parse(o.windowStart) !== windowStart || Date.parse(o.windowEnd) !== windowEnd || o.timeZone !== spend.timeZone || Date.parse(o.asOf) > observedAt) fail3(p + ".channels.observations", "foreign or mismatched observation interval");
1856
+ if (o.source === "provider" && o.dataThrough !== null) fail3(p + ".channels.observations", "reported provider observation remains nonfinal");
1439
1857
  }
1440
1858
  }
1441
1859
  checkAllocationEvidence(r);
@@ -1443,9 +1861,9 @@ function checkReportedAllocationEvidence(r) {
1443
1861
  var optimizationEvidenceRefFields = { id: uuid, revision, evidenceDigest: digest };
1444
1862
  var optimizationEvidenceRef = object2(optimizationEvidenceRefFields);
1445
1863
  var finiteOwnMeasurement = union2(
1446
- object2({ state: literal2("unobserved"), observations: literal2(null), reasonCodes: list2(text2(80), 50) }),
1447
- object2({ state: choice2("pending", "blocked"), observations: nullable2(list2(metric, 100)), reasonCodes: list2(text2(80), 50) }),
1448
- object2({ state: literal2("mature"), observations: list2(metric, 100, 1), reasonCodes: list2(text2(80), 50) })
1864
+ object2({ state: literal2("unobserved"), observations: literal2(null), reasonCodes: list2(text3(80), 50) }),
1865
+ object2({ state: choice2("pending", "blocked"), observations: nullable2(list2(metric, 100)), reasonCodes: list2(text3(80), 50) }),
1866
+ object2({ state: literal2("mature"), observations: list2(metric, 100, 1), reasonCodes: list2(text3(80), 50) })
1449
1867
  );
1450
1868
  var finiteCandidateObservation = object2({
1451
1869
  channelId: uuid,
@@ -1463,7 +1881,7 @@ var finiteCandidateObservation = object2({
1463
1881
  coverageBasisPoints: nullable2(integer2(0, 1e4)),
1464
1882
  dedupeCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1465
1883
  qualificationCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1466
- reasonCodes: list2(text2(80), 50),
1884
+ reasonCodes: list2(text3(80), 50),
1467
1885
  ownMeasurement: finiteOwnMeasurement
1468
1886
  });
1469
1887
  var finiteOptimizationEvidence = object2({
@@ -1499,48 +1917,48 @@ function parseResonanceOptimizationEvidence(v, preparedPlan) {
1499
1917
  if (!("evidenceKind" in r)) return parseMatureOptimizationEvidence(r);
1500
1918
  if (r.evidenceKind === "reported_cpql_sql_clock_v1") return parseReportedOptimizationEvidence(r);
1501
1919
  const p = "optimizationEvidence", policy = parseResonanceOptimizationPolicy(r.resolvedPolicy);
1502
- if (r.objective.measurementRevision !== r.goalRevision || r.objective.countingUnit !== "unique_qualified_contact" || canonical(policy.measurementGuard.sourceRef) !== canonical(r.objective.source) || canonical(policy.measurementGuard.qualificationRuleRef) !== canonical(r.objective.qualificationRuleRef) || policy.measurementGuard.maturityDelaySeconds !== r.objective.maturityDelaySeconds) fail2(p + ".objective", "finite policy must retain the original qualified objective");
1503
- if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart) || r.dataThrough !== null && Date.parse(r.dataThrough) > Date.parse(r.observedAt)) fail2(p + ".window", "invalid observed window");
1920
+ if (r.objective.measurementRevision !== r.goalRevision || r.objective.countingUnit !== "unique_qualified_contact" || canonical(policy.measurementGuard.sourceRef) !== canonical(r.objective.source) || canonical(policy.measurementGuard.qualificationRuleRef) !== canonical(r.objective.qualificationRuleRef) || policy.measurementGuard.maturityDelaySeconds !== r.objective.maturityDelaySeconds) fail3(p + ".objective", "finite policy must retain the original qualified objective");
1921
+ if (Date.parse(r.windowEnd) <= Date.parse(r.windowStart) || r.dataThrough !== null && Date.parse(r.dataThrough) > Date.parse(r.observedAt)) fail3(p + ".window", "invalid observed window");
1504
1922
  unique(r.candidates.map((c) => c.channelId), p + ".candidates");
1505
- if (r.candidates.length !== policy.candidateChannelIds.length || r.candidates.some((c) => !policy.candidateChannelIds.includes(c.channelId))) fail2(p + ".candidates", "must cover exactly the original finite policy");
1923
+ if (r.candidates.length !== policy.candidateChannelIds.length || r.candidates.some((c) => !policy.candidateChannelIds.includes(c.channelId))) fail3(p + ".candidates", "must cover exactly the original finite policy");
1506
1924
  scoped(r, r.projectId, r.candidates.map((c) => c.site), p);
1507
1925
  for (const c of r.candidates) {
1508
- if (c.graphDigest !== c.manifestRef.digest) fail2(p + ".candidates.graphDigest", "must match the actual original manifest graph digest");
1509
- if (c.cap.currency !== policy.totalExplorationCap.currency || BigInt(c.cap.amountMicros) === 0n) fail2(p + ".candidates.cap", "requires the original positive cap currency");
1510
- if (Date.parse(c.flight.endAt) <= Date.parse(c.flight.startAt)) fail2(p + ".candidates.flight", "invalid original flight");
1926
+ if (c.graphDigest !== c.manifestRef.digest) fail3(p + ".candidates.graphDigest", "must match the actual original manifest graph digest");
1927
+ if (c.cap.currency !== policy.totalExplorationCap.currency || BigInt(c.cap.amountMicros) === 0n) fail3(p + ".candidates.cap", "requires the original positive cap currency");
1928
+ if (Date.parse(c.flight.endAt) <= Date.parse(c.flight.startAt)) fail3(p + ".candidates.flight", "invalid original flight");
1511
1929
  const schedule = policy.selection.eligibilitySchedule.find((s) => s.channelId === c.channelId);
1512
- if (Date.parse(schedule.notBefore) < Date.parse(c.flight.startAt) || Date.parse(schedule.notAfter) > Date.parse(c.flight.endAt)) fail2(p + ".candidates.flight", "selection must stay inside original flight");
1513
- if (c.lifecycle === "not_materialized" && (c.commitmentEvidenceRef !== null || c.activationsObserved !== 0)) fail2(p + ".candidates", "absence cannot borrow a commitment or prior activation");
1514
- if (["active", "stopped"].includes(c.lifecycle) && c.activationsObserved !== 1) fail2(p + ".candidates.activationsObserved", "active/stopped state requires its original activation");
1515
- if (c.lifecycle === "not_materialized" && c.ownMeasurement.observations !== null || c.activationsObserved === 0 && c.ownMeasurement.state === "mature") fail2(p + ".candidates.ownMeasurement", "cold/absent candidates cannot borrow mature observations");
1516
- if (c.ownMeasurement.state === "mature" && c.ownMeasurement.observations.some((o) => o.state !== "observed")) fail2(p + ".candidates.ownMeasurement", "mature observations must be observed");
1930
+ if (Date.parse(schedule.notBefore) < Date.parse(c.flight.startAt) || Date.parse(schedule.notAfter) > Date.parse(c.flight.endAt)) fail3(p + ".candidates.flight", "selection must stay inside original flight");
1931
+ if (c.lifecycle === "not_materialized" && (c.commitmentEvidenceRef !== null || c.activationsObserved !== 0)) fail3(p + ".candidates", "absence cannot borrow a commitment or prior activation");
1932
+ if (["active", "stopped"].includes(c.lifecycle) && c.activationsObserved !== 1) fail3(p + ".candidates.activationsObserved", "active/stopped state requires its original activation");
1933
+ if (c.lifecycle === "not_materialized" && c.ownMeasurement.observations !== null || c.activationsObserved === 0 && c.ownMeasurement.state === "mature") fail3(p + ".candidates.ownMeasurement", "cold/absent candidates cannot borrow mature observations");
1934
+ if (c.ownMeasurement.state === "mature" && c.ownMeasurement.observations.some((o) => o.state !== "observed")) fail3(p + ".candidates.ownMeasurement", "mature observations must be observed");
1517
1935
  for (const o of c.ownMeasurement.observations ?? []) {
1518
1936
  parseResonanceMetricObservation(o);
1519
- if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site) fail2(p + ".candidates.ownMeasurement", "foreign candidate measurement scope");
1520
- if (Date.parse(o.asOf) > Date.parse(r.observedAt) || Date.parse(o.windowStart) < Date.parse(r.windowStart) || Date.parse(o.windowEnd) > Date.parse(r.windowEnd) || o.dataThrough !== null && Date.parse(o.dataThrough) > Date.parse(r.observedAt)) fail2(p + ".candidates.ownMeasurement", "outside the actual candidate evidence window");
1937
+ if (o.projectId !== r.projectId || o.campaignId !== r.campaignId || o.site !== c.site) fail3(p + ".candidates.ownMeasurement", "foreign candidate measurement scope");
1938
+ if (Date.parse(o.asOf) > Date.parse(r.observedAt) || Date.parse(o.windowStart) < Date.parse(r.windowStart) || Date.parse(o.windowEnd) > Date.parse(r.windowEnd) || o.dataThrough !== null && Date.parse(o.dataThrough) > Date.parse(r.observedAt)) fail3(p + ".candidates.ownMeasurement", "outside the actual candidate evidence window");
1521
1939
  const aggregate = o.source === "provider" && RESONANCE_PROVIDER_METRIC_NAMES.includes(o.name);
1522
- if (aggregate ? o.countingUnit !== providerCountingUnit(o.name) || o.attributionModel !== "provider_reported" || o.goalRevision !== null && o.goalRevision !== r.goalRevision : o.source !== "first_party" || o.goalRevision !== r.goalRevision || o.countingUnit !== r.objective.countingUnit || o.attributionModel !== policy.measurementGuard.attributionModel) fail2(p + ".candidates.ownMeasurement", "preserve actual provider aggregate versus first-party cohort provenance");
1940
+ if (aggregate ? o.countingUnit !== providerCountingUnit(o.name) || o.attributionModel !== "provider_reported" || o.goalRevision !== null && o.goalRevision !== r.goalRevision : o.source !== "first_party" || o.goalRevision !== r.goalRevision || o.countingUnit !== r.objective.countingUnit || o.attributionModel !== policy.measurementGuard.attributionModel) fail3(p + ".candidates.ownMeasurement", "preserve actual provider aggregate versus first-party cohort provenance");
1523
1941
  }
1524
1942
  }
1525
1943
  return r;
1526
1944
  }
1527
1945
  function checkOptimizationEvidencePlan(e, plan) {
1528
1946
  const p = "optimizationEvidence";
1529
- if (e.projectId !== plan.projectId || e.campaignId !== plan.campaignId || e.preparedPlanId !== plan.id || e.reviewDigest !== plan.reviewDigest || canonical(e.objective) !== canonical(plan.definition.objective) || canonical(e.resolvedPolicy) !== canonical(plan.resolvedEvidencePolicy)) fail2(p + ".preparedPlanId", "requires the exact original prepared scope and policy");
1947
+ if (e.projectId !== plan.projectId || e.campaignId !== plan.campaignId || e.preparedPlanId !== plan.id || e.reviewDigest !== plan.reviewDigest || canonical(e.objective) !== canonical(plan.definition.objective) || canonical(e.resolvedPolicy) !== canonical(plan.resolvedEvidencePolicy)) fail3(p + ".preparedPlanId", "requires the exact original prepared scope and policy");
1530
1948
  if (!("evidenceKind" in e)) return;
1531
1949
  if (e.evidenceKind === "reported_cpql_sql_clock_v1") {
1532
1950
  const cohort = plan.resolvedQualificationRule?.cohort;
1533
- if (!cohort || Date.parse(e.windowStart) < Date.parse(cohort.startAt) || Date.parse(e.windowEnd) > Date.parse(cohort.endAt)) fail2(p + ".window", "outside the original frozen qualification cohort");
1951
+ if (!cohort || Date.parse(e.windowStart) < Date.parse(cohort.startAt) || Date.parse(e.windowEnd) > Date.parse(cohort.endAt)) fail3(p + ".window", "outside the original frozen qualification cohort");
1534
1952
  for (const c of e.channels) {
1535
1953
  const original = plan.definition.channels.find((x) => x.id === c.channelId), account = plan.accounts.find((x) => x.id === c.accountBindingId);
1536
- if (!original || !("provider" in original) || original.site !== c.site || original.accountBindingId !== c.accountBindingId || !account || c.observations.some((o) => o.timeZone !== account.timeZone)) fail2(p + ".channels", "reported evidence must retain original channel/account/site/timezone");
1954
+ if (!original || !("provider" in original) || original.site !== c.site || original.accountBindingId !== c.accountBindingId || !account || c.observations.some((o) => o.timeZone !== account.timeZone)) fail3(p + ".channels", "reported evidence must retain original channel/account/site/timezone");
1537
1955
  }
1538
1956
  return;
1539
1957
  }
1540
1958
  for (const observed of e.candidates) {
1541
1959
  const original = plan.definition.channels.find((c) => c.id === observed.channelId), preview2 = plan.channelPreviews.find((c) => c.channelId === observed.channelId);
1542
- if (!original || original.kind !== "meta_retargeting" || !preview2 || observed.site !== original.site || observed.accountBindingId !== original.accountBindingId || canonical(observed.cap) !== canonical(original.allocation) || canonical(observed.manifestRef) !== canonical(preview2.manifestRef)) fail2(p + ".candidates", "candidate projection differs from original channel and manifest");
1543
- if (canonical(observed.flight) !== canonical({ startAt: plan.definition.budget.startAt, endAt: plan.definition.budget.endAt, timeZone: plan.definition.budget.timeZone })) fail2(p + ".candidates.flight", "must retain the original budget flight");
1960
+ if (!original || original.kind !== "meta_retargeting" || !preview2 || observed.site !== original.site || observed.accountBindingId !== original.accountBindingId || canonical(observed.cap) !== canonical(original.allocation) || canonical(observed.manifestRef) !== canonical(preview2.manifestRef)) fail3(p + ".candidates", "candidate projection differs from original channel and manifest");
1961
+ if (canonical(observed.flight) !== canonical({ startAt: plan.definition.budget.startAt, endAt: plan.definition.budget.endAt, timeZone: plan.definition.budget.timeZone })) fail3(p + ".candidates.flight", "must retain the original budget flight");
1544
1962
  }
1545
1963
  }
1546
1964
  var matureOptimizationDecision = object2({
@@ -1559,9 +1977,9 @@ var matureOptimizationDecision = object2({
1559
1977
  state: choice2("actionable", "noop", "blocked"),
1560
1978
  decisionKind: choice2("observational_allocation", "experimental_promotion"),
1561
1979
  executionOrder: literal2("reduce_then_increase"),
1562
- reasonCodes: list2(text2(80), 50),
1563
- adjustments: list2(object2({ channelId: uuid, site, budgetMode: choice2("campaign_total", "average_daily", "lifetime", "daily"), providerUnitExponent: refine2(integer2(0, 6), (v, p) => {
1564
- if (![0, 2, 3, 6].includes(v)) fail2(p, "unsupported provider exponent");
1980
+ reasonCodes: list2(text3(80), 50),
1981
+ adjustments: list2(object2({ channelId: uuid, site, budgetMode: choice2("campaign_total", "average_daily", "lifetime", "daily"), providerUnitExponent: refine3(integer2(0, 6), (v, p) => {
1982
+ if (![0, 2, 3, 6].includes(v)) fail3(p, "unsupported provider exponent");
1565
1983
  }), providerMaxUnits: decimal, before: money, after: money, remoteSnapshotDigest: digest }), 100),
1566
1984
  createdAt: instant
1567
1985
  });
@@ -1586,7 +2004,7 @@ var finiteDecisionFields = {
1586
2004
  algorithmRevision: literal2("finite_meta_candidates_v1"),
1587
2005
  sourceRefs: list2(revision, 200),
1588
2006
  decisionKind: literal2("preapproved_candidate_operation"),
1589
- reasonCodes: list2(text2(80), 50, 1)
2007
+ reasonCodes: list2(text3(80), 50, 1)
1590
2008
  };
1591
2009
  var finiteOptimizationDecision = union2(
1592
2010
  object2({ ...finiteDecisionFields, state: literal2("actionable"), candidateActions: list2(finiteCandidateActionBody, 1, 1) }),
@@ -1595,77 +2013,77 @@ var finiteOptimizationDecision = union2(
1595
2013
  var optimizationDecision = union2(matureOptimizationDecision, finiteOptimizationDecision);
1596
2014
  function parseResonanceOptimizationDecision(v, evidence, preparedPlan) {
1597
2015
  const r = optimizationDecision.read(v, "optimizationDecision");
1598
- if (Date.parse(r.expiresAt) <= Date.parse(r.createdAt)) fail2("optimizationDecision.expiresAt", "must follow decision");
1599
- if (preparedPlan !== void 0 && evidence === void 0) fail2("optimizationDecision.evidenceRef", "plan binding requires actual evidence");
2016
+ if (Date.parse(r.expiresAt) <= Date.parse(r.createdAt)) fail3("optimizationDecision.expiresAt", "must follow decision");
2017
+ if (preparedPlan !== void 0 && evidence === void 0) fail3("optimizationDecision.evidenceRef", "plan binding requires actual evidence");
1600
2018
  if (evidence !== void 0) checkOptimizationDecisionEvidence(r, parseResonanceOptimizationEvidence(evidence, preparedPlan));
1601
2019
  if (r.decisionKind === "preapproved_candidate_operation") return r;
1602
2020
  unique(r.adjustments.map((c) => c.channelId), "optimizationDecision.adjustments");
1603
2021
  scoped(r, r.projectId, r.adjustments.map((c) => c.site), "optimizationDecision");
1604
- if (r.state !== "actionable" && r.adjustments.length) fail2("optimizationDecision.adjustments", "no effects for blocked/noop decision");
1605
- if (r.state === "actionable" && !r.adjustments.length) fail2("optimizationDecision.adjustments", "action requires exact adjustments");
2022
+ if (r.state !== "actionable" && r.adjustments.length) fail3("optimizationDecision.adjustments", "no effects for blocked/noop decision");
2023
+ if (r.state === "actionable" && !r.adjustments.length) fail3("optimizationDecision.adjustments", "action requires exact adjustments");
1606
2024
  for (const a of r.adjustments) {
1607
2025
  compareMoney(a.before, a.after);
1608
2026
  moneyToProviderUnits(a.before, { currency: a.before.currency, unitExponent: a.providerUnitExponent, maxUnits: a.providerMaxUnits });
1609
2027
  moneyToProviderUnits(a.after, { currency: a.after.currency, unitExponent: a.providerUnitExponent, maxUnits: a.providerMaxUnits });
1610
- if (r.adjustments[0].before.currency !== a.before.currency) fail2("optimizationDecision.adjustments", "currency mismatch");
2028
+ if (r.adjustments[0].before.currency !== a.before.currency) fail3("optimizationDecision.adjustments", "currency mismatch");
1611
2029
  }
1612
2030
  return r;
1613
2031
  }
1614
2032
  function checkOptimizationDecisionEvidence(d, e) {
1615
2033
  const p = "optimizationDecision";
1616
- if (d.projectId !== e.projectId || d.campaignId !== e.campaignId || d.preparedPlanId !== e.preparedPlanId || d.reviewDigest !== e.reviewDigest || d.policyDigest !== e.policyDigest || canonical(d.evidenceRef) !== canonical({ id: e.id, revision: e.revision, evidenceDigest: e.evidenceDigest })) fail2(p + ".evidenceRef", "must bind the exact original evidence and review");
1617
- if (Date.parse(d.createdAt) < Date.parse(e.observedAt)) fail2(p + ".createdAt", "precedes actual evidence");
2034
+ if (d.projectId !== e.projectId || d.campaignId !== e.campaignId || d.preparedPlanId !== e.preparedPlanId || d.reviewDigest !== e.reviewDigest || d.policyDigest !== e.policyDigest || canonical(d.evidenceRef) !== canonical({ id: e.id, revision: e.revision, evidenceDigest: e.evidenceDigest })) fail3(p + ".evidenceRef", "must bind the exact original evidence and review");
2035
+ if (Date.parse(d.createdAt) < Date.parse(e.observedAt)) fail3(p + ".createdAt", "precedes actual evidence");
1618
2036
  if (d.decisionKind !== "preapproved_candidate_operation") {
1619
- if ("evidenceKind" in e && e.evidenceKind !== "reported_cpql_sql_clock_v1") fail2(p + ".decisionKind", "mature decisions cannot borrow finite lifecycle evidence");
1620
- if ("evidenceKind" in e && e.evidenceKind === "reported_cpql_sql_clock_v1" ? d.algorithmRevision !== e.resolvedPolicy.algorithm || d.decisionKind !== "observational_allocation" : d.algorithmRevision === "reported_cpql_conserved_transfer_v1") fail2(p + ".algorithmRevision", "reported-cost decisions require the exact reported evidence policy");
2037
+ if ("evidenceKind" in e && e.evidenceKind !== "reported_cpql_sql_clock_v1") fail3(p + ".decisionKind", "mature decisions cannot borrow finite lifecycle evidence");
2038
+ if ("evidenceKind" in e && e.evidenceKind === "reported_cpql_sql_clock_v1" ? d.algorithmRevision !== e.resolvedPolicy.algorithm || d.decisionKind !== "observational_allocation" : d.algorithmRevision === "reported_cpql_conserved_transfer_v1") fail3(p + ".algorithmRevision", "reported-cost decisions require the exact reported evidence policy");
1621
2039
  if ("evidenceKind" in e && e.evidenceKind === "reported_cpql_sql_clock_v1") {
1622
2040
  const deadline = Math.min(Date.parse(e.observedAt), ...e.channels.flatMap((c) => [Date.parse(c.channelReportedCost.readClock.notBeforeAt), Date.parse(c.channelReportedCost.recordedAt)])) + e.resolvedPolicy.maxEvidenceAgeSeconds * 1e3;
1623
- if (Date.parse(d.createdAt) > deadline || Date.parse(d.expiresAt) > deadline) fail2(p + ".expiresAt", "outside original HTTP/database evidence freshness");
2041
+ if (Date.parse(d.createdAt) > deadline || Date.parse(d.expiresAt) > deadline) fail3(p + ".expiresAt", "outside original HTTP/database evidence freshness");
1624
2042
  const refs = e.channels.flatMap((c) => [c.channelReportedCost.observationId, c.outcomeSource.sourceRevision]);
1625
- if (refs.some((ref) => !d.sourceRefs.includes(ref))) fail2(p + ".sourceRefs", "requires immutable reported-cost and independent outcome sources");
2043
+ if (refs.some((ref) => !d.sourceRefs.includes(ref))) fail3(p + ".sourceRefs", "requires immutable reported-cost and independent outcome sources");
1626
2044
  }
1627
- if (d.algorithmRevision === "finite_meta_candidates_v1") fail2(p + ".algorithmRevision", "mature decisions cannot use the finite algorithm");
2045
+ if (d.algorithmRevision === "finite_meta_candidates_v1") fail3(p + ".algorithmRevision", "mature decisions cannot use the finite algorithm");
1628
2046
  return;
1629
2047
  }
1630
- if (!("evidenceKind" in e) || e.evidenceKind !== "finite_candidate_lifecycle_v1") fail2(p + ".decisionKind", "finite actions require finite lifecycle evidence");
2048
+ if (!("evidenceKind" in e) || e.evidenceKind !== "finite_candidate_lifecycle_v1") fail3(p + ".decisionKind", "finite actions require finite lifecycle evidence");
1631
2049
  const finite = e, policy = finite.resolvedPolicy;
1632
- if (Date.parse(d.createdAt) - Date.parse(finite.observedAt) > policy.measurementGuard.maxEvidenceAgeSeconds * 1e3 || Date.parse(d.expiresAt) > Date.parse(policy.expiresAt)) fail2(p + ".expiresAt", "outside current policy/evidence freshness");
2050
+ if (Date.parse(d.createdAt) - Date.parse(finite.observedAt) > policy.measurementGuard.maxEvidenceAgeSeconds * 1e3 || Date.parse(d.expiresAt) > Date.parse(policy.expiresAt)) fail3(p + ".expiresAt", "outside current policy/evidence freshness");
1633
2051
  for (const a of d.candidateActions) {
1634
- const c = finite.candidates.find((c2) => c2.channelId === a.channelId) ?? fail2(p + ".candidateActions", "unknown original candidate");
1635
- if (!policy.allowedActions.includes(a.action) || c.graphDigest !== a.graphDigest || c.nativeStateEvidenceRef === null || canonical(c.nativeStateEvidenceRef) !== canonical(a.nativeStateEvidenceRef)) fail2(p + ".candidateActions", "outside original candidate action/state evidence");
1636
- if (c.lifecycle === "unknown") fail2(p + ".candidateActions", "unknown state requires reconciliation");
2052
+ const c = finite.candidates.find((c2) => c2.channelId === a.channelId) ?? fail3(p + ".candidateActions", "unknown original candidate");
2053
+ if (!policy.allowedActions.includes(a.action) || c.graphDigest !== a.graphDigest || c.nativeStateEvidenceRef === null || canonical(c.nativeStateEvidenceRef) !== canonical(a.nativeStateEvidenceRef)) fail3(p + ".candidateActions", "outside original candidate action/state evidence");
2054
+ if (c.lifecycle === "unknown") fail3(p + ".candidateActions", "unknown state requires reconciliation");
1637
2055
  if (a.action === "pause_candidate") {
1638
- if (c.lifecycle !== "active") fail2(p + ".candidateActions", "pause requires the actual active original candidate");
2056
+ if (c.lifecycle !== "active") fail3(p + ".candidateActions", "pause requires the actual active original candidate");
1639
2057
  continue;
1640
2058
  }
1641
- if (finite.inventoryState !== "complete" || finite.candidates.some((c2) => c2.lifecycle === "unknown") || c.activationsObserved !== 0 || finite.candidates.filter((c2) => c2.lifecycle === "active").length >= policy.maxConcurrentCandidates) fail2(p + ".candidateActions", "unknown inventory, prior activation or concurrency blocks activation");
2059
+ if (finite.inventoryState !== "complete" || finite.candidates.some((c2) => c2.lifecycle === "unknown") || c.activationsObserved !== 0 || finite.candidates.filter((c2) => c2.lifecycle === "active").length >= policy.maxConcurrentCandidates) fail3(p + ".candidateActions", "unknown inventory, prior activation or concurrency blocks activation");
1642
2060
  const firstEligible = policy.selection.candidateOrder.find((id) => {
1643
2061
  const candidate = finite.candidates.find((c2) => c2.channelId === id), window = policy.selection.eligibilitySchedule.find((s) => s.channelId === id);
1644
2062
  const permittedLifecycle = candidate.lifecycle === "not_materialized" && policy.allowedActions.includes("materialize_and_activate") && candidate.nativeStateEvidenceRef !== null || candidate.lifecycle === "paused" && policy.allowedActions.includes("activate_held") && candidate.commitmentEvidenceRef !== null && candidate.nativeStateEvidenceRef !== null;
1645
2063
  return permittedLifecycle && candidate.activationsObserved === 0 && Date.parse(d.createdAt) >= Date.parse(window.notBefore) && Date.parse(d.createdAt) < Date.parse(window.notAfter);
1646
2064
  });
1647
- if (firstEligible !== c.channelId) fail2(p + ".candidateActions", "must retain the original fixed candidate order");
2065
+ if (firstEligible !== c.channelId) fail3(p + ".candidateActions", "must retain the original fixed candidate order");
1648
2066
  const schedule = policy.selection.eligibilitySchedule.find((s) => s.channelId === c.channelId);
1649
- if (Date.parse(d.createdAt) < Date.parse(schedule.notBefore) || Date.parse(d.createdAt) >= Date.parse(schedule.notAfter)) fail2(p + ".candidateActions", "outside original selection window");
1650
- if (a.action === "materialize_and_activate" && (c.lifecycle !== "not_materialized" || c.commitmentEvidenceRef !== null)) fail2(p + ".candidateActions", "new create requires original absence, not a borrowed hold");
1651
- if (a.action === "activate_held" && (c.lifecycle !== "paused" || !c.commitmentEvidenceRef || c.commitmentEvidenceRef.commitmentOperationId !== a.commitmentOperationId)) fail2(p + ".candidateActions", "held activation requires the exact original commitment reference");
1652
- if (compareMoney(c.cap, policy.totalExplorationCap) > 0) fail2(p + ".candidateActions", "original full cap exceeds reviewed exploration ceiling");
1653
- if (finite.trackingState !== "healthy" || c.trackingState !== "healthy" || c.coverageBasisPoints === null || c.coverageBasisPoints < policy.measurementGuard.minimumCoverageBasisPoints) fail2(p + ".candidateActions", "current required tracking coverage unavailable");
2067
+ if (Date.parse(d.createdAt) < Date.parse(schedule.notBefore) || Date.parse(d.createdAt) >= Date.parse(schedule.notAfter)) fail3(p + ".candidateActions", "outside original selection window");
2068
+ if (a.action === "materialize_and_activate" && (c.lifecycle !== "not_materialized" || c.commitmentEvidenceRef !== null)) fail3(p + ".candidateActions", "new create requires original absence, not a borrowed hold");
2069
+ if (a.action === "activate_held" && (c.lifecycle !== "paused" || !c.commitmentEvidenceRef || c.commitmentEvidenceRef.commitmentOperationId !== a.commitmentOperationId)) fail3(p + ".candidateActions", "held activation requires the exact original commitment reference");
2070
+ if (compareMoney(c.cap, policy.totalExplorationCap) > 0) fail3(p + ".candidateActions", "original full cap exceeds reviewed exploration ceiling");
2071
+ if (finite.trackingState !== "healthy" || c.trackingState !== "healthy" || c.coverageBasisPoints === null || c.coverageBasisPoints < policy.measurementGuard.minimumCoverageBasisPoints) fail3(p + ".candidateActions", "current required tracking coverage unavailable");
1654
2072
  for (const check of policy.measurementGuard.requiredChecks) {
1655
- if (check === "dedupe" && c.dedupeCheck !== "pass" || check === "qualification" && c.qualificationCheck !== "pass") fail2(p + ".candidateActions", "required source check unavailable");
1656
- if (["uncertainty", "assignment", "power"].includes(check)) fail2(p + ".candidateActions", "fixed exploration has no adopted measured/assignment decision policy");
2073
+ if (check === "dedupe" && c.dedupeCheck !== "pass" || check === "qualification" && c.qualificationCheck !== "pass") fail3(p + ".candidateActions", "required source check unavailable");
2074
+ if (["uncertainty", "assignment", "power"].includes(check)) fail3(p + ".candidateActions", "fixed exploration has no adopted measured/assignment decision policy");
1657
2075
  }
1658
2076
  }
1659
2077
  }
1660
2078
  var RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA = optimizationEvidence.schema;
1661
2079
  var RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA = optimizationDecision.schema;
1662
- var metaBrowserWitness = object2({ controlsRevision: text2(60, /^[A-Z][A-Z0-9_]*$/), policyRevision: revision, witnessId: uuid, assertedAt: instant });
2080
+ var metaBrowserWitness = object2({ controlsRevision: text3(60, /^[A-Z][A-Z0-9_]*$/), policyRevision: revision, witnessId: uuid, assertedAt: instant });
1663
2081
  var publicDestination = union2(
1664
- object2({ provider: literal2("google_ads"), id: uuid, tagId: text2(40, /^AW-[0-9]+$/) }),
2082
+ object2({ provider: literal2("google_ads"), id: uuid, tagId: text3(40, /^AW-[0-9]+$/) }),
1665
2083
  // browserWitness and tagManagerAttested are optional so configurations from before the Meta loader keep parsing; absent means no Meta browser loading.
1666
- object2({ provider: literal2("meta_ads"), id: uuid, pixelId: text2(40, /^[0-9]+$/), browserWitness: optional2(metaBrowserWitness), tagManagerAttested: optional2(bool) })
2084
+ object2({ provider: literal2("meta_ads"), id: uuid, pixelId: text3(40, /^[0-9]+$/), browserWitness: optional2(metaBrowserWitness), tagManagerAttested: optional2(bool) })
1667
2085
  );
1668
- var interestResource = object2({ ...scope, type: choice2("page", "article", "product", "listing"), id: text2(160, /^[a-zA-Z0-9._:-]+$/), revision });
2086
+ var interestResource = object2({ ...scope, type: choice2("page", "article", "product", "listing"), id: text3(160, /^[a-zA-Z0-9._:-]+$/), revision });
1669
2087
  var measurementConfig = object2({
1670
2088
  schemaVersion: literal2(1),
1671
2089
  ...scope,
@@ -1676,7 +2094,7 @@ var measurementConfig = object2({
1676
2094
  consentPolicy: object2({ mode: literal2("basic"), requiredPurposes: list2(purpose, 4, 1) }),
1677
2095
  destinations: list2(publicDestination, 10),
1678
2096
  // metaEligible is set by a person with owner or admin standing; absent means false. The browser never decides it.
1679
- resourceRules: list2(object2({ id: uuid, revision, site, resource: interestResource, path, interestKey: text2(100, /^[a-zA-Z0-9._:-]+$/), metaEligible: optional2(bool) }), 500)
2097
+ resourceRules: list2(object2({ id: uuid, revision, site, resource: interestResource, path, interestKey: text3(100, /^[a-zA-Z0-9._:-]+$/), metaEligible: optional2(bool) }), 500)
1680
2098
  });
1681
2099
  function parseResonanceMeasurementConfig(v) {
1682
2100
  const r = measurementConfig.read(v, "measurementConfig");
@@ -1684,7 +2102,7 @@ function parseResonanceMeasurementConfig(v) {
1684
2102
  unique(r.destinations.map((d) => d.id), "measurementConfig.destinations");
1685
2103
  unique(r.consentPolicy.requiredPurposes, "measurementConfig.consentPolicy.requiredPurposes");
1686
2104
  unique(r.resourceRules.map((rule) => rule.id), "measurementConfig.resourceRules");
1687
- if (r.destinations.length && ["ad_storage", "ad_user_data", "ad_personalization"].some((p) => !r.consentPolicy.requiredPurposes.includes(p))) fail2("measurementConfig.consentPolicy", "provider minimum purposes are mandatory");
2105
+ if (r.destinations.length && ["ad_storage", "ad_user_data", "ad_personalization"].some((p) => !r.consentPolicy.requiredPurposes.includes(p))) fail3("measurementConfig.consentPolicy", "provider minimum purposes are mandatory");
1688
2106
  return r;
1689
2107
  }
1690
2108
  function resonanceMeasurementConfigDigestInput(value) {
@@ -1692,7 +2110,7 @@ function resonanceMeasurementConfigDigestInput(value) {
1692
2110
  return canonical(semantic);
1693
2111
  }
1694
2112
  var clickIdentifierPattern = /^[^\s\u0000-\u001f\u007f-\u009f]+(?![\s\S])/;
1695
- var clickIdentifier = field2({ type: "string", minLength: 1, maxLength: 1024, pattern: clickIdentifierPattern.source }, (v, p) => typeof v === "string" && v.length <= 2048 && [...v].length <= 1024 && clickIdentifierPattern.test(v) ? v : fail2(p, "invalid click identifier"));
2113
+ var clickIdentifier = field2({ type: "string", minLength: 1, maxLength: 1024, pattern: clickIdentifierPattern.source }, (v, p) => typeof v === "string" && v.length <= 2048 && [...v].length <= 1024 && clickIdentifierPattern.test(v) ? v : fail3(p, "invalid click identifier"));
1696
2114
  var clickIdentifiersShape = union2(object2({ gclid: clickIdentifier }), object2({ gbraid: clickIdentifier }), object2({ wbraid: clickIdentifier }));
1697
2115
  var clickIdentifiers = field2(clickIdentifiersShape.schema, clickIdentifiersShape.read);
1698
2116
  var parseResonanceClickIdentifiers = (v) => clickIdentifiers.read(v, "clickIdentifiers");
@@ -1700,13 +2118,13 @@ var RESONANCE_CLICK_IDENTIFIERS_JSON_SCHEMA = clickIdentifiers.schema;
1700
2118
  var observedPathControl = /[\s\u0000-\u001f\u007f-\u009f]/;
1701
2119
  var observedPagePath = field2({ ...path.schema, allOf: [{ not: { pattern: observedPathControl.source } }] }, (v, p) => {
1702
2120
  const result = path.read(v, p);
1703
- if (observedPathControl.test(result)) fail2(p, "invalid observed path");
2121
+ if (observedPathControl.test(result)) fail3(p, "invalid observed path");
1704
2122
  return result;
1705
2123
  });
1706
2124
  var metaCookieShape = object2({ source: literal2(RESONANCE_WEBSITE_VISIT_PROFILE.source), fbp: optional2(clickIdentifier), fbc: optional2(clickIdentifier) });
1707
2125
  var metaCookieObservation = field2({ ...metaCookieShape.schema, anyOf: [{ required: ["fbp"] }, { required: ["fbc"] }] }, (v, p) => {
1708
2126
  const result = metaCookieShape.read(v, p);
1709
- if (!result.fbp && !result.fbc) fail2(p, "requires an actual reported cookie value");
2127
+ if (!result.fbp && !result.fbc) fail3(p, "requires an actual reported cookie value");
1710
2128
  return result;
1711
2129
  });
1712
2130
  var occurrenceShape = object2({
@@ -1732,17 +2150,17 @@ var occurrence = field2({ ...occurrenceShape.schema, allOf: [
1732
2150
  { if: { required: ["metaCookieObservation"] }, then: { required: ["pagePath"], properties: { kind: { const: "page_view" }, resourceRef: interestResource.schema } } }
1733
2151
  ] }, (v, p) => {
1734
2152
  const r = occurrenceShape.read(v, p);
1735
- if (r.clickIdentifiers && r.kind !== "page_view") fail2(p + ".clickIdentifiers", "requires page_view");
1736
- if (r.pagePath !== void 0 && r.kind !== "page_view" && r.kind !== "experiment_exposure") fail2(p + ".pagePath", "requires page_view or experiment_exposure");
1737
- if (r.metaCookieObservation && (r.kind !== "page_view" || r.pagePath === void 0 || !r.resourceRef)) fail2(p + ".metaCookieObservation", "requires the same page_view path and resource");
2153
+ if (r.clickIdentifiers && r.kind !== "page_view") fail3(p + ".clickIdentifiers", "requires page_view");
2154
+ if (r.pagePath !== void 0 && r.kind !== "page_view" && r.kind !== "experiment_exposure") fail3(p + ".pagePath", "requires page_view or experiment_exposure");
2155
+ if (r.metaCookieObservation && (r.kind !== "page_view" || r.pagePath === void 0 || !r.resourceRef)) fail3(p + ".metaCookieObservation", "requires the same page_view path and resource");
1738
2156
  return r;
1739
2157
  });
1740
2158
  function parseResonanceMeasurementOccurrence(v) {
1741
2159
  const r = occurrence.read(v, "occurrence");
1742
2160
  scoped(r, r.projectId, [r.site], "occurrence");
1743
2161
  unique(r.consentReceiptRefs.map((c) => c.purpose), "occurrence.consentReceiptRefs");
1744
- if (r.kind === "content_interest" && !r.resourceRef) fail2("occurrence.resourceRef", "content interest requires resource");
1745
- if (r.kind === "experiment_exposure" && !r.experiment) fail2("occurrence.experiment", "exposure requires assignment context");
2162
+ if (r.kind === "content_interest" && !r.resourceRef) fail3("occurrence.resourceRef", "content interest requires resource");
2163
+ if (r.kind === "experiment_exposure" && !r.experiment) fail3("occurrence.experiment", "exposure requires assignment context");
1746
2164
  return r;
1747
2165
  }
1748
2166
  var consentUpdate = object2({ schemaVersion: literal2(1), ...scope, configRevision: revision, policyRevision: revision, expectedConsentRevision: integer2(0), occurredAt: instant, idempotencyKey: operationKey, source: choice2("cmp", "user_preference"), purposes: list2(object2({ purpose, state: choice2("unknown", "granted", "denied", "withdrawn") }), 4, 1) });
@@ -1762,12 +2180,12 @@ function resonanceOptimizationDecisionDigestInput(v) {
1762
2180
  const { requestDigest: _digest, ...body } = parseResonanceOptimizationDecision(v);
1763
2181
  return canonical(body);
1764
2182
  }
1765
- var consentResult = object2({ subjectProof: text2(200, /^[a-zA-Z0-9_-]{32,}$/), expiresAt: instant, currentConsentRevision: integer2(1), receipts: list2(consent, 4, 4) });
2183
+ var consentResult = object2({ subjectProof: text3(200, /^[a-zA-Z0-9_-]{32,}$/), expiresAt: instant, currentConsentRevision: integer2(1), receipts: list2(consent, 4, 4) });
1766
2184
  function parseResonanceConsentResponse(v) {
1767
2185
  const r = consentResult.read(v, "consentResponse"), first = r.receipts[0];
1768
- if (r.receipts.some((c) => c.consentRevision !== r.currentConsentRevision)) fail2("consentResponse.receipts", "global consent revision mismatch");
2186
+ if (r.receipts.some((c) => c.consentRevision !== r.currentConsentRevision)) fail3("consentResponse.receipts", "global consent revision mismatch");
1769
2187
  unique(r.receipts.map((c) => c.purpose), "consentResult.receipts");
1770
- for (const c of r.receipts) if (c.projectId !== first.projectId || c.site !== first.site || c.configRevision !== first.configRevision || c.policyRevision !== first.policyRevision || c.visitorNamespace !== first.visitorNamespace) fail2("consentResult.receipts", "mixed consent subjects or scope");
2188
+ for (const c of r.receipts) if (c.projectId !== first.projectId || c.site !== first.site || c.configRevision !== first.configRevision || c.policyRevision !== first.policyRevision || c.visitorNamespace !== first.visitorNamespace) fail3("consentResult.receipts", "mixed consent subjects or scope");
1771
2189
  return r;
1772
2190
  }
1773
2191
  var occurrenceResult = object2({ eventId: uuid, accepted: literal2(true), replayed: bool, exposureId: nullable2(uuid) });
@@ -1788,12 +2206,12 @@ var audienceDraft = object2({
1788
2206
  schemaVersion: literal2(1),
1789
2207
  expectedRevision: optional2(integer2(1)),
1790
2208
  idempotencyKey: operationKey,
1791
- definition: object2({ name: text2(160), site, accountBindingId: uuid, resourceRuleId: uuid, excludedResourceRuleIds: list2(uuid, 50), retentionDays: integer2(1, 540), minDaysSinceVisit: optional2(integer2(1, 179)), policyRevision: revision, currentConsentPolicyRevision: revision })
2209
+ definition: object2({ name: text3(160), site, accountBindingId: uuid, resourceRuleId: uuid, excludedResourceRuleIds: list2(uuid, 50), retentionDays: integer2(1, 540), minDaysSinceVisit: optional2(integer2(1, 179)), policyRevision: revision, currentConsentPolicyRevision: revision })
1792
2210
  });
1793
2211
  function parseResonanceAudienceDraftSaveCommand(v) {
1794
2212
  const r = audienceDraft.read(v, "audienceDraftSave");
1795
2213
  unique(r.definition.excludedResourceRuleIds, "audienceDraftSave.definition.excludedResourceRuleIds");
1796
- if (r.definition.minDaysSinceVisit !== void 0 && r.definition.minDaysSinceVisit >= r.definition.retentionDays) fail2("audienceDraftSave.definition.minDaysSinceVisit", "must be shorter than the retention window");
2214
+ if (r.definition.minDaysSinceVisit !== void 0 && r.definition.minDaysSinceVisit >= r.definition.retentionDays) fail3("audienceDraftSave.definition.minDaysSinceVisit", "must be shorter than the retention window");
1797
2215
  return r;
1798
2216
  }
1799
2217
  var RESONANCE_AUDIENCE_DRAFT_SAVE_COMMAND_JSON_SCHEMA = audienceDraft.schema;
@@ -1802,20 +2220,20 @@ var experimentCreateField = field2(SIGNAL_EXPERIMENT_CREATE_JSON_SCHEMA, (v, p)
1802
2220
  try {
1803
2221
  return parseSignalExperimentCreate(v);
1804
2222
  } catch (error) {
1805
- return fail2(p, error instanceof Error ? error.message : "invalid experiment");
2223
+ return fail3(p, error instanceof Error ? error.message : "invalid experiment");
1806
2224
  }
1807
2225
  });
1808
2226
  var experimentUpdateField = field2(SIGNAL_EXPERIMENT_UPDATE_JSON_SCHEMA, (v, p) => {
1809
2227
  try {
1810
2228
  return parseSignalExperimentUpdate(v);
1811
2229
  } catch (error) {
1812
- return fail2(p, error instanceof Error ? error.message : "invalid experiment");
2230
+ return fail3(p, error instanceof Error ? error.message : "invalid experiment");
1813
2231
  }
1814
2232
  });
1815
2233
  var managedExperimentCreate = object2({ ...managedExperimentBase, experiment: experimentCreateField });
1816
2234
  var managedExperimentUpdate = object2({ ...managedExperimentBase, experiment: experimentUpdateField });
1817
2235
  var managedExperimentLifecycle = object2(managedExperimentBase);
1818
- var managedExperimentComplete = object2({ ...managedExperimentBase, winnerVariant: text2(80) });
2236
+ var managedExperimentComplete = object2({ ...managedExperimentBase, winnerVariant: text3(80) });
1819
2237
  var managedExperimentLink = object2({ ...managedExperimentBase, experimentId: uuid });
1820
2238
  var parseResonanceExperimentCreateCommand = (v) => managedExperimentCreate.read(v, "experimentCreateCommand");
1821
2239
  var parseResonanceExperimentUpdateCommand = (v) => managedExperimentUpdate.read(v, "experimentUpdateCommand");
@@ -1829,18 +2247,18 @@ var RESONANCE_EXPERIMENT_COMPLETE_COMMAND_JSON_SCHEMA = managedExperimentComplet
1829
2247
  var RESONANCE_EXPERIMENT_LINK_COMMAND_JSON_SCHEMA = managedExperimentLink.schema;
1830
2248
  var nativePageRevision = field2({ ...instant.schema, pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z(?![\\s\\S])" }, (v, p) => {
1831
2249
  const result = instant.read(v, p);
1832
- if (new Date(result).toISOString() !== result) fail2(p, "requires canonical UTC milliseconds");
2250
+ if (new Date(result).toISOString() !== result) fail3(p, "requires canonical UTC milliseconds");
1833
2251
  return result;
1834
2252
  });
1835
- var positiveRevision = text2(128, /^[1-9][0-9]*(?![\s\S])/);
1836
- var friendlyName = field2({ type: "string", minLength: 0, maxLength: 200 }, (v, p) => typeof v === "string" && [...v].length <= 200 ? v : fail2(p, "invalid friendly name"));
2253
+ var positiveRevision = text3(128, /^[1-9][0-9]*(?![\s\S])/);
2254
+ var friendlyName = field2({ type: "string", minLength: 0, maxLength: 200 }, (v, p) => typeof v === "string" && [...v].length <= 200 ? v : fail3(p, "invalid friendly name"));
1837
2255
  var setupConsentPolicyShape = object2({ mode: literal2("basic"), requiredPurposes: uniqueList(purpose, 4, 3) });
1838
2256
  var setupConsentPolicy = field2({ ...setupConsentPolicyShape.schema, allOf: [{ properties: { requiredPurposes: { allOf: ["ad_storage", "ad_user_data", "ad_personalization"].map((value) => ({ contains: { const: value } })) } } }] }, (input, p) => {
1839
2257
  const v = setupConsentPolicyShape.read(input, p);
1840
- for (const required of ["ad_storage", "ad_user_data", "ad_personalization"]) if (!v.requiredPurposes.includes(required)) fail2(p, "all advertising purpose requirements are mandatory");
2258
+ for (const required of ["ad_storage", "ad_user_data", "ad_personalization"]) if (!v.requiredPurposes.includes(required)) fail3(p, "all advertising purpose requirements are mandatory");
1841
2259
  return v;
1842
2260
  });
1843
- var measurementSave = refine2(object2({
2261
+ var measurementSave = refine3(object2({
1844
2262
  schemaVersion: literal2(1),
1845
2263
  site,
1846
2264
  expectedCampaignRevision: integer2(1),
@@ -1857,20 +2275,20 @@ var measurementSavedFields = { configurationRevision: integer2(1), configuration
1857
2275
  object2(measurementSavedFields);
1858
2276
  function checkMeasurementSaved(v, p) {
1859
2277
  const config = parseResonanceMeasurementConfig(v.configuration);
1860
- if (config.projectId !== v.projectId || config.site !== v.site) fail2(p + ".configuration", "configuration scope mismatch");
2278
+ if (config.projectId !== v.projectId || config.site !== v.site) fail3(p + ".configuration", "configuration scope mismatch");
1861
2279
  positiveRevision.read(config.configRevision, p + ".configuration.configRevision");
1862
2280
  positiveRevision.read(config.policyRevision, p + ".configuration.policyRevision");
1863
2281
  setupConsentPolicy.read(config.consentPolicy, p + ".configuration.consentPolicy");
1864
2282
  unique(v.pages.map((page2) => page2.pageId), p + ".pages");
1865
- if (v.pages.length !== config.resourceRules.length) fail2(p + ".pages", "must cover the exact native page rules");
2283
+ if (v.pages.length !== config.resourceRules.length) fail3(p + ".pages", "must cover the exact native page rules");
1866
2284
  for (const page2 of v.pages) {
1867
2285
  const rule = config.resourceRules.find((rule2) => rule2.id === page2.resourceRuleId);
1868
- if (page2.resourceRuleId !== page2.pageId || page2.resourceRuleRevision !== page2.evidenceDigest || !rule || rule.revision !== page2.evidenceDigest || rule.path !== page2.path || rule.interestKey !== page2.pageId || rule.resource.type !== "page" || rule.resource.id !== page2.pageId || rule.resource.revision !== page2.pageRevision) fail2(p + ".pages", "native page/resource/rule version mismatch");
2286
+ if (page2.resourceRuleId !== page2.pageId || page2.resourceRuleRevision !== page2.evidenceDigest || !rule || rule.revision !== page2.evidenceDigest || rule.path !== page2.path || rule.interestKey !== page2.pageId || rule.resource.type !== "page" || rule.resource.id !== page2.pageId || rule.resource.revision !== page2.pageRevision) fail3(p + ".pages", "native page/resource/rule version mismatch");
1869
2287
  }
1870
2288
  }
1871
- var measurementCurrent = refine2(union2(
2289
+ var measurementCurrent = refine3(union2(
1872
2290
  object2({ schemaVersion: literal2(1), kind: literal2("unconfigured"), ...scope, configurationRevision: literal2(0) }),
1873
- object2({ schemaVersion: literal2(1), kind: literal2("configured"), ...scope, ...measurementSavedFields, reasonCodes: uniqueList(text2(200), 100) })
2291
+ object2({ schemaVersion: literal2(1), kind: literal2("configured"), ...scope, ...measurementSavedFields, reasonCodes: uniqueList(text3(200), 100) })
1874
2292
  ), (v, p) => {
1875
2293
  if (v.kind === "configured") checkMeasurementSaved(v, p);
1876
2294
  });
@@ -1879,8 +2297,8 @@ var measurementSnapshotShape = object2(measurementSnapshotFields);
1879
2297
  function checkMeasurementSnapshot(v, p) {
1880
2298
  checkMeasurementSaved({ ...v, saveOperationId: v.operationId }, p);
1881
2299
  }
1882
- var measurementSnapshot = refine2(measurementSnapshotShape, checkMeasurementSnapshot);
1883
- var measurementSaveResponse = refine2(object2({ ...measurementSnapshotFields, replayed: bool }), checkMeasurementSnapshot);
2300
+ var measurementSnapshot = refine3(measurementSnapshotShape, checkMeasurementSnapshot);
2301
+ var measurementSaveResponse = refine3(object2({ ...measurementSnapshotFields, replayed: bool }), checkMeasurementSnapshot);
1884
2302
  var parseResonanceMeasurementConfigurationCurrent = (v) => measurementCurrent.read(v, "measurementConfigurationCurrent");
1885
2303
  var parseResonanceMeasurementConfigurationSnapshot = (v) => measurementSnapshot.read(v, "measurementConfigurationSnapshot");
1886
2304
  var parseResonanceMeasurementConfigurationSaveResponse = (v) => measurementSaveResponse.read(v, "measurementConfigurationSaveResponse");
@@ -1888,9 +2306,9 @@ var measurementProjectionContext = object2({ projectId: uuid, current: measureme
1888
2306
  function projectResonanceMeasurementConfiguration(value, context) {
1889
2307
  const command2 = parseResonanceMeasurementConfigurationSaveCommand(value), actual = measurementProjectionContext.read(context, "measurementConfigurationProjection");
1890
2308
  const current = parseResonanceMeasurementConfigurationCurrent(actual.current);
1891
- if (current.projectId !== actual.projectId || current.site !== command2.site || current.configurationRevision !== command2.expectedConfigurationRevision) fail2("measurementConfigurationProjection.current", "scope or configuration CAS mismatch");
2309
+ if (current.projectId !== actual.projectId || current.site !== command2.site || current.configurationRevision !== command2.expectedConfigurationRevision) fail3("measurementConfigurationProjection.current", "scope or configuration CAS mismatch");
1892
2310
  unique(actual.pages.map((page2) => page2.pageId), "measurementConfigurationProjection.pages");
1893
- if (actual.pages.length !== command2.pages.length || actual.pages.some((page2) => !command2.pages.some((selected) => selected.pageId === page2.pageId && selected.observedRevision === page2.pageRevision && selected.observedDigest === page2.evidenceDigest))) fail2("measurementConfigurationProjection.pages", "requires the exact selected current native page evidence");
2311
+ if (actual.pages.length !== command2.pages.length || actual.pages.some((page2) => !command2.pages.some((selected) => selected.pageId === page2.pageId && selected.observedRevision === page2.pageRevision && selected.observedDigest === page2.evidenceDigest))) fail3("measurementConfigurationProjection.pages", "requires the exact selected current native page evidence");
1894
2312
  const pages = [...actual.pages].sort((a, b) => a.pageId < b.pageId ? -1 : a.pageId > b.pageId ? 1 : 0).map((page2) => ({ ...page2, resourceRuleId: page2.pageId, resourceRuleRevision: page2.evidenceDigest }));
1895
2313
  const consentPolicy = { ...command2.consentPolicy, requiredPurposes: [...command2.consentPolicy.requiredPurposes].sort() };
1896
2314
  const previous = current.kind === "configured" ? current.configuration : null;
@@ -1919,10 +2337,10 @@ var RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA = measurementSa
1919
2337
  var RESONANCE_MEASUREMENT_CONFIGURATION_CURRENT_JSON_SCHEMA = measurementCurrent.schema;
1920
2338
  var RESONANCE_MEASUREMENT_CONFIGURATION_SNAPSHOT_JSON_SCHEMA = measurementSnapshot.schema;
1921
2339
  var RESONANCE_MEASUREMENT_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA = measurementSaveResponse.schema;
1922
- var nativeAudienceId = text2(160, /^[0-9]+(?![\s\S])/);
2340
+ var nativeAudienceId = text3(160, /^[0-9]+(?![\s\S])/);
1923
2341
  var RESONANCE_META_DATASET_NAME_MAX_LENGTH = 160;
1924
- var metaDatasetName = refine2(text2(RESONANCE_META_DATASET_NAME_MAX_LENGTH), (value, at) => {
1925
- if (!value.trim() || value !== value.trim() || /[\x00-\x1f\x7f]/.test(value)) fail2(at, "requires a trimmed dataset name without control characters");
2342
+ var metaDatasetName = refine3(text3(RESONANCE_META_DATASET_NAME_MAX_LENGTH), (value, at) => {
2343
+ if (!value.trim() || value !== value.trim() || /[\x00-\x1f\x7f]/.test(value)) fail3(at, "requires a trimmed dataset name without control characters");
1926
2344
  });
1927
2345
  var parseResonanceMetaDatasetName = (value) => metaDatasetName.read(value, "metaDatasetName");
1928
2346
  var metaDatasetExistingSelection = object2({ kind: literal2("existing"), externalId: nativeAudienceId });
@@ -1968,7 +2386,7 @@ var RESONANCE_META_DATASET_SETUP_REVIEW_JSON_SCHEMA = metaDatasetSetupReview.sch
1968
2386
  var metaDatasetSetupFirstOutcome = object2({
1969
2387
  admission: choice2("accepted", "rejected", "unknown"),
1970
2388
  externalId: nullable2(nativeAudienceId),
1971
- providerRequestId: nullable2(text2(200)),
2389
+ providerRequestId: nullable2(text3(200)),
1972
2390
  providerRequestDigest: digest
1973
2391
  });
1974
2392
  var metaSetupVerificationFields = {
@@ -1989,39 +2407,39 @@ var metaSetupReceiptFields = {
1989
2407
  requestDigest: digest,
1990
2408
  status: choice2("pending", "selected", "created_unverified", "verified", "rejected", "uncertain", "cancelled"),
1991
2409
  firstOutcome: nullable2(metaDatasetSetupFirstOutcome),
1992
- reasonCodes: uniqueList(text2(80, /^[a-z][a-z0-9_]*$/), 30)
2410
+ reasonCodes: uniqueList(text3(80, /^[a-z][a-z0-9_]*$/), 30)
1993
2411
  };
1994
2412
  function checkMetaSetupReceipt(value, at, resource2) {
1995
2413
  const { status, firstOutcome, currentVerification } = value;
1996
2414
  if (firstOutcome && firstOutcome.admission === "accepted" !== (firstOutcome.externalId !== null)) {
1997
- fail2(at + ".firstOutcome", "requires the original provider ID exactly when creation was accepted");
2415
+ fail3(at + ".firstOutcome", "requires the original provider ID exactly when creation was accepted");
1998
2416
  }
1999
2417
  switch (status) {
2000
2418
  case "pending":
2001
2419
  case "cancelled":
2002
- if (firstOutcome || currentVerification) fail2(at, "cannot carry a creation outcome or verification");
2420
+ if (firstOutcome || currentVerification) fail3(at, "cannot carry a creation outcome or verification");
2003
2421
  break;
2004
2422
  case "selected":
2005
- if (firstOutcome || !currentVerification) fail2(at, "requires verified existing selection without a creation outcome");
2423
+ if (firstOutcome || !currentVerification) fail3(at, "requires verified existing selection without a creation outcome");
2006
2424
  break;
2007
2425
  case "created_unverified":
2008
- if (firstOutcome?.admission !== "accepted" || currentVerification) fail2(at, "requires accepted creation and no verified readback");
2426
+ if (firstOutcome?.admission !== "accepted" || currentVerification) fail3(at, "requires accepted creation and no verified readback");
2009
2427
  break;
2010
2428
  case "verified":
2011
2429
  if (firstOutcome?.admission !== "accepted" || !currentVerification || firstOutcome.externalId !== currentVerification.externalId) {
2012
- fail2(at, `requires verified readback of the exact created ${resource2}`);
2430
+ fail3(at, `requires verified readback of the exact created ${resource2}`);
2013
2431
  }
2014
2432
  break;
2015
2433
  case "rejected":
2016
- if (firstOutcome?.admission !== "rejected") fail2(at, "requires the original rejection");
2434
+ if (firstOutcome?.admission !== "rejected") fail3(at, "requires the original rejection");
2017
2435
  break;
2018
2436
  case "uncertain":
2019
- if (firstOutcome?.admission !== "unknown" || currentVerification) fail2(at, `requires an unknown outcome without an attributable ${resource2}`);
2437
+ if (firstOutcome?.admission !== "unknown" || currentVerification) fail3(at, `requires an unknown outcome without an attributable ${resource2}`);
2020
2438
  break;
2021
2439
  }
2022
2440
  }
2023
2441
  var metaSetupReceiptState = object2({ ...metaSetupReceiptFields, currentVerification: nullable2(metaDatasetSetupVerification) });
2024
- var metaDatasetSetupReceipt = refine2(metaSetupReceiptState, (value, at) => checkMetaSetupReceipt(value, at, "dataset"));
2442
+ var metaDatasetSetupReceipt = refine3(metaSetupReceiptState, (value, at) => checkMetaSetupReceipt(value, at, "dataset"));
2025
2443
  var parseResonanceMetaDatasetSetupReceipt = (value) => metaDatasetSetupReceipt.read(value, "metaDatasetSetupReceipt");
2026
2444
  var RESONANCE_META_DATASET_SETUP_RECEIPT_JSON_SCHEMA = metaDatasetSetupReceipt.schema;
2027
2445
  var metaAudienceSetupResource = object2({ externalId: nativeAudienceId, resourceRevision: revision });
@@ -2047,7 +2465,7 @@ var metaAudienceSetupPrepareFields = {
2047
2465
  var metaAudienceSetupPrepare = object2(metaAudienceSetupPrepareFields);
2048
2466
  var parseResonanceMetaAudienceSetupPrepareRequest = (value) => metaAudienceSetupPrepare.read(value, "metaAudienceSetupPrepare");
2049
2467
  var RESONANCE_META_AUDIENCE_SETUP_PREPARE_REQUEST_JSON_SCHEMA = metaAudienceSetupPrepare.schema;
2050
- var metaAudienceSetupIntent = refine2(object2({
2468
+ var metaAudienceSetupIntent = refine3(object2({
2051
2469
  ...metaAudienceSetupPrepareFields,
2052
2470
  ...metaSetupOwnerFields,
2053
2471
  audienceRuleRef: audience,
@@ -2060,11 +2478,11 @@ var metaAudienceSetupIntent = refine2(object2({
2060
2478
  expiresAt: instant
2061
2479
  }), (value, at) => {
2062
2480
  const { audienceRule, audienceRuleRef, resourceRuleRef, excludedResourceRuleRefs, measurementConfigRef: measurementConfigRef2 } = value;
2063
- if (audienceRuleRef.projectId !== value.projectId || audienceRuleRef.site !== value.site || audienceRuleRef.id !== audienceRule.id || audienceRuleRef.revision !== audienceRule.revision || audienceRuleRef.policyRevision !== measurementConfigRef2.policyRevision) fail2(at + ".audienceRuleRef", "requires the exact scoped audience and policy revision");
2481
+ if (audienceRuleRef.projectId !== value.projectId || audienceRuleRef.site !== value.site || audienceRuleRef.id !== audienceRule.id || audienceRuleRef.revision !== audienceRule.revision || audienceRuleRef.policyRevision !== measurementConfigRef2.policyRevision) fail3(at + ".audienceRuleRef", "requires the exact scoped audience and policy revision");
2064
2482
  const excludedIds = excludedResourceRuleRefs.map((ref) => ref.id);
2065
2483
  unique(excludedIds, at + ".excludedResourceRuleRefs");
2066
2484
  if (excludedIds.includes(resourceRuleRef.id) || canonical([...audienceRuleRef.exclusionRuleIds].sort()) !== canonical(excludedIds.sort())) {
2067
- fail2(at + ".excludedResourceRuleRefs", "requires the exact exclusions disjoint from the positive rule");
2485
+ fail3(at + ".excludedResourceRuleRefs", "requires the exact exclusions disjoint from the positive rule");
2068
2486
  }
2069
2487
  checkAudienceBand(audienceRuleRef, "meta_ads", at + ".audienceRuleRef");
2070
2488
  });
@@ -2081,14 +2499,14 @@ var metaAudienceSetupVerification = object2({
2081
2499
  audienceSpecDigest: digest,
2082
2500
  retentionDays: integer2(1, META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS)
2083
2501
  });
2084
- var metaAudienceSetupReceipt = refine2(object2({
2502
+ var metaAudienceSetupReceipt = refine3(object2({
2085
2503
  ...metaSetupReceiptFields,
2086
2504
  currentVerification: nullable2(metaAudienceSetupVerification)
2087
2505
  }), (value, at) => checkMetaSetupReceipt(value, at, "audience"));
2088
2506
  var parseResonanceMetaAudienceSetupReceipt = (value) => metaAudienceSetupReceipt.read(value, "metaAudienceSetupReceipt");
2089
2507
  var resonanceMetaAudienceSetupReceiptDigestInput = (value) => canonical(parseResonanceMetaAudienceSetupReceipt(value));
2090
2508
  var RESONANCE_META_AUDIENCE_SETUP_RECEIPT_JSON_SCHEMA = metaAudienceSetupReceipt.schema;
2091
- var websiteVisitSetupGrantProof = refine2(object2({
2509
+ var websiteVisitSetupGrantProof = refine3(object2({
2092
2510
  schemaVersion: literal2(1),
2093
2511
  grantOperationId: uuid,
2094
2512
  audienceOperationId: uuid,
@@ -2104,10 +2522,10 @@ var websiteVisitSetupGrantProof = refine2(object2({
2104
2522
  accountBindingId: uuid,
2105
2523
  audience: metaAudienceSetupVerification
2106
2524
  }), (value, at) => {
2107
- if (value.grantOperationId.toLowerCase() === value.audienceOperationId.toLowerCase()) fail2(at + ".grantOperationId", "requires a distinct native grant operation");
2108
- if (Date.parse(value.audience.observedAt) > Date.parse(value.activatedAt) || Date.parse(value.activatedAt) >= Date.parse(value.expiresAt)) fail2(at, "requires verification by activation and a nonempty grant window");
2525
+ if (value.grantOperationId.toLowerCase() === value.audienceOperationId.toLowerCase()) fail3(at + ".grantOperationId", "requires a distinct native grant operation");
2526
+ if (Date.parse(value.audience.observedAt) > Date.parse(value.activatedAt) || Date.parse(value.activatedAt) >= Date.parse(value.expiresAt)) fail3(at, "requires verification by activation and a nonempty grant window");
2109
2527
  });
2110
- var websiteVisitSetupGrantStatus = refine2(object2({
2528
+ var websiteVisitSetupGrantStatus = refine3(object2({
2111
2529
  proof: websiteVisitSetupGrantProof,
2112
2530
  status: choice2("active", "revoked", "expired", "invalidated"),
2113
2531
  checkedAt: instant,
@@ -2115,14 +2533,14 @@ var websiteVisitSetupGrantStatus = refine2(object2({
2115
2533
  reasonCodes: metaSetupReceiptFields.reasonCodes
2116
2534
  }), (value, at) => {
2117
2535
  const checked = Date.parse(value.checkedAt), activated = Date.parse(value.proof.activatedAt), expires = Date.parse(value.proof.expiresAt);
2118
- if (checked < activated) fail2(at + ".checkedAt", "cannot predate activation");
2536
+ if (checked < activated) fail3(at + ".checkedAt", "cannot predate activation");
2119
2537
  if (value.status === "revoked") {
2120
2538
  if (!value.revokedAt || Date.parse(value.revokedAt) < activated || Date.parse(value.revokedAt) > checked) {
2121
- fail2(at + ".revokedAt", "requires the recorded revocation between activation and observation");
2539
+ fail3(at + ".revokedAt", "requires the recorded revocation between activation and observation");
2122
2540
  }
2123
- } else if (value.revokedAt) fail2(at + ".revokedAt", "requires revoked status");
2541
+ } else if (value.revokedAt) fail3(at + ".revokedAt", "requires revoked status");
2124
2542
  if (value.status === "active" && checked >= expires || value.status === "expired" && checked < expires) {
2125
- fail2(at + ".status", "must agree with the original expiry");
2543
+ fail3(at + ".status", "must agree with the original expiry");
2126
2544
  }
2127
2545
  });
2128
2546
  var parseResonanceWebsiteVisitSetupGrantProof = (value) => websiteVisitSetupGrantProof.read(value, "websiteVisitSetupGrantProof");
@@ -2134,23 +2552,23 @@ function checkMetaAudienceSetupStatus({ receipt: receipt2, grant }, at) {
2134
2552
  if (!grant) return;
2135
2553
  const { proof } = grant;
2136
2554
  if (receipt2.status !== "selected" && receipt2.status !== "verified" || !receipt2.currentVerification || canonical(receipt2.currentVerification) !== canonical(proof.audience)) {
2137
- fail2(at + ".grant", "requires the same verified audience witness as the setup receipt");
2555
+ fail3(at + ".grant", "requires the same verified audience witness as the setup receipt");
2138
2556
  }
2139
2557
  if (proof.audienceOperationId !== receipt2.operationId || proof.requestDigest !== receipt2.requestDigest || proof.projectId !== receipt2.projectId || proof.campaignId !== receipt2.campaignId || proof.site !== receipt2.site || proof.accountBindingId !== receipt2.accountBindingId) {
2140
- fail2(at + ".grant", "requires the grant linked to this exact setup operation");
2558
+ fail3(at + ".grant", "requires the grant linked to this exact setup operation");
2141
2559
  }
2142
2560
  }
2143
2561
  var metaAudienceSetupStatusShape = object2(metaAudienceSetupStatusFields);
2144
- var metaAudienceSetupStatus = refine2(metaAudienceSetupStatusShape, checkMetaAudienceSetupStatus);
2562
+ var metaAudienceSetupStatus = refine3(metaAudienceSetupStatusShape, checkMetaAudienceSetupStatus);
2145
2563
  var parseResonanceMetaAudienceSetupStatus = (value) => metaAudienceSetupStatus.read(value, "metaAudienceSetupStatus");
2146
2564
  var RESONANCE_META_AUDIENCE_SETUP_STATUS_JSON_SCHEMA = metaAudienceSetupStatus.schema;
2147
- var metaAudienceSetupListItem = refine2(object2({ ledgerActionId: uuid, ...metaAudienceSetupStatusFields }), (item, at) => {
2565
+ var metaAudienceSetupListItem = refine3(object2({ ledgerActionId: uuid, ...metaAudienceSetupStatusFields }), (item, at) => {
2148
2566
  checkMetaAudienceSetupStatus(item, at);
2149
2567
  if (item.grant && item.grant.proof.approvalActionId.toLowerCase() !== item.ledgerActionId.toLowerCase()) {
2150
- fail2(at + ".ledgerActionId", "requires the original approval linked to this grant");
2568
+ fail3(at + ".ledgerActionId", "requires the original approval linked to this grant");
2151
2569
  }
2152
2570
  });
2153
- var metaAudienceSetupList = refine2(object2({
2571
+ var metaAudienceSetupList = refine3(object2({
2154
2572
  items: list2(metaAudienceSetupListItem, 25),
2155
2573
  nextCursor: nullable2(uuid)
2156
2574
  }), ({ items }, at) => {
@@ -2158,18 +2576,18 @@ var metaAudienceSetupList = refine2(object2({
2158
2576
  });
2159
2577
  var parseResonanceMetaAudienceSetupList = (value) => metaAudienceSetupList.read(value, "metaAudienceSetupList");
2160
2578
  var RESONANCE_META_AUDIENCE_SETUP_LIST_JSON_SCHEMA = metaAudienceSetupList.schema;
2161
- var websiteVisitSetupGrant = refine2(object2({
2579
+ var websiteVisitSetupGrant = refine3(object2({
2162
2580
  proof: websiteVisitSetupGrantProof,
2163
2581
  intent: metaAudienceSetupIntent
2164
2582
  }), (value, at) => {
2165
2583
  const { proof, intent } = value;
2166
2584
  const { audience: witness } = proof;
2167
- if (intent.feed.kind !== "enable" || Date.parse(intent.feed.expiresAt) !== Date.parse(proof.expiresAt) || Date.parse(proof.activatedAt) >= Date.parse(intent.expiresAt)) fail2(at, "requires the explicit original opt-in and an unexpired setup approval");
2585
+ if (intent.feed.kind !== "enable" || Date.parse(intent.feed.expiresAt) !== Date.parse(proof.expiresAt) || Date.parse(proof.activatedAt) >= Date.parse(intent.expiresAt)) fail3(at, "requires the explicit original opt-in and an unexpired setup approval");
2168
2586
  if (proof.projectId !== intent.projectId || proof.campaignId !== intent.campaignId || proof.site !== intent.site || proof.accountBindingId !== intent.accountBindingId || witness.externalAccountId !== intent.externalAccountId || witness.businessId !== intent.businessId || witness.datasetExternalId !== intent.dataset.externalId || witness.datasetResourceRevision !== intent.dataset.resourceRevision || witness.audienceSpecDigest !== intent.audienceSpecDigest || witness.retentionDays !== intent.audienceRuleRef.retentionDays) {
2169
- fail2(at, "requires the exact original scope and verified destination");
2587
+ fail3(at, "requires the exact original scope and verified destination");
2170
2588
  }
2171
2589
  if (intent.selection.kind === "existing" && (witness.externalId !== intent.selection.externalId || witness.resourceRevision !== intent.selection.resourceRevision)) {
2172
- fail2(at, "requires verification of the exact existing audience");
2590
+ fail3(at, "requires verification of the exact existing audience");
2173
2591
  }
2174
2592
  });
2175
2593
  var parseResonanceWebsiteVisitSetupGrant = (value) => websiteVisitSetupGrant.read(value, "websiteVisitSetupGrant");
@@ -2197,7 +2615,7 @@ function resonanceWebsiteVisitSetupEventTime(value, context) {
2197
2615
  return websiteVisitEventTime(input, Date.parse(actual.activatedAt), Date.parse(actual.expiresAt), Date.parse(actual.now));
2198
2616
  }
2199
2617
  var nativeAudienceRef = object2({ externalId: nativeAudienceId, revision: digest });
2200
- var metaSave = refine2(object2({
2618
+ var metaSave = refine3(object2({
2201
2619
  schemaVersion: literal2(1),
2202
2620
  expectedCampaignRevision: integer2(1),
2203
2621
  expectedConfigurationRevision: integer2(0),
@@ -2221,7 +2639,7 @@ var metaMaterialFields = {
2221
2639
  configurationRevision: integer2(1),
2222
2640
  saveOperationId: uuid,
2223
2641
  channel: meta,
2224
- account: object2({ id: uuid, externalId: text2(160), name: nullable2(friendlyName) }),
2642
+ account: object2({ id: uuid, externalId: text3(160), name: nullable2(friendlyName) }),
2225
2643
  datasetName: nullable2(friendlyName),
2226
2644
  pageName: nullable2(friendlyName),
2227
2645
  instagramName: nullable2(friendlyName),
@@ -2233,34 +2651,34 @@ var metaMaterialFields = {
2233
2651
  object2(metaMaterialFields);
2234
2652
  function checkMetaMaterial(v, p) {
2235
2653
  scoped(v, v.projectId, [v.site], p);
2236
- if (v.channel.id !== v.channelId || v.channel.accountBindingId !== v.account.id || v.matchingProfileRef.id !== v.saveOperationId || v.matchingProfileRef.revision !== v.configurationRevision) fail2(p, "original channel/account/profile receipt mismatch");
2237
- if (!v.channel.instagramRef && v.instagramName !== null) fail2(p + ".instagramName", "absent original Instagram identity requires null");
2654
+ if (v.channel.id !== v.channelId || v.channel.accountBindingId !== v.account.id || v.matchingProfileRef.id !== v.saveOperationId || v.matchingProfileRef.revision !== v.configurationRevision) fail3(p, "original channel/account/profile receipt mismatch");
2655
+ if (!v.channel.instagramRef && v.instagramName !== null) fail3(p + ".instagramName", "absent original Instagram identity requires null");
2238
2656
  unique(v.rules.map((rule) => rule.id), p + ".rules");
2239
2657
  unique(v.audiences.map((a) => a.audienceRuleRef.id), p + ".audiences");
2240
2658
  unique(v.channel.audienceRuleRefs.map((a) => a.id), p + ".channel.audienceRuleRefs");
2241
- if (v.audiences.length !== v.channel.audienceRuleRefs.length) fail2(p + ".audiences", "must cover exactly the original logical audiences");
2659
+ if (v.audiences.length !== v.channel.audienceRuleRefs.length) fail3(p + ".audiences", "must cover exactly the original logical audiences");
2242
2660
  checkMetaAudienceBands(v.channel, p + ".channel.audienceRuleRefs");
2243
2661
  for (const a of v.audiences) {
2244
- if (!v.channel.audienceRuleRefs.some((ref) => canonical(ref) === canonical(a.audienceRuleRef))) fail2(p + ".audiences", "original logical audience version mismatch");
2662
+ if (!v.channel.audienceRuleRefs.some((ref) => canonical(ref) === canonical(a.audienceRuleRef))) fail3(p + ".audiences", "original logical audience version mismatch");
2245
2663
  unique(a.excludedResourceRuleRefs.map((ref) => ref.id), p + ".audiences.excludedResourceRuleRefs");
2246
2664
  unique(a.audienceRuleRef.exclusionRuleIds, p + ".audiences.audienceRuleRef.exclusionRuleIds");
2247
- if (canonical([...a.audienceRuleRef.exclusionRuleIds].sort()) !== canonical(a.excludedResourceRuleRefs.map((ref) => ref.id).sort()) || a.excludedResourceRuleRefs.some((ref) => ref.id === a.resourceRuleRef.id)) fail2(p + ".audiences", "positive/excluded resource scope mismatch");
2248
- for (const selected of [a.resourceRuleRef, ...a.excludedResourceRuleRefs]) if (!v.rules.some((rule) => rule.id === selected.id && rule.revision === selected.revision)) fail2(p + ".audiences", "resource rule version mismatch");
2249
- if (a.selection.mode === "admitted_setup" && a.selection.setup.localOutputKey !== `audience:${a.audienceRuleRef.id}:${a.audienceRuleRef.revision}`) fail2(p + ".audiences.selection.setup.localOutputKey", "must retain the actual original SDK creator key");
2665
+ if (canonical([...a.audienceRuleRef.exclusionRuleIds].sort()) !== canonical(a.excludedResourceRuleRefs.map((ref) => ref.id).sort()) || a.excludedResourceRuleRefs.some((ref) => ref.id === a.resourceRuleRef.id)) fail3(p + ".audiences", "positive/excluded resource scope mismatch");
2666
+ for (const selected of [a.resourceRuleRef, ...a.excludedResourceRuleRefs]) if (!v.rules.some((rule) => rule.id === selected.id && rule.revision === selected.revision)) fail3(p + ".audiences", "resource rule version mismatch");
2667
+ if (a.selection.mode === "admitted_setup" && a.selection.setup.localOutputKey !== `audience:${a.audienceRuleRef.id}:${a.audienceRuleRef.revision}`) fail3(p + ".audiences.selection.setup.localOutputKey", "must retain the actual original SDK creator key");
2250
2668
  }
2251
2669
  }
2252
- var metaSnapshot = refine2(object2({ ...metaMaterialFields, configurationDigest: digest }), checkMetaMaterial);
2670
+ var metaSnapshot = refine3(object2({ ...metaMaterialFields, configurationDigest: digest }), checkMetaMaterial);
2253
2671
  var parseResonanceMetaConfigurationSnapshot = (v) => metaSnapshot.read(v, "metaConfigurationSnapshot");
2254
- var metaDigestValue = refine2(object2({ ...metaMaterialFields, configurationDigest: optional2(digest) }), checkMetaMaterial);
2672
+ var metaDigestValue = refine3(object2({ ...metaMaterialFields, configurationDigest: optional2(digest) }), checkMetaMaterial);
2255
2673
  function resonanceMetaConfigurationDigestInput(v) {
2256
2674
  const { configurationDigest: _self, ...material } = metaDigestValue.read(v, "metaConfigurationDigestInput");
2257
2675
  return canonical(material);
2258
2676
  }
2259
- var metaCurrentMetadata = object2({ currentCampaignRevision: integer2(1), currentDefinitionDigest: digest, observedAt: instant, expiresAt: nullable2(instant), reasonCodes: uniqueList(text2(200), 100), pendingRequirements: uniqueList(text2(200), 100) });
2677
+ var metaCurrentMetadata = object2({ currentCampaignRevision: integer2(1), currentDefinitionDigest: digest, observedAt: instant, expiresAt: nullable2(instant), reasonCodes: uniqueList(text3(200), 100), pendingRequirements: uniqueList(text3(200), 100) });
2260
2678
  function metaReviewable(snapshot, metadata) {
2261
2679
  return metadata.currentCampaignRevision >= snapshot.campaignRevision && metadata.currentDefinitionDigest === snapshot.reviewedDefinitionDigest && metadata.reasonCodes.length === 0 && metadata.expiresAt !== null && Date.parse(metadata.expiresAt) > Date.parse(metadata.observedAt);
2262
2680
  }
2263
- var metaView = refine2(union2(
2681
+ var metaView = refine3(union2(
2264
2682
  object2({ schemaVersion: literal2(1), kind: literal2("unconfigured"), projectId: uuid, campaignId: uuid, channelId: uuid, configurationRevision: literal2(0) }),
2265
2683
  object2({
2266
2684
  schemaVersion: literal2(1),
@@ -2275,14 +2693,14 @@ var metaView = refine2(union2(
2275
2693
  observedAt: instant,
2276
2694
  expiresAt: nullable2(instant),
2277
2695
  readyForReview: bool,
2278
- reasonCodes: uniqueList(text2(200), 100),
2279
- pendingRequirements: uniqueList(text2(200), 100)
2696
+ reasonCodes: uniqueList(text3(200), 100),
2697
+ pendingRequirements: uniqueList(text3(200), 100)
2280
2698
  })
2281
2699
  ), (v, p) => {
2282
2700
  if (v.kind !== "configured") return;
2283
2701
  const s = parseResonanceMetaConfigurationSnapshot(v.snapshot);
2284
- if (v.projectId !== s.projectId || v.campaignId !== s.campaignId || v.channelId !== s.channelId || v.configurationRevision !== s.configurationRevision) fail2(p, "snapshot identity or configuration CAS mismatch");
2285
- if (v.readyForReview !== metaReviewable(s, v)) fail2(p + ".readyForReview", "must reflect current review prerequisites only");
2702
+ if (v.projectId !== s.projectId || v.campaignId !== s.campaignId || v.channelId !== s.channelId || v.configurationRevision !== s.configurationRevision) fail3(p, "snapshot identity or configuration CAS mismatch");
2703
+ if (v.readyForReview !== metaReviewable(s, v)) fail3(p + ".readyForReview", "must reflect current review prerequisites only");
2286
2704
  });
2287
2705
  var parseResonanceMetaConfigurationView = (v) => metaView.read(v, "metaConfigurationView");
2288
2706
  var RESONANCE_META_AUDIENCE_VERDICTS = ["ready", "too_small", "blocked", "unknown"];
@@ -2312,24 +2730,24 @@ var RESONANCE_META_AUDIENCE_REASONS = [
2312
2730
  "meta_audience_name_sensitive"
2313
2731
  ];
2314
2732
  var metaReadinessPage = object2({ resourceRuleRef: measurementRuleRef, path: observedPagePath, label: nullable2(friendlyName) });
2315
- var metaAudienceSize = refine2(object2({ lower: integer2(0), upper: integer2(0) }), (v, p) => {
2316
- if (v.upper < v.lower) fail2(p, "size bounds must be ordered");
2733
+ var metaAudienceSize = refine3(object2({ lower: integer2(0), upper: integer2(0) }), (v, p) => {
2734
+ if (v.upper < v.lower) fail3(p, "size bounds must be ordered");
2317
2735
  });
2318
2736
  var metaAudienceReadinessFields = {
2319
2737
  verdict: choice2(...RESONANCE_META_AUDIENCE_VERDICTS),
2320
2738
  reasonCodes: uniqueList(choice2(...RESONANCE_META_AUDIENCE_REASONS), 50),
2321
2739
  size: nullable2(metaAudienceSize)
2322
2740
  };
2323
- var metaAudienceSetupReadiness = refine2(object2({
2741
+ var metaAudienceSetupReadiness = refine3(object2({
2324
2742
  status: metaAudienceSetupStatus,
2325
2743
  delivery: nullable2(object2(websiteVisitSetupAcceptedVisitFields)),
2326
2744
  providerAudience: nullable2(object2({ externalId: nativeAudienceId, observedAt: instant, readiness: object2(metaAudienceReadinessFields) }))
2327
2745
  }), ({ status, delivery, providerAudience }, at) => {
2328
2746
  if (delivery && (!status.grant || Date.parse(delivery.checkedAt) < Date.parse(status.grant.proof.activatedAt))) {
2329
- fail2(at + ".delivery", "requires the grant and an observation at or after activation");
2747
+ fail3(at + ".delivery", "requires the grant and an observation at or after activation");
2330
2748
  }
2331
2749
  if (providerAudience && (status.receipt.status !== "selected" && status.receipt.status !== "verified" || status.receipt.currentVerification?.externalId !== providerAudience.externalId)) {
2332
- fail2(at + ".providerAudience", "requires observation of the exact verified audience");
2750
+ fail3(at + ".providerAudience", "requires observation of the exact verified audience");
2333
2751
  }
2334
2752
  });
2335
2753
  var parseResonanceMetaAudienceSetupReadiness = (value) => metaAudienceSetupReadiness.read(value, "metaAudienceSetupReadiness");
@@ -2339,23 +2757,23 @@ var metaReadinessCheck = union2(
2339
2757
  object2({ state: literal2("observed"), mappingSource: choice2("selected_external_audience", "current_materialized_audience"), ...metaAudienceReadinessFields, observedAt: instant, expiresAt: nullable2(instant), sizeObservedAt: literal2(null), sizeExpiresAt: literal2(null) })
2340
2758
  );
2341
2759
  var metaReadinessAudience = object2({ audienceRuleRef: audience, name: friendlyName, includedPage: metaReadinessPage, excludedPages: list2(metaReadinessPage, 50), nativeAudienceId: nullable2(nativeAudienceId), check: metaReadinessCheck });
2342
- var metaRetargetingReadiness = refine2(object2({ schemaVersion: literal2(1), projectId: uuid, campaignId: uuid, channelId: uuid, site, campaignRevision: integer2(1), accountBindingId: uuid, configuration: metaView, audiences: list2(metaReadinessAudience, 50) }), (v, p) => {
2760
+ var metaRetargetingReadiness = refine3(object2({ schemaVersion: literal2(1), projectId: uuid, campaignId: uuid, channelId: uuid, site, campaignRevision: integer2(1), accountBindingId: uuid, configuration: metaView, audiences: list2(metaReadinessAudience, 50) }), (v, p) => {
2343
2761
  const sameId = (a, b) => a.toLowerCase() === b.toLowerCase();
2344
2762
  const config = v.configuration;
2345
- if (!sameId(config.projectId, v.projectId) || !sameId(config.campaignId, v.campaignId) || !sameId(config.channelId, v.channelId)) fail2(p + ".configuration", "configuration scope mismatch");
2346
- if (config.kind === "configured" && (config.currentCampaignRevision !== v.campaignRevision || config.snapshot.site !== v.site || !sameId(config.snapshot.account.id, v.accountBindingId))) fail2(p + ".configuration", "current configuration revision, site or account mismatch");
2763
+ if (!sameId(config.projectId, v.projectId) || !sameId(config.campaignId, v.campaignId) || !sameId(config.channelId, v.channelId)) fail3(p + ".configuration", "configuration scope mismatch");
2764
+ if (config.kind === "configured" && (config.currentCampaignRevision !== v.campaignRevision || config.snapshot.site !== v.site || !sameId(config.snapshot.account.id, v.accountBindingId))) fail3(p + ".configuration", "current configuration revision, site or account mismatch");
2347
2765
  unique(v.audiences.map((row) => row.audienceRuleRef.id.toLowerCase()), p + ".audiences");
2348
2766
  for (const row of v.audiences) {
2349
- if (!sameId(row.audienceRuleRef.projectId, v.projectId) || row.audienceRuleRef.site !== v.site) fail2(p + ".audiences", "audience scope mismatch");
2767
+ if (!sameId(row.audienceRuleRef.projectId, v.projectId) || row.audienceRuleRef.site !== v.site) fail3(p + ".audiences", "audience scope mismatch");
2350
2768
  const excluded = row.excludedPages.map((page2) => page2.resourceRuleRef.id.toLowerCase());
2351
2769
  unique(excluded, p + ".audiences.excludedPages");
2352
2770
  const expected = row.audienceRuleRef.exclusionRuleIds.map((id) => id.toLowerCase());
2353
2771
  unique(expected, p + ".audiences.audienceRuleRef.exclusionRuleIds");
2354
- if (excluded.includes(row.includedPage.resourceRuleRef.id.toLowerCase()) || excluded.length !== expected.length || expected.some((id) => !excluded.includes(id))) fail2(p + ".audiences.excludedPages", "exclusion rule scope mismatch");
2355
- if (row.check.state === "observed" && (row.nativeAudienceId === null || config.kind !== "configured")) fail2(p + ".audiences.check", "observed check requires configured scope and actual native audience identity");
2772
+ if (excluded.includes(row.includedPage.resourceRuleRef.id.toLowerCase()) || excluded.length !== expected.length || expected.some((id) => !excluded.includes(id))) fail3(p + ".audiences.excludedPages", "exclusion rule scope mismatch");
2773
+ if (row.check.state === "observed" && (row.nativeAudienceId === null || config.kind !== "configured")) fail3(p + ".audiences.check", "observed check requires configured scope and actual native audience identity");
2356
2774
  if (config.kind === "configured" && config.currentDefinitionDigest === config.snapshot.reviewedDefinitionDigest) {
2357
2775
  const original = config.snapshot.audiences.find((a) => sameId(a.audienceRuleRef.id, row.audienceRuleRef.id));
2358
- if (!original || canonical(original.audienceRuleRef) !== canonical(row.audienceRuleRef) || canonical(original.resourceRuleRef) !== canonical(row.includedPage.resourceRuleRef) || original.excludedResourceRuleRefs.length !== row.excludedPages.length || original.excludedResourceRuleRefs.some((ref) => !row.excludedPages.some((page2) => canonical(page2.resourceRuleRef) === canonical(ref)))) fail2(p + ".audiences", "original audience and page rule versions must match");
2776
+ if (!original || canonical(original.audienceRuleRef) !== canonical(row.audienceRuleRef) || canonical(original.resourceRuleRef) !== canonical(row.includedPage.resourceRuleRef) || original.excludedResourceRuleRefs.length !== row.excludedPages.length || original.excludedResourceRuleRefs.some((ref) => !row.excludedPages.some((page2) => canonical(page2.resourceRuleRef) === canonical(ref)))) fail3(p + ".audiences", "original audience and page rule versions must match");
2359
2777
  }
2360
2778
  }
2361
2779
  });
@@ -2373,38 +2791,38 @@ var RESONANCE_META_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA = metaSave.schema;
2373
2791
  var RESONANCE_META_CONFIGURATION_SNAPSHOT_JSON_SCHEMA = metaSnapshot.schema;
2374
2792
  var RESONANCE_META_CONFIGURATION_VIEW_JSON_SCHEMA = metaView.schema;
2375
2793
  var RESONANCE_META_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA = metaSaveResponse.schema;
2376
- var feedSelection = refine2(object2({ channels: list2(object2({ channelId: uuid, expectedConfigurationRevision: integer2(1), resourceRuleRefs: list2(measurementRuleRef, 500, 1) }), 100, 1) }), (v, p) => {
2794
+ var feedSelection = refine3(object2({ channels: list2(object2({ channelId: uuid, expectedConfigurationRevision: integer2(1), resourceRuleRefs: list2(measurementRuleRef, 500, 1) }), 100, 1) }), (v, p) => {
2377
2795
  unique(v.channels.map((c) => c.channelId), p + ".channels");
2378
2796
  for (const c of v.channels) unique(c.resourceRuleRefs.map((ref) => ref.id), p + ".resourceRuleRefs");
2379
2797
  });
2380
- var mandateDraftRequest = object2({ expectedRevision: integer2(1), allowedOperations: mandateAllowedOperations, expiresAt: instant, websiteVisitFeedSelection: optional2(feedSelection), providerReporting: optional2(providerReportingSelection) });
2798
+ var mandateDraftRequest = object2({ expectedRevision: integer2(1), allowedOperations: mandateAllowedOperations, expiresAt: instant, websiteVisitFeedSelection: optional2(feedSelection), providerReporting: optional2(providerReportingSelection), operatingPolicySelection: optional2(operatingPolicySelection), activation: optional2(literal2("operating_policy")) });
2381
2799
  var parseResonanceMandateDraftRequest = (v) => mandateDraftRequest.read(v, "mandateDraftRequest");
2382
2800
  var RESONANCE_MANDATE_DRAFT_REQUEST_JSON_SCHEMA = mandateDraftRequest.schema;
2383
- var feedReview = object2({ schemaVersion: literal2(1), approval: mandateApproval, mandateRef, configurations: list2(metaSnapshot, 100), current: object2({ state: choice2("not_enabled", "eligible", "invalidated", "unavailable"), checkedAt: instant, expiresAt: nullable2(instant), reasonCodes: uniqueList(text2(200), 100) }) });
2801
+ var feedReview = object2({ schemaVersion: literal2(1), approval: mandateApproval, mandateRef, configurations: list2(metaSnapshot, 100), current: object2({ state: choice2("not_enabled", "eligible", "invalidated", "unavailable"), checkedAt: instant, expiresAt: nullable2(instant), reasonCodes: uniqueList(text3(200), 100) }) });
2384
2802
  function parseResonanceWebsiteVisitFeedReview(v, context) {
2385
2803
  const r = feedReview.read(v, "websiteVisitFeedReview"), original = r.approval, grant = parseResonanceMandateScope(original.mandate), ref = r.mandateRef, p = "websiteVisitFeedReview";
2386
2804
  parseResonanceMandateApprovalPayload(original, { project_id: grant.projectId, campaign_id: grant.campaignId });
2387
- if (ref.campaignId !== grant.campaignId || ref.preparedPlanId !== original.preparedPlanId || ref.reviewDigest !== original.reviewDigest || ref.mandateDigest !== original.mandateDigest) fail2(p + ".mandateRef", "requires the same original accepted mandate");
2805
+ if (ref.campaignId !== grant.campaignId || ref.preparedPlanId !== original.preparedPlanId || ref.reviewDigest !== original.reviewDigest || ref.mandateDigest !== original.mandateDigest) fail3(p + ".mandateRef", "requires the same original accepted mandate");
2388
2806
  unique(r.configurations.map((c) => c.channelId), p + ".configurations");
2389
2807
  const feed = grant.websiteVisitFeed;
2390
2808
  if (!feed) {
2391
- if (r.configurations.length || r.current.state !== "not_enabled") fail2(p, "absent original feed requires not_enabled and no configurations");
2809
+ if (r.configurations.length || r.current.state !== "not_enabled") fail3(p, "absent original feed requires not_enabled and no configurations");
2392
2810
  } else {
2393
- if (r.current.state === "not_enabled" || r.configurations.length !== feed.channels.length) fail2(p, "must cover the exact original feed channels");
2811
+ if (r.current.state === "not_enabled" || r.configurations.length !== feed.channels.length) fail3(p, "must cover the exact original feed channels");
2394
2812
  for (const selected of feed.channels) {
2395
2813
  const config = r.configurations.find((c) => c.channelId === selected.channelId);
2396
- if (!config || config.projectId !== grant.projectId || config.campaignId !== grant.campaignId || !grant.sites.includes(config.site) || !grant.accountBindingIds.includes(config.account.id) || config.campaignRevision > original.expectedRevision || canonical(config.measurementConfigRef) !== canonical(selected.measurementConfigRef) || canonical(config.matchingProfileRef) !== canonical(selected.matchingProfileRef)) fail2(p + ".configurations", "original configuration/profile/scope mismatch");
2814
+ if (!config || config.projectId !== grant.projectId || config.campaignId !== grant.campaignId || !grant.sites.includes(config.site) || !grant.accountBindingIds.includes(config.account.id) || config.campaignRevision > original.expectedRevision || canonical(config.measurementConfigRef) !== canonical(selected.measurementConfigRef) || canonical(config.matchingProfileRef) !== canonical(selected.matchingProfileRef)) fail3(p + ".configurations", "original configuration/profile/scope mismatch");
2397
2815
  const saved = config;
2398
- for (const a of saved.channel.audienceRuleRefs) if (!grant.audienceRuleRefs.some((ref2) => canonical(ref2) === canonical(a))) fail2(p + ".configurations", "original logical audience grant mismatch");
2816
+ for (const a of saved.channel.audienceRuleRefs) if (!grant.audienceRuleRefs.some((ref2) => canonical(ref2) === canonical(a))) fail3(p + ".configurations", "original logical audience grant mismatch");
2399
2817
  const positive = saved.audiences.map((a) => a.resourceRuleRef);
2400
- for (const rule of selected.resourceRuleRefs) if (!positive.some((ref2) => ref2.id === rule.id && ref2.revision === rule.revision)) fail2(p + ".configurations", "feed requires an original positive resource rule, never excluded-only");
2818
+ for (const rule of selected.resourceRuleRefs) if (!positive.some((ref2) => ref2.id === rule.id && ref2.revision === rule.revision)) fail3(p + ".configurations", "feed requires an original positive resource rule, never excluded-only");
2401
2819
  }
2402
- if (r.current.state === "eligible" && (r.current.reasonCodes.length || r.current.expiresAt === null || Date.parse(r.current.expiresAt) <= Date.parse(r.current.checkedAt))) fail2(p + ".current", "eligible review requires an observed nonexpired horizon and no blockers");
2820
+ if (r.current.state === "eligible" && (r.current.reasonCodes.length || r.current.expiresAt === null || Date.parse(r.current.expiresAt) <= Date.parse(r.current.checkedAt))) fail3(p + ".current", "eligible review requires an observed nonexpired horizon and no blockers");
2403
2821
  }
2404
2822
  if (context) {
2405
2823
  const actual = object2({ preparedPlan: prepared }).read(context, p + ".context"), plan = parseResonancePreparedPlan(actual.preparedPlan);
2406
- if (plan.id !== original.preparedPlanId || plan.campaignId !== grant.campaignId || plan.projectId !== grant.projectId || plan.reviewDigest !== original.reviewDigest || plan.expectedRevision !== original.expectedRevision || canonical(plan.definition.budget) !== canonical(grant.budget) || canonical(plan.definition.objective) !== canonical(grant.goal)) fail2(p + ".context", "requires the original prepared plan and mandate material");
2407
- for (const config of r.configurations) if (config.reviewedDefinitionDigest !== plan.definitionDigest || !plan.definition.channels.some((c) => canonical(c) === canonical(config.channel))) fail2(p + ".context", "original channel or reviewed definition mismatch");
2824
+ if (plan.id !== original.preparedPlanId || plan.campaignId !== grant.campaignId || plan.projectId !== grant.projectId || plan.reviewDigest !== original.reviewDigest || plan.expectedRevision !== original.expectedRevision || canonical(plan.definition.budget) !== canonical(grant.budget) || canonical(plan.definition.objective) !== canonical(grant.goal)) fail3(p + ".context", "requires the original prepared plan and mandate material");
2825
+ for (const config of r.configurations) if (config.reviewedDefinitionDigest !== plan.definitionDigest || !plan.definition.channels.some((c) => canonical(c) === canonical(config.channel))) fail3(p + ".context", "original channel or reviewed definition mismatch");
2408
2826
  }
2409
2827
  return r;
2410
2828
  }
@@ -2412,7 +2830,7 @@ var RESONANCE_WEBSITE_VISIT_FEED_REVIEW_JSON_SCHEMA = feedReview.schema;
2412
2830
  var observationIdentity = { observationId: uuid, channelId: uuid, versionId: uuid, accountBindingId: uuid };
2413
2831
  var publicObservationMetric = union2(
2414
2832
  object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: literal2("observed"), value: metricValue }),
2415
- object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text2(80) })
2833
+ object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text3(80) })
2416
2834
  );
2417
2835
  function parseResonancePublicObservationMetric(v) {
2418
2836
  const r = publicObservationMetric.read(v, "observationItem");
@@ -2421,7 +2839,7 @@ function parseResonancePublicObservationMetric(v) {
2421
2839
  return r;
2422
2840
  }
2423
2841
  var observationDenominators = object2({ eligibleContacts: nullable2(decimal), fullyResolvedContacts: nullable2(decimal), qualifiedContacts: nullable2(decimal) });
2424
- var observationSupportFields = { ...observationIdentity, currency, fetchedAt: instant, dataThrough: nullable2(instant), coverage: choice2("unknown", "partial", "complete"), reasonCode: nullable2(text2(80)), denominators: observationDenominators };
2842
+ var observationSupportFields = { ...observationIdentity, currency, fetchedAt: instant, dataThrough: nullable2(instant), coverage: choice2("unknown", "partial", "complete"), reasonCode: nullable2(text3(80)), denominators: observationDenominators };
2425
2843
  var firstPartyObservationSupport = object2({ ...observationSupportFields, source: literal2("first_party") });
2426
2844
  var providerObservationSupport = object2({
2427
2845
  ...observationSupportFields,
@@ -2437,53 +2855,53 @@ var providerObservationSupport = object2({
2437
2855
  var observationSupport = union2(firstPartyObservationSupport, providerObservationSupport);
2438
2856
  function parseResonanceObservationSupport(v) {
2439
2857
  const r = observationSupport.read(v, "observationSupport"), p = "observationSupport", d = r.denominators;
2440
- if (d.fullyResolvedContacts !== null && (d.eligibleContacts === null || BigInt(d.fullyResolvedContacts) > BigInt(d.eligibleContacts)) || d.qualifiedContacts !== null && (d.fullyResolvedContacts === null || BigInt(d.qualifiedContacts) > BigInt(d.fullyResolvedContacts))) fail2(p + ".denominators", "inconsistent independent contact universe");
2858
+ if (d.fullyResolvedContacts !== null && (d.eligibleContacts === null || BigInt(d.fullyResolvedContacts) > BigInt(d.eligibleContacts)) || d.qualifiedContacts !== null && (d.fullyResolvedContacts === null || BigInt(d.qualifiedContacts) > BigInt(d.fullyResolvedContacts))) fail3(p + ".denominators", "inconsistent independent contact universe");
2441
2859
  if (r.source === "provider") {
2442
- if (Object.values(d).some((v2) => v2 !== null)) fail2(p + ".denominators", "provider reporting cannot supply qualified-contact denominators");
2443
- if (r.firstReceivedAt !== null && (r.receivedAt === null || Date.parse(r.firstReceivedAt) > Date.parse(r.receivedAt))) fail2(p + ".firstReceivedAt", "preserve actual internal HTTP receipt order");
2444
- if (r.recordedAt !== null && Date.parse(r.recordedAt) !== Date.parse(r.fetchedAt)) fail2(p + ".recordedAt", "must retain the native immutable SQL write time");
2445
- if (r.readClock !== null && (r.firstReceivedAt === null || r.receivedAt === null || r.recordedAt === null || Date.parse(r.readClock.notBeforeAt) > Date.parse(r.recordedAt))) fail2(p + ".readClock", "requires actual earliest/final HTTP metadata and SQL lower-bound chronology");
2446
- if (r.coverageBasis === "closed_query_snapshot" ? r.coverage !== "complete" || r.reasonCode !== null || r.receivedAt === null || r.recordedAt === null || r.dataThrough !== null : r.coverage === "complete") fail2(p + ".coverage", "distinguish revisable query coverage from unestablished legacy reporting");
2860
+ if (Object.values(d).some((v2) => v2 !== null)) fail3(p + ".denominators", "provider reporting cannot supply qualified-contact denominators");
2861
+ if (r.firstReceivedAt !== null && (r.receivedAt === null || Date.parse(r.firstReceivedAt) > Date.parse(r.receivedAt))) fail3(p + ".firstReceivedAt", "preserve actual internal HTTP receipt order");
2862
+ if (r.recordedAt !== null && Date.parse(r.recordedAt) !== Date.parse(r.fetchedAt)) fail3(p + ".recordedAt", "must retain the native immutable SQL write time");
2863
+ if (r.readClock !== null && (r.firstReceivedAt === null || r.receivedAt === null || r.recordedAt === null || Date.parse(r.readClock.notBeforeAt) > Date.parse(r.recordedAt))) fail3(p + ".readClock", "requires actual earliest/final HTTP metadata and SQL lower-bound chronology");
2864
+ if (r.coverageBasis === "closed_query_snapshot" ? r.coverage !== "complete" || r.reasonCode !== null || r.receivedAt === null || r.recordedAt === null || r.dataThrough !== null : r.coverage === "complete") fail3(p + ".coverage", "distinguish revisable query coverage from unestablished legacy reporting");
2447
2865
  }
2448
2866
  return r;
2449
2867
  }
2450
2868
  var observationsPage = object2({ items: list2(publicObservationMetric, 500), nextCursor: nullable2(uuid), observedAt: instant, support: list2(observationSupport, 500) });
2451
2869
  function parseResonanceObservationsPage(v) {
2452
2870
  const r = observationsPage.read(v, "observationsPage"), p = "observationsPage";
2453
- if (r.items.length !== r.support.length) fail2(p + ".support", "requires one support entry for each metric item");
2871
+ if (r.items.length !== r.support.length) fail3(p + ".support", "requires one support entry for each metric item");
2454
2872
  const pairs = /* @__PURE__ */ new Set(), rows = /* @__PURE__ */ new Map(), observedAt = Date.parse(r.observedAt);
2455
2873
  let previous;
2456
2874
  const first = r.items[0];
2457
2875
  for (let i = 0; i < r.items.length; i++) {
2458
2876
  const item = parseResonancePublicObservationMetric(r.items[i]), s = parseResonanceObservationSupport(r.support[i]), rowId = item.observationId.toLowerCase();
2459
- if (Object.keys(observationIdentity).some((k) => item[k] !== s[k])) fail2(p + ".support", "item/support observation, channel, version and account must align in order");
2460
- if (item.source !== s.source || item.projectId !== first.projectId || item.campaignId !== first.campaignId || item.site !== first.site) fail2(p + ".items", "requires one scoped provider or first-party page");
2461
- if (Date.parse(item.asOf) !== Date.parse(s.fetchedAt) || Date.parse(s.fetchedAt) > observedAt || item.dataThrough === null !== (s.dataThrough === null) || item.dataThrough !== null && s.dataThrough !== null && Date.parse(item.dataThrough) !== Date.parse(s.dataThrough)) fail2(p + ".support", "preserve native SQL observation chronology and data-through meaning");
2462
- if (item.state === "observed" && item.value.kind === "money" && item.value.money.currency !== s.currency) fail2(p + ".support.currency", "observed money must retain account currency");
2463
- if (previous !== void 0 && rowId < previous) fail2(p + ".items", "native-row UUID order cannot be replaced by metric/time sorting");
2877
+ if (Object.keys(observationIdentity).some((k) => item[k] !== s[k])) fail3(p + ".support", "item/support observation, channel, version and account must align in order");
2878
+ if (item.source !== s.source || item.projectId !== first.projectId || item.campaignId !== first.campaignId || item.site !== first.site) fail3(p + ".items", "requires one scoped provider or first-party page");
2879
+ if (Date.parse(item.asOf) !== Date.parse(s.fetchedAt) || Date.parse(s.fetchedAt) > observedAt || item.dataThrough === null !== (s.dataThrough === null) || item.dataThrough !== null && s.dataThrough !== null && Date.parse(item.dataThrough) !== Date.parse(s.dataThrough)) fail3(p + ".support", "preserve native SQL observation chronology and data-through meaning");
2880
+ if (item.state === "observed" && item.value.kind === "money" && item.value.money.currency !== s.currency) fail3(p + ".support.currency", "observed money must retain account currency");
2881
+ if (previous !== void 0 && rowId < previous) fail3(p + ".items", "native-row UUID order cannot be replaced by metric/time sorting");
2464
2882
  previous = rowId;
2465
2883
  const key = rowId + ":" + item.name;
2466
- if (pairs.has(key)) fail2(p + ".items", "duplicate observation/metric pair");
2884
+ if (pairs.has(key)) fail3(p + ".items", "duplicate observation/metric pair");
2467
2885
  pairs.add(key);
2468
2886
  const supportIdentity = { ...s, fetchedAt: Date.parse(s.fetchedAt), dataThrough: s.dataThrough === null ? null : Date.parse(s.dataThrough), ...s.source === "provider" ? { firstReceivedAt: s.firstReceivedAt === null ? null : Date.parse(s.firstReceivedAt), receivedAt: s.receivedAt === null ? null : Date.parse(s.receivedAt), recordedAt: s.recordedAt === null ? null : Date.parse(s.recordedAt) } : {} };
2469
2887
  const row = canonical({ projectId: item.projectId, campaignId: item.campaignId, site: item.site, channelId: item.channelId, versionId: item.versionId, accountBindingId: item.accountBindingId, source: item.source, windowStart: Date.parse(item.windowStart), windowEnd: Date.parse(item.windowEnd), timeZone: item.timeZone, fetchedAt: Date.parse(s.fetchedAt), support: supportIdentity });
2470
- if (rows.has(rowId) && rows.get(rowId) !== row) fail2(p + ".support", "one immutable native observation cannot change identity or support across metrics");
2888
+ if (rows.has(rowId) && rows.get(rowId) !== row) fail3(p + ".support", "one immutable native observation cannot change identity or support across metrics");
2471
2889
  rows.set(rowId, row);
2472
2890
  if (s.source === "provider") {
2473
- if (item.state === "observed" && (s.coverage !== "complete" || s.coverageBasis !== "closed_query_snapshot" || s.reasonCode !== null)) fail2(p + ".support", "observed provider values require complete genuine closed-query support");
2474
- if (!RESONANCE_PROVIDER_METRIC_NAMES.includes(item.name) || item.sourceRef !== item.observationId || item.countingUnit !== providerCountingUnit(item.name) || item.attributionModel !== "provider_reported") fail2(p + ".items", "provider metrics retain exact native observation and aggregate semantics");
2475
- if (s.readClock !== null && Date.parse(s.readClock.notBeforeAt) < Date.parse(item.windowEnd)) fail2(p + ".support.readClock", "SQL pre-read lower bound must follow the completed query window");
2891
+ if (item.state === "observed" && (s.coverage !== "complete" || s.coverageBasis !== "closed_query_snapshot" || s.reasonCode !== null)) fail3(p + ".support", "observed provider values require complete genuine closed-query support");
2892
+ if (!RESONANCE_PROVIDER_METRIC_NAMES.includes(item.name) || item.sourceRef !== item.observationId || item.countingUnit !== providerCountingUnit(item.name) || item.attributionModel !== "provider_reported") fail3(p + ".items", "provider metrics retain exact native observation and aggregate semantics");
2893
+ if (s.readClock !== null && Date.parse(s.readClock.notBeforeAt) < Date.parse(item.windowEnd)) fail3(p + ".support.readClock", "SQL pre-read lower bound must follow the completed query window");
2476
2894
  } else {
2477
2895
  const d = s.denominators;
2478
- if (item.name !== "qualified_goals" || item.countingUnit !== "unique_qualified_contact" || item.goalRevision === null || item.attributionModel !== RESONANCE_ATTRIBUTION_MODEL || item.eligibleExposures !== null || item.matureOutcomes !== null) fail2(p + ".items", "preserve genuine first-party qualification without fabricated exposure counts");
2896
+ if (item.name !== "qualified_goals" || item.countingUnit !== "unique_qualified_contact" || item.goalRevision === null || item.attributionModel !== RESONANCE_ATTRIBUTION_MODEL || item.eligibleExposures !== null || item.matureOutcomes !== null) fail3(p + ".items", "preserve genuine first-party qualification without fabricated exposure counts");
2479
2897
  const coverage = d.eligibleContacts === null || d.eligibleContacts === "0" || d.fullyResolvedContacts === null ? null : Number(BigInt(d.fullyResolvedContacts) * 10000n / BigInt(d.eligibleContacts));
2480
- if (item.coverageBasisPoints !== coverage) fail2(p + ".support.denominators", "contact resolution coverage must match the independent universe");
2481
- if (item.state !== "observed" && (s.coverage === "complete" || s.reasonCode !== item.reasonCode)) fail2(p + ".support", "unresolved qualified sources keep incomplete coverage and their native reason");
2482
- if (item.state === "observed" && (s.coverage !== "complete" || s.reasonCode !== null || d.eligibleContacts === null || d.fullyResolvedContacts !== d.eligibleContacts || d.qualifiedContacts === null || item.value.kind !== "count" || item.value.count !== d.qualifiedContacts)) fail2(p + ".support", "observed qualified count requires its complete independent native universe");
2898
+ if (item.coverageBasisPoints !== coverage) fail3(p + ".support.denominators", "contact resolution coverage must match the independent universe");
2899
+ if (item.state !== "observed" && (s.coverage === "complete" || s.reasonCode !== item.reasonCode)) fail3(p + ".support", "unresolved qualified sources keep incomplete coverage and their native reason");
2900
+ if (item.state === "observed" && (s.coverage !== "complete" || s.reasonCode !== null || d.eligibleContacts === null || d.fullyResolvedContacts !== d.eligibleContacts || d.qualifiedContacts === null || item.value.kind !== "count" || item.value.count !== d.qualifiedContacts)) fail3(p + ".support", "observed qualified count requires its complete independent native universe");
2483
2901
  }
2484
2902
  }
2485
- if (rows.size > 100) fail2(p + ".items", "at most 100 native rows per page");
2486
- if (r.nextCursor !== null && (!r.items.length || r.nextCursor.toLowerCase() !== previous)) fail2(p + ".nextCursor", "cursor must retain the final native row, not a metric offset");
2903
+ if (rows.size > 100) fail3(p + ".items", "at most 100 native rows per page");
2904
+ if (r.nextCursor !== null && (!r.items.length || r.nextCursor.toLowerCase() !== previous)) fail3(p + ".nextCursor", "cursor must retain the final native row, not a metric offset");
2487
2905
  return r;
2488
2906
  }
2489
2907
  var RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA = publicObservationMetric.schema;
@@ -2499,13 +2917,13 @@ var isMetaChannel = (c) => c.kind === "meta_retargeting";
2499
2917
  var usesPropertyModel = (c) => c.channelGroup !== void 0 || c.audienceRuleRefs.some((ref) => ref.minDaysSinceVisit !== void 0);
2500
2918
  function checkAudienceBand(ref, provider = "meta_ads", at = "audienceRuleRef") {
2501
2919
  const min = ref.minDaysSinceVisit;
2502
- if (min !== void 0 && min >= ref.retentionDays) fail2(at + ".minDaysSinceVisit", "must be shorter than the retention window");
2920
+ if (min !== void 0 && min >= ref.retentionDays) fail3(at + ".minDaysSinceVisit", "must be shorter than the retention window");
2503
2921
  if (provider === "google_ads") {
2504
- if (min !== void 0) fail2(at + ".minDaysSinceVisit", "Google audiences have no recency band");
2922
+ if (min !== void 0) fail3(at + ".minDaysSinceVisit", "Google audiences have no recency band");
2505
2923
  return;
2506
2924
  }
2507
- if (ref.retentionDays > META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS) fail2(at + ".retentionDays", `exceeds the ${META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS}-day Meta website audience maximum`);
2508
- if (1 + ref.exclusionRuleIds.length + (min === void 0 ? 0 : 1) > META_AUDIENCE_RULE_LIMIT) fail2(at + ".exclusionRuleIds", `a Meta audience holds at most ${META_AUDIENCE_RULE_LIMIT} rules including the page and any recency band`);
2925
+ if (ref.retentionDays > META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS) fail3(at + ".retentionDays", `exceeds the ${META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS}-day Meta website audience maximum`);
2926
+ if (1 + ref.exclusionRuleIds.length + (min === void 0 ? 0 : 1) > META_AUDIENCE_RULE_LIMIT) fail3(at + ".exclusionRuleIds", `a Meta audience holds at most ${META_AUDIENCE_RULE_LIMIT} rules including the page and any recency band`);
2509
2927
  }
2510
2928
  function checkMetaAudienceBands(channel2, at) {
2511
2929
  if (!usesPropertyModel(channel2)) return;
@@ -2517,25 +2935,25 @@ function checkChannelGroups(channels) {
2517
2935
  for (const c of channels) if (isMetaChannel(c) && c.channelGroup) groups.set(c.channelGroup.key, [...groups.get(c.channelGroup.key) ?? [], c]);
2518
2936
  for (const [key, members] of groups) {
2519
2937
  const at = `campaign.channelGroup.${key}`;
2520
- if (members.length > RESONANCE_MAX_CHANNELS_PER_GROUP) fail2(at, `at most ${RESONANCE_MAX_CHANNELS_PER_GROUP} channels per group`);
2938
+ if (members.length > RESONANCE_MAX_CHANNELS_PER_GROUP) fail3(at, `at most ${RESONANCE_MAX_CHANNELS_PER_GROUP} channels per group`);
2521
2939
  const first = members[0];
2522
2940
  const shared = (c) => canonical([c.site, c.accountBindingId, c.datasetRef.id, c.pageRef, c.instagramRef, c.specialCategories, c.countryCodes, c.objective, c.optimization]);
2523
2941
  const identity = /* @__PURE__ */ new Set(), destinationOf = /* @__PURE__ */ new Map(), propertyOfDestination = /* @__PURE__ */ new Map();
2524
2942
  for (const c of members) {
2525
- if (shared(c) !== shared(first)) fail2(at, "channels in one group must share site, account, dataset, Page, categories, countries, objective and optimization");
2526
- if (c.specialCategories.length > 0 && c.ageConstraint?.mode !== "provider_managed") fail2(at + ".ageConstraint", "a special category requires provider-managed age");
2527
- const pk = (c.property ?? fail2(at + ".property", "a grouped channel names its property")).key, tier = c.tier?.label ?? "", id = `${pk}|${tier}`;
2528
- if (identity.has(id)) fail2(at + ".property", "two channels share one property and tier");
2943
+ if (shared(c) !== shared(first)) fail3(at, "channels in one group must share site, account, dataset, Page, categories, countries, objective and optimization");
2944
+ if (c.specialCategories.length > 0 && c.ageConstraint?.mode !== "provider_managed") fail3(at + ".ageConstraint", "a special category requires provider-managed age");
2945
+ const pk = (c.property ?? fail3(at + ".property", "a grouped channel names its property")).key, tier = c.tier?.label ?? "", id = `${pk}|${tier}`;
2946
+ if (identity.has(id)) fail3(at + ".property", "two channels share one property and tier");
2529
2947
  identity.add(id);
2530
- if (destinationOf.has(pk) && destinationOf.get(pk) !== c.destinationId) fail2(at + ".destinationId", "channels for one property share one destination");
2948
+ if (destinationOf.has(pk) && destinationOf.get(pk) !== c.destinationId) fail3(at + ".destinationId", "channels for one property share one destination");
2531
2949
  destinationOf.set(pk, c.destinationId);
2532
2950
  const other = propertyOfDestination.get(c.destinationId);
2533
- if (other !== void 0 && other !== pk) fail2(at + ".destinationId", "channels for different properties have different destinations");
2951
+ if (other !== void 0 && other !== pk) fail3(at + ".destinationId", "channels for different properties have different destinations");
2534
2952
  propertyOfDestination.set(c.destinationId, pk);
2535
2953
  }
2536
2954
  for (let i = 0; i < members.length; i++) for (let j = i + 1; j < members.length; j++) {
2537
2955
  if (members[i].property?.key !== members[j].property?.key) continue;
2538
- for (const a of members[i].audienceRuleRefs) for (const b of members[j].audienceRuleRefs) if (bandsOverlap(a, b)) fail2(at + ".audienceRuleRefs", "tiers of one property cannot overlap in time");
2956
+ for (const a of members[i].audienceRuleRefs) for (const b of members[j].audienceRuleRefs) if (bandsOverlap(a, b)) fail3(at + ".audienceRuleRefs", "tiers of one property cannot overlap in time");
2539
2957
  }
2540
2958
  }
2541
2959
  }
@@ -2543,14 +2961,14 @@ function checkGroupedAllocations(v) {
2543
2961
  if (!v.channels.some((c) => isMetaChannel(c) && c.channelGroup)) return;
2544
2962
  let sum = 0n;
2545
2963
  for (const c of v.channels) if ("allocation" in c) sum += BigInt(c.allocation.amountMicros);
2546
- if (sum > BigInt(v.budget.total.amountMicros) - BigInt(v.budget.reserveMargin.amountMicros)) fail2("campaign.channels.allocation", "channel allocations exceed the campaign total less its reserve");
2964
+ if (sum > BigInt(v.budget.total.amountMicros) - BigInt(v.budget.reserveMargin.amountMicros)) fail3("campaign.channels.allocation", "channel allocations exceed the campaign total less its reserve");
2547
2965
  }
2548
2966
  function splitBudget(total, weights, quantumMicros) {
2549
2967
  const t = parseMoney(total), at = "splitBudget";
2550
- if (!/^[1-9][0-9]{0,29}$/.test(quantumMicros)) fail2(at + ".quantumMicros", "must be a positive whole number of micros");
2551
- if (weights.length < 1 || weights.length > 100 || weights.some((w) => !Number.isSafeInteger(w) || w < 1)) fail2(at + ".weights", "one to 100 positive whole weights");
2968
+ if (!/^[1-9][0-9]{0,29}$/.test(quantumMicros)) fail3(at + ".quantumMicros", "must be a positive whole number of micros");
2969
+ if (weights.length < 1 || weights.length > 100 || weights.some((w) => !Number.isSafeInteger(w) || w < 1)) fail3(at + ".weights", "one to 100 positive whole weights");
2552
2970
  const quantum = BigInt(quantumMicros), micros = BigInt(t.amountMicros);
2553
- if (micros % quantum !== 0n) fail2(at + ".total", "must be a whole number of provider quanta");
2971
+ if (micros % quantum !== 0n) fail3(at + ".total", "must be a whole number of provider quanta");
2554
2972
  const units = micros / quantum, sum = weights.reduce((a, w) => a + BigInt(w), 0n);
2555
2973
  const parts = weights.map((w, index) => ({ index, floor: units * BigInt(w) / sum, rest: units * BigInt(w) % sum }));
2556
2974
  let left = units - parts.reduce((a, p) => a + p.floor, 0n);
@@ -2565,8 +2983,8 @@ function splitBudget(total, weights, quantumMicros) {
2565
2983
  }
2566
2984
  function suggestPropertyWeights(visitors, bounds = {}) {
2567
2985
  const floor = bounds.floorBasisPoints ?? 1e3, ceiling = bounds.ceilingBasisPoints ?? 4e3, n = visitors.length, at = "suggestPropertyWeights";
2568
- if (n < 1 || n > 100 || visitors.some((v) => !Number.isSafeInteger(v) || v < 0)) fail2(at + ".visitors", "one to 100 whole, non-negative visitor counts");
2569
- if (!Number.isInteger(floor) || !Number.isInteger(ceiling) || floor < 0 || ceiling > 1e4 || floor > ceiling || n * floor > 1e4 || n * ceiling < 1e4) fail2(at + ".bounds", "floor and ceiling cannot hold every share");
2986
+ if (n < 1 || n > 100 || visitors.some((v) => !Number.isSafeInteger(v) || v < 0)) fail3(at + ".visitors", "one to 100 whole, non-negative visitor counts");
2987
+ if (!Number.isInteger(floor) || !Number.isInteger(ceiling) || floor < 0 || ceiling > 1e4 || floor > ceiling || n * floor > 1e4 || n * ceiling < 1e4) fail3(at + ".bounds", "floor and ceiling cannot hold every share");
2570
2988
  const weight = visitors.map((v) => v + 1);
2571
2989
  const total = (lambda) => weight.reduce((a, w) => a + Math.min(ceiling, Math.max(floor, lambda * w)), 0);
2572
2990
  let low = 0, high = ceiling / Math.min(...weight) + 1;
@@ -2603,7 +3021,7 @@ var clip = (value, max) => value.length <= max ? value : value.slice(0, max);
2603
3021
  function expandPropertyChannels(definition2, groupKey, additions, options) {
2604
3022
  const at = "expandPropertyChannels";
2605
3023
  const group = definition2.channels.filter((c) => isMetaChannel(c) && c.channelGroup?.key === groupKey);
2606
- if (!group.length) fail2(at + ".group", "needs an existing property channel to use as the template");
3024
+ if (!group.length) fail3(at + ".group", "needs an existing property channel to use as the template");
2607
3025
  const template = group[0];
2608
3026
  const present = new Set(group.map((c) => c.property?.key));
2609
3027
  const keys = additions.map((a) => a.key);
@@ -2694,6 +3112,8 @@ exports.META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED = META_SAC_CUSTOM_AUDIENCE_E
2694
3112
  exports.META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS = META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS;
2695
3113
  exports.MONEY_EXPONENT = MONEY_EXPONENT;
2696
3114
  exports.MONEY_JSON_SCHEMA = MONEY_JSON_SCHEMA;
3115
+ exports.NATIVE_CAS_TIMESTAMP_JSON_SCHEMA = NATIVE_CAS_TIMESTAMP_JSON_SCHEMA;
3116
+ exports.NativeCasTimestampValidationError = NativeCasTimestampValidationError;
2697
3117
  exports.RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA = RESONANCE_ACCEPT_COMMAND_JSON_SCHEMA;
2698
3118
  exports.RESONANCE_ACCOUNT_CAPABILITY_JSON_SCHEMA = RESONANCE_ACCOUNT_CAPABILITY_JSON_SCHEMA;
2699
3119
  exports.RESONANCE_ATTRIBUTION_MODEL = RESONANCE_ATTRIBUTION_MODEL;
@@ -2719,11 +3139,17 @@ exports.RESONANCE_EXPERIMENT_LIFECYCLE_COMMAND_JSON_SCHEMA = RESONANCE_EXPERIMEN
2719
3139
  exports.RESONANCE_EXPERIMENT_LINK_COMMAND_JSON_SCHEMA = RESONANCE_EXPERIMENT_LINK_COMMAND_JSON_SCHEMA;
2720
3140
  exports.RESONANCE_EXPERIMENT_REF_JSON_SCHEMA = RESONANCE_EXPERIMENT_REF_JSON_SCHEMA;
2721
3141
  exports.RESONANCE_EXPERIMENT_UPDATE_COMMAND_JSON_SCHEMA = RESONANCE_EXPERIMENT_UPDATE_COMMAND_JSON_SCHEMA;
3142
+ exports.RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_PAYLOAD_JSON_SCHEMA = RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_PAYLOAD_JSON_SCHEMA;
3143
+ exports.RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_REPORT_JSON_SCHEMA = RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_REPORT_JSON_SCHEMA;
3144
+ exports.RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_REQUEST_JSON_SCHEMA = RESONANCE_GOOGLE_CAMPAIGN_DIAGNOSTICS_REQUEST_JSON_SCHEMA;
2722
3145
  exports.RESONANCE_GOOGLE_CONFIGURATION_REVIEW_JSON_SCHEMA = RESONANCE_GOOGLE_CONFIGURATION_REVIEW_JSON_SCHEMA;
2723
3146
  exports.RESONANCE_GOOGLE_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA = RESONANCE_GOOGLE_CONFIGURATION_SAVE_COMMAND_JSON_SCHEMA;
2724
3147
  exports.RESONANCE_GOOGLE_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA = RESONANCE_GOOGLE_CONFIGURATION_SAVE_RESPONSE_JSON_SCHEMA;
2725
3148
  exports.RESONANCE_GOOGLE_CONFIGURATION_SNAPSHOT_JSON_SCHEMA = RESONANCE_GOOGLE_CONFIGURATION_SNAPSHOT_JSON_SCHEMA;
2726
3149
  exports.RESONANCE_GOOGLE_CONFIGURATION_VIEW_JSON_SCHEMA = RESONANCE_GOOGLE_CONFIGURATION_VIEW_JSON_SCHEMA;
3150
+ exports.RESONANCE_GOOGLE_CONTENT_UPDATE_JSON_SCHEMA = RESONANCE_GOOGLE_CONTENT_UPDATE_JSON_SCHEMA;
3151
+ exports.RESONANCE_GOOGLE_CONTENT_UPDATE_SELECTION_JSON_SCHEMA = RESONANCE_GOOGLE_CONTENT_UPDATE_SELECTION_JSON_SCHEMA;
3152
+ exports.RESONANCE_GOOGLE_DIAGNOSTICS_SECTIONS = RESONANCE_GOOGLE_DIAGNOSTICS_SECTIONS;
2727
3153
  exports.RESONANCE_GOOGLE_SETUP_SPEC_JSON_SCHEMA = RESONANCE_GOOGLE_SETUP_SPEC_JSON_SCHEMA;
2728
3154
  exports.RESONANCE_GOOGLE_SIGNAL_SEMANTICS = RESONANCE_GOOGLE_SIGNAL_SEMANTICS;
2729
3155
  exports.RESONANCE_GOOGLE_SOURCE_CATEGORIES = RESONANCE_GOOGLE_SOURCE_CATEGORIES;
@@ -2764,6 +3190,10 @@ exports.RESONANCE_METRIC_JSON_SCHEMA = RESONANCE_METRIC_JSON_SCHEMA;
2764
3190
  exports.RESONANCE_OBSERVATIONS_PAGE_JSON_SCHEMA = RESONANCE_OBSERVATIONS_PAGE_JSON_SCHEMA;
2765
3191
  exports.RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA = RESONANCE_OBSERVATION_SUPPORT_JSON_SCHEMA;
2766
3192
  exports.RESONANCE_OCCURRENCE_RESPONSE_JSON_SCHEMA = RESONANCE_OCCURRENCE_RESPONSE_JSON_SCHEMA;
3193
+ exports.RESONANCE_OPERATING_POLICY_BASE_JSON_SCHEMA = RESONANCE_OPERATING_POLICY_BASE_JSON_SCHEMA;
3194
+ exports.RESONANCE_OPERATING_POLICY_JSON_SCHEMA = RESONANCE_OPERATING_POLICY_JSON_SCHEMA;
3195
+ exports.RESONANCE_OPERATING_POLICY_REF_JSON_SCHEMA = RESONANCE_OPERATING_POLICY_REF_JSON_SCHEMA;
3196
+ exports.RESONANCE_OPERATING_POLICY_SELECTION_JSON_SCHEMA = RESONANCE_OPERATING_POLICY_SELECTION_JSON_SCHEMA;
2767
3197
  exports.RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA = RESONANCE_OPTIMIZATION_DECISION_JSON_SCHEMA;
2768
3198
  exports.RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA = RESONANCE_OPTIMIZATION_EVIDENCE_JSON_SCHEMA;
2769
3199
  exports.RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA = RESONANCE_OPTIMIZATION_POLICY_JSON_SCHEMA;
@@ -2774,9 +3204,14 @@ exports.RESONANCE_POSITIONING_METHOD_VERSION = RESONANCE_POSITIONING_METHOD_VERS
2774
3204
  exports.RESONANCE_POSITIONING_PREVIEW_JSON_SCHEMA = RESONANCE_POSITIONING_PREVIEW_JSON_SCHEMA;
2775
3205
  exports.RESONANCE_POSITIONING_PREVIEW_REQUEST_JSON_SCHEMA = RESONANCE_POSITIONING_PREVIEW_REQUEST_JSON_SCHEMA;
2776
3206
  exports.RESONANCE_POSITIONING_RESULT_JSON_SCHEMA = RESONANCE_POSITIONING_RESULT_JSON_SCHEMA;
3207
+ exports.RESONANCE_PREPARATION_LOOKUP_REQUEST_JSON_SCHEMA = RESONANCE_PREPARATION_LOOKUP_REQUEST_JSON_SCHEMA;
3208
+ exports.RESONANCE_PREPARATION_LOOKUP_RESPONSE_JSON_SCHEMA = RESONANCE_PREPARATION_LOOKUP_RESPONSE_JSON_SCHEMA;
3209
+ exports.RESONANCE_PREPARATION_RETIRE_REQUEST_JSON_SCHEMA = RESONANCE_PREPARATION_RETIRE_REQUEST_JSON_SCHEMA;
3210
+ exports.RESONANCE_PREPARATION_RETIRE_RESPONSE_JSON_SCHEMA = RESONANCE_PREPARATION_RETIRE_RESPONSE_JSON_SCHEMA;
2777
3211
  exports.RESONANCE_PREPARED_PLAN_JSON_SCHEMA = RESONANCE_PREPARED_PLAN_JSON_SCHEMA;
2778
3212
  exports.RESONANCE_PROVIDER_METRIC_NAMES = RESONANCE_PROVIDER_METRIC_NAMES;
2779
3213
  exports.RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA = RESONANCE_PROVIDER_REPORTING_GRANT_JSON_SCHEMA;
3214
+ exports.RESONANCE_PROVIDER_REPORTING_MAX_TAIL_DAYS = RESONANCE_PROVIDER_REPORTING_MAX_TAIL_DAYS;
2780
3215
  exports.RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA = RESONANCE_PROVIDER_REPORTING_SELECTION_JSON_SCHEMA;
2781
3216
  exports.RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA = RESONANCE_PUBLIC_OBSERVATION_METRIC_JSON_SCHEMA;
2782
3217
  exports.RESONANCE_QUALIFICATION_RULE_JSON_SCHEMA = RESONANCE_QUALIFICATION_RULE_JSON_SCHEMA;
@@ -2810,7 +3245,9 @@ exports.googleUploadClicksSetupSemantics = googleUploadClicksSetupSemantics;
2810
3245
  exports.metaExclusionPolicy = metaExclusionPolicy;
2811
3246
  exports.moneyFromProviderUnits = moneyFromProviderUnits;
2812
3247
  exports.moneyToProviderUnits = moneyToProviderUnits;
3248
+ exports.normalizeResonanceGoogleCriterionText = normalizeResonanceGoogleCriterionText;
2813
3249
  exports.parseMoney = parseMoney;
3250
+ exports.parseNativeCasTimestamp = parseNativeCasTimestamp;
2814
3251
  exports.parseResonanceAcceptCommand = parseResonanceAcceptCommand;
2815
3252
  exports.parseResonanceAccountCapability = parseResonanceAccountCapability;
2816
3253
  exports.parseResonanceAudienceDraftSaveCommand = parseResonanceAudienceDraftSaveCommand;
@@ -2835,11 +3272,16 @@ exports.parseResonanceExperimentLifecycleCommand = parseResonanceExperimentLifec
2835
3272
  exports.parseResonanceExperimentLinkCommand = parseResonanceExperimentLinkCommand;
2836
3273
  exports.parseResonanceExperimentRef = parseResonanceExperimentRef;
2837
3274
  exports.parseResonanceExperimentUpdateCommand = parseResonanceExperimentUpdateCommand;
3275
+ exports.parseResonanceGoogleCampaignDiagnosticsPayload = parseResonanceGoogleCampaignDiagnosticsPayload;
3276
+ exports.parseResonanceGoogleCampaignDiagnosticsReport = parseResonanceGoogleCampaignDiagnosticsReport;
3277
+ exports.parseResonanceGoogleCampaignDiagnosticsRequest = parseResonanceGoogleCampaignDiagnosticsRequest;
2838
3278
  exports.parseResonanceGoogleConfigurationReview = parseResonanceGoogleConfigurationReview;
2839
3279
  exports.parseResonanceGoogleConfigurationSaveCommand = parseResonanceGoogleConfigurationSaveCommand;
2840
3280
  exports.parseResonanceGoogleConfigurationSaveResponse = parseResonanceGoogleConfigurationSaveResponse;
2841
3281
  exports.parseResonanceGoogleConfigurationSnapshot = parseResonanceGoogleConfigurationSnapshot;
2842
3282
  exports.parseResonanceGoogleConfigurationView = parseResonanceGoogleConfigurationView;
3283
+ exports.parseResonanceGoogleContentUpdate = parseResonanceGoogleContentUpdate;
3284
+ exports.parseResonanceGoogleContentUpdateSelection = parseResonanceGoogleContentUpdateSelection;
2843
3285
  exports.parseResonanceGoogleUploadClicksCustomGoalSpec = parseResonanceGoogleUploadClicksCustomGoalSpec;
2844
3286
  exports.parseResonanceMandateApprovalPayload = parseResonanceMandateApprovalPayload;
2845
3287
  exports.parseResonanceMandateDraftRequest = parseResonanceMandateDraftRequest;
@@ -2875,6 +3317,10 @@ exports.parseResonanceMetricObservation = parseResonanceMetricObservation;
2875
3317
  exports.parseResonanceObservationSupport = parseResonanceObservationSupport;
2876
3318
  exports.parseResonanceObservationsPage = parseResonanceObservationsPage;
2877
3319
  exports.parseResonanceOccurrenceResponse = parseResonanceOccurrenceResponse;
3320
+ exports.parseResonanceOperatingPolicy = parseResonanceOperatingPolicy;
3321
+ exports.parseResonanceOperatingPolicyBase = parseResonanceOperatingPolicyBase;
3322
+ exports.parseResonanceOperatingPolicyRef = parseResonanceOperatingPolicyRef;
3323
+ exports.parseResonanceOperatingPolicySelection = parseResonanceOperatingPolicySelection;
2878
3324
  exports.parseResonanceOptimizationDecision = parseResonanceOptimizationDecision;
2879
3325
  exports.parseResonanceOptimizationEvidence = parseResonanceOptimizationEvidence;
2880
3326
  exports.parseResonanceOptimizationPolicy = parseResonanceOptimizationPolicy;
@@ -2884,6 +3330,10 @@ exports.parseResonancePositioningContext = parseResonancePositioningContext;
2884
3330
  exports.parseResonancePositioningPreview = parseResonancePositioningPreview;
2885
3331
  exports.parseResonancePositioningPreviewRequest = parseResonancePositioningPreviewRequest;
2886
3332
  exports.parseResonancePositioningResult = parseResonancePositioningResult;
3333
+ exports.parseResonancePreparationLookupRequest = parseResonancePreparationLookupRequest;
3334
+ exports.parseResonancePreparationLookupResponse = parseResonancePreparationLookupResponse;
3335
+ exports.parseResonancePreparationRetireRequest = parseResonancePreparationRetireRequest;
3336
+ exports.parseResonancePreparationRetireResponse = parseResonancePreparationRetireResponse;
2887
3337
  exports.parseResonancePrepareCommand = parseResonancePrepareCommand;
2888
3338
  exports.parseResonancePreparedPlan = parseResonancePreparedPlan;
2889
3339
  exports.parseResonanceProviderReportingGrant = parseResonanceProviderReportingGrant;
@@ -2918,6 +3368,8 @@ exports.resonanceMetaAudienceSetupReceiptDigestInput = resonanceMetaAudienceSetu
2918
3368
  exports.resonanceMetaConfigurationDigestInput = resonanceMetaConfigurationDigestInput;
2919
3369
  exports.resonanceMetaConfigurationSaveDigestInput = resonanceMetaConfigurationSaveDigestInput;
2920
3370
  exports.resonanceMetaDatasetSetupDigestInput = resonanceMetaDatasetSetupDigestInput;
3371
+ exports.resonanceOperatingPolicyActionDigestInput = resonanceOperatingPolicyActionDigestInput;
3372
+ exports.resonanceOperatingPolicyDigestInput = resonanceOperatingPolicyDigestInput;
2921
3373
  exports.resonanceOptimizationDecisionDigestInput = resonanceOptimizationDecisionDigestInput;
2922
3374
  exports.resonanceOptimizationEvidenceDigestInput = resonanceOptimizationEvidenceDigestInput;
2923
3375
  exports.resonanceOptimizationPolicyDigestInput = resonanceOptimizationPolicyDigestInput;