@sonordev/contracts 2.28.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.
@@ -0,0 +1,2197 @@
1
+ // src/contracts/wire-schema.ts
2
+ function createWireSchema(fail5, isValidationError) {
3
+ const own = (v, k) => Object.prototype.hasOwnProperty.call(v, k);
4
+ const field4 = (schema, read) => ({ schema, read });
5
+ const text5 = (max = 200, pattern, min = 1) => field4({ 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 : fail5(p, "invalid string"));
6
+ const choice4 = (...values) => field4({ type: "string", enum: values }, (v, p) => typeof v === "string" && values.includes(v) ? v : fail5(p, "unsupported value"));
7
+ const literal4 = (value) => field4({ const: value }, (v, p) => v === value ? value : fail5(p, "unexpected value"));
8
+ const integer4 = (min = 0, max = Number.MAX_SAFE_INTEGER) => field4({ type: "integer", minimum: min, maximum: max }, (v, p) => typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max ? v : fail5(p, "invalid integer"));
9
+ const bool3 = field4({ type: "boolean" }, (v, p) => typeof v === "boolean" ? v : fail5(p, "must be boolean"));
10
+ const optional3 = (f) => ({ ...f, optional: true });
11
+ const nullable4 = (f) => field4({ anyOf: [f.schema, { type: "null" }] }, (v, p) => v === null ? null : f.read(v, p));
12
+ const list4 = (f, max = 100, min = 0) => field4({ type: "array", items: f.schema, minItems: min, maxItems: max }, (v, p) => {
13
+ if (!Array.isArray(v) || v.length < min || v.length > max) fail5(p, "invalid array");
14
+ return v.map((x, i) => f.read(x, `${p}[${i}]`));
15
+ });
16
+ const object4 = (fields2) => field4({ 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) => {
17
+ if (!v || typeof v !== "object" || Array.isArray(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) fail5(p, "must be a plain object");
18
+ const source2 = v, result = {};
19
+ for (const key of Reflect.ownKeys(source2)) if (typeof key !== "string" || !own(fields2, key)) fail5(p, "unknown field");
20
+ for (const [key, f] of Object.entries(fields2)) {
21
+ if (!own(source2, key)) {
22
+ if ("optional" in f) continue;
23
+ fail5(`${p}.${key}`, "required");
24
+ }
25
+ const descriptor = Object.getOwnPropertyDescriptor(source2, key);
26
+ if (!own(descriptor, "value")) fail5(`${p}.${key}`, "accessors are not wire data");
27
+ result[key] = f.read(descriptor.value, `${p}.${key}`);
28
+ }
29
+ return result;
30
+ });
31
+ const union4 = (...fields2) => field4({ oneOf: fields2.map((f) => f.schema) }, (v, p) => {
32
+ const found = [];
33
+ for (const f of fields2) {
34
+ try {
35
+ found.push(f.read(v, p));
36
+ } catch (e) {
37
+ if (!isValidationError(e)) throw e;
38
+ }
39
+ }
40
+ return found.length === 1 ? found[0] : fail5(p, "must match exactly one supported shape");
41
+ });
42
+ const refine5 = (f, check) => field4(f.schema, (v, p) => {
43
+ const result = f.read(v, p);
44
+ check(result, p);
45
+ return result;
46
+ });
47
+ return { field: field4, text: text5, choice: choice4, literal: literal4, integer: integer4, bool: bool3, optional: optional3, nullable: nullable4, list: list4, object: object4, union: union4, refine: refine5 };
48
+ }
49
+
50
+ // src/contracts/wire-uuid.ts
51
+ var UUID_V1_TO_V8_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
52
+
53
+ // src/contracts/sites-normalize.ts
54
+ function normalizeSiteHost(site3) {
55
+ if (!site3 || typeof site3 !== "string") return null;
56
+ let s = site3.trim().toLowerCase();
57
+ if (!s) return null;
58
+ s = s.replace(/^https?:\/\//, "");
59
+ const slash = s.indexOf("/");
60
+ if (slash >= 0) s = s.slice(0, slash);
61
+ const colon = s.indexOf(":");
62
+ if (colon >= 0) s = s.slice(0, colon);
63
+ s = s.replace(/\.+$/, "");
64
+ return s || null;
65
+ }
66
+
67
+ // src/contracts/sites.ts
68
+ function isNormalizedSiteHost(value) {
69
+ return typeof value === "string" && value.length > 0 && normalizeSiteHost(value) === value;
70
+ }
71
+
72
+ // src/contracts/public-url-host.ts
73
+ function isPrivateIpv4(a, b) {
74
+ return a === 127 || a === 10 || a === 0 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a >= 224;
75
+ }
76
+ function ipv6Words(host) {
77
+ if (!host.includes(":") || !/^[a-f\d:.]+$/.test(host)) return null;
78
+ let canonical2;
79
+ try {
80
+ canonical2 = new URL(`http://[${host}]/`).hostname.slice(1, -1);
81
+ } catch {
82
+ return null;
83
+ }
84
+ const sides = canonical2.split("::");
85
+ const left = sides[0] ? sides[0].split(":") : [];
86
+ const right = sides.length > 1 && sides[1] ? sides[1].split(":") : [];
87
+ return [...left, ...Array(sides.length > 1 ? 8 - left.length - right.length : 0).fill("0"), ...right].map((word) => parseInt(word, 16));
88
+ }
89
+ function isBlockedPublicUrlHost(rawHost) {
90
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
91
+ const blockedName = host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
92
+ if (host.includes(":") && host.includes("%")) return true;
93
+ const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
94
+ const blockedIp = !!ipv4 && isPrivateIpv4(Number(ipv4[1]), Number(ipv4[2]));
95
+ const words = ipv6Words(host);
96
+ const blockedIpv6 = !!words && // Unspecified/loopback, unique-local, link-local, deprecated site-local
97
+ // and multicast destinations aren't public logo/webhook endpoints.
98
+ (words.every((word) => word === 0) || words.slice(0, 7).every((word) => word === 0) && words[7] === 1 || (words[0] & 65024) === 64512 || (words[0] & 65472) === 65152 || (words[0] & 65472) === 65216 || (words[0] & 65280) === 65280 || // IPv4-mapped and older IPv4-compatible forms carry an IPv4 destination.
99
+ words.slice(0, 5).every((word) => word === 0) && [0, 65535].includes(words[5]) && isPrivateIpv4(words[6] >> 8, words[6] & 255));
100
+ return blockedName || blockedIp || blockedIpv6;
101
+ }
102
+
103
+ // src/contracts/resonance-constants.ts
104
+ var RESONANCE_ATTRIBUTION_MODEL = "first_party_last_touch_marker_v1";
105
+ var RESONANCE_SOURCE_MARKER_PARAMETER = "sonor_source";
106
+
107
+ // src/contracts/wire-native-cas.ts
108
+ var NativeCasTimestampValidationError = class extends Error {
109
+ constructor(path2, reason) {
110
+ super(`${path2}: ${reason}`);
111
+ this.path = path2;
112
+ this.name = "NativeCasTimestampValidationError";
113
+ }
114
+ };
115
+ var fail = (path2, reason) => {
116
+ throw new NativeCasTimestampValidationError(path2, reason);
117
+ };
118
+ var { text, refine } = createWireSchema(fail, (error) => error instanceof NativeCasTimestampValidationError);
119
+ 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) => {
120
+ const calendar = v.slice(0, 19) + "Z";
121
+ 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");
122
+ });
123
+ var parseNativeCasTimestamp = (v) => timestamp.read(v, "nativeCasTimestamp");
124
+ var NATIVE_CAS_TIMESTAMP_JSON_SCHEMA = timestamp.schema;
125
+
126
+ // src/contracts/signal-experiments.ts
127
+ var SignalExperimentValidationError = class extends Error {
128
+ constructor(path2, reason) {
129
+ super(`${path2}: ${reason}`);
130
+ this.path = path2;
131
+ this.name = "SignalExperimentValidationError";
132
+ }
133
+ };
134
+ var fail2 = (path2, reason) => {
135
+ throw new SignalExperimentValidationError(path2, reason);
136
+ };
137
+ var { field, text: text2, choice, literal, integer, optional, nullable, list, object, union, refine: refine2 } = createWireSchema(fail2, (error) => error instanceof SignalExperimentValidationError);
138
+ 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"));
139
+ var page = refine2(text2(2048, /^\/(?!\/)[^?#\s\\]*$/), (v, p) => {
140
+ const parsed = new URL(v, "https://example.com");
141
+ if (parsed.pathname !== v) fail2(p, "must be a canonical page path");
142
+ });
143
+ var variant = object({ key: text2(80), name: text2(160), weight: percent, description: optional(text2(1e3, void 0, 0)) });
144
+ var variants = refine2(list(variant, 50, 2), (v, p) => {
145
+ if (new Set(v.map((x) => x.key)).size !== v.length) fail2(p, "variant keys must be unique");
146
+ if (Math.abs(v.reduce((sum, x) => sum + x.weight, 0) - 100) > 0.01) fail2(p, "variant weights must sum to 100");
147
+ });
148
+ 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)) });
149
+ var fields = { name: text2(160), description: text2(1e4, void 0, 0), variants, traffic_allocation: percent, targeting_rules: targeting };
150
+ var create = object({ ...fields, description: optional(fields.description), traffic_allocation: optional(fields.traffic_allocation), targeting_rules: optional(fields.targeting_rules) });
151
+ 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) });
152
+ var parseSignalExperimentCreate = (v) => create.read(v, "experimentCreate");
153
+ var parseSignalExperimentUpdate = (v) => update.read(v, "experimentUpdate");
154
+ var SIGNAL_EXPERIMENT_CREATE_JSON_SCHEMA = create.schema;
155
+ var SIGNAL_EXPERIMENT_UPDATE_JSON_SCHEMA = update.schema;
156
+ var measurementUuid = text2(36, UUID_V1_TO_V8_PATTERN);
157
+ var measurementRevision = text2(128, /^[a-zA-Z0-9._:-]+$/);
158
+ var measurementInstant = refine2(text2(30, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (v, p) => {
159
+ if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().replace(".000Z", "Z") !== v.replace(".000Z", "Z")) fail2(p, "invalid UTC instant");
160
+ });
161
+ var measurementSite = refine2(text2(253), (v, p) => {
162
+ if (!isNormalizedSiteHost(v) || isBlockedPublicUrlHost(v)) fail2(p, "must be a normalized public site host");
163
+ });
164
+ var measurementCount = text2(30, /^(?:0|[1-9][0-9]*)$/);
165
+ var measurementScope = object({
166
+ projectId: measurementUuid,
167
+ experimentId: measurementUuid,
168
+ site: measurementSite,
169
+ experimentRevision: integer(1),
170
+ goalRevision: measurementRevision,
171
+ campaignId: measurementUuid,
172
+ campaignVersionId: measurementUuid,
173
+ assignedFrom: measurementInstant,
174
+ assignedTo: measurementInstant
175
+ });
176
+ var assignmentCounts = {
177
+ variantKey: text2(80),
178
+ assignedUnits: measurementCount,
179
+ exposureEvents: measurementCount,
180
+ exposedUnits: measurementCount,
181
+ matureAssignedUnits: measurementCount,
182
+ immatureAssignedUnits: measurementCount,
183
+ assignmentsWithoutExposure: measurementCount
184
+ };
185
+ var availableVariant = object({ ...assignmentCounts, acceptedFormEvents: measurementCount, acceptedFormUnits: measurementCount, matureAcceptedFormUnits: measurementCount });
186
+ var unsupportedVariant = object({ ...assignmentCounts, acceptedFormEvents: literal(null), acceptedFormUnits: literal(null), matureAcceptedFormUnits: literal(null) });
187
+ var businessMetrics = object({
188
+ uniqueQualifiedContacts: object({ state: literal("unavailable"), reasonCode: literal("original_qualified_lineage_not_bound") }),
189
+ wonValue: object({ state: literal("unavailable"), reasonCode: literal("original_deal_lineage_not_bound") }),
190
+ paidRevenue: object({ state: literal("unavailable"), reasonCode: literal("original_paid_source_lineage_not_bound") })
191
+ });
192
+ var goalCountingUnit = choice("unique_source", "unique_qualified_contact", "net_order");
193
+ var originalGoalFields = { sourceId: measurementUuid, sourceRevision: measurementRevision, countingUnit: goalCountingUnit };
194
+ var formSourceKind = choice("accepted_form", "qualified_lead");
195
+ var unsupportedSourceKind = choice("completed_booking", "net_paid_order", "approved_application");
196
+ var observedFields = {
197
+ schemaVersion: literal(1),
198
+ mode: literal("trusted_source"),
199
+ state: literal("observed"),
200
+ observedAt: measurementInstant,
201
+ scope: measurementScope,
202
+ countingUnit: literal("consent_subject"),
203
+ coverage: literal("assigned_population_only"),
204
+ semanticRole: literal("accepted_form_diagnostic"),
205
+ businessMetrics
206
+ };
207
+ var observedMeasurement = refine2(union(
208
+ object({
209
+ ...observedFields,
210
+ originalGoal: object({ ...originalGoalFields, sourceKind: formSourceKind }),
211
+ diagnosticType: literal("accepted_form"),
212
+ diagnosticState: literal("available"),
213
+ variants: list(availableVariant, 50)
214
+ }),
215
+ object({
216
+ ...observedFields,
217
+ originalGoal: object({ ...originalGoalFields, sourceKind: unsupportedSourceKind }),
218
+ diagnosticType: literal(null),
219
+ diagnosticState: literal("unsupported_original_source"),
220
+ variants: list(unsupportedVariant, 50)
221
+ })
222
+ ), (value, p) => {
223
+ if (Date.parse(value.scope.assignedFrom) >= Date.parse(value.scope.assignedTo) || Date.parse(value.scope.assignedTo) > Date.parse(value.observedAt))
224
+ fail2(p + ".scope", "requires an increasing assignment cohort ending by the native observation");
225
+ if (new Set(value.variants.map((v) => v.variantKey)).size !== value.variants.length) fail2(p + ".variants", "variant keys must be unique");
226
+ for (const [index, v] of value.variants.entries()) {
227
+ const assigned = BigInt(v.assignedUnits), exposed = BigInt(v.exposedUnits), mature = BigInt(v.matureAssignedUnits);
228
+ const at = `${p}.variants[${index}]`;
229
+ if (exposed > assigned || BigInt(v.exposureEvents) < exposed || BigInt(v.assignmentsWithoutExposure) !== assigned - exposed || mature + BigInt(v.immatureAssignedUnits) !== assigned)
230
+ fail2(at, "assignment, exposure and maturity counts are inconsistent");
231
+ if (v.acceptedFormUnits !== null && v.acceptedFormEvents !== null && v.matureAcceptedFormUnits !== null) {
232
+ const accepted = BigInt(v.acceptedFormUnits), matureAccepted = BigInt(v.matureAcceptedFormUnits);
233
+ if (accepted > exposed || accepted > BigInt(v.acceptedFormEvents) || matureAccepted > mature || matureAccepted > accepted)
234
+ fail2(at, "accepted form units must remain within their exposed, event and mature cohorts");
235
+ }
236
+ }
237
+ });
238
+ var measurement = union(
239
+ object({ schemaVersion: literal(1), mode: literal("legacy"), state: literal("unavailable"), reasonCode: literal("legacy_assignment_outcome_events_only") }),
240
+ object({ schemaVersion: literal(1), mode: literal("trusted_source"), state: literal("unavailable"), reasonCode: literal("measurement_scope_required") }),
241
+ observedMeasurement
242
+ );
243
+ measurement.schema;
244
+ var scopeOption = object({
245
+ campaignId: measurementUuid,
246
+ campaignVersionId: measurementUuid,
247
+ campaignDefinitionRevision: integer(1),
248
+ acceptedAt: measurementInstant,
249
+ site: measurementSite,
250
+ experimentId: measurementUuid,
251
+ experimentRevision: integer(1),
252
+ goalRevision: measurementRevision,
253
+ goalLabel: nullable(text2(200)),
254
+ assignmentExtent: nullable(object({ firstAssignedAt: measurementInstant, lastAssignedAt: measurementInstant })),
255
+ suggestedCohort: nullable(object({ assignedFrom: measurementInstant, assignedTo: measurementInstant }))
256
+ });
257
+ var scopeOptions = refine2(object({ observedAt: measurementInstant, items: list(scopeOption, 100), nextCursor: nullable(text2(4096)) }), (value, p) => {
258
+ const observed = Date.parse(value.observedAt), tuples = /* @__PURE__ */ new Set();
259
+ for (const [index, item] of value.items.entries()) {
260
+ const at = `${p}.items[${index}]`, accepted = Date.parse(item.acceptedAt);
261
+ const tuple = JSON.stringify([
262
+ item.campaignId.toLowerCase(),
263
+ item.campaignVersionId.toLowerCase(),
264
+ item.site,
265
+ item.experimentId.toLowerCase(),
266
+ item.experimentRevision,
267
+ item.goalRevision
268
+ ]);
269
+ if (tuples.has(tuple)) fail2(at, "original scope tuples must be unique");
270
+ tuples.add(tuple);
271
+ if (accepted > observed) fail2(at + ".acceptedAt", "must not follow the native observation");
272
+ if (item.assignmentExtent) {
273
+ const first = Date.parse(item.assignmentExtent.firstAssignedAt), last = Date.parse(item.assignmentExtent.lastAssignedAt);
274
+ if (first > last || last > observed) fail2(at + ".assignmentExtent", "requires first <= last <= native observation");
275
+ }
276
+ if (item.suggestedCohort) {
277
+ const from = Date.parse(item.suggestedCohort.assignedFrom), to = Date.parse(item.suggestedCohort.assignedTo);
278
+ if (from !== accepted || from >= to || to > observed) fail2(at + ".suggestedCohort", "requires original acceptance start and increasing cohort ending by native observation");
279
+ }
280
+ }
281
+ });
282
+ scopeOptions.schema;
283
+
284
+ // src/contracts/campaign-normalize.ts
285
+ function normalizeCampaignSlug(input) {
286
+ if (!input || typeof input !== "string") return null;
287
+ const slug = input.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
288
+ return slug || null;
289
+ }
290
+
291
+ // src/contracts/resonance.ts
292
+ var ResonanceValidationError = class extends Error {
293
+ constructor(path2, reason) {
294
+ super(`${path2}: ${reason}`);
295
+ this.path = path2;
296
+ this.name = "ResonanceValidationError";
297
+ }
298
+ };
299
+ var fail3 = (path2, reason) => {
300
+ throw new ResonanceValidationError(path2, reason);
301
+ };
302
+ 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);
303
+ var uuid = text3(36, UUID_V1_TO_V8_PATTERN);
304
+ var digest = text3(64, /^[a-f0-9]{64}$/);
305
+ var revision = text3(128, /^[a-zA-Z0-9._:-]+$/);
306
+ var instant = refine3(text3(30, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (v, p) => {
307
+ if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().replace(".000Z", "Z") !== v.replace(".000Z", "Z")) fail3(p, "invalid UTC instant");
308
+ });
309
+ var timeZone = refine3(text3(80), (v, p) => {
310
+ try {
311
+ new Intl.DateTimeFormat("en", { timeZone: v });
312
+ } catch {
313
+ fail3(p, "invalid IANA timezone");
314
+ }
315
+ });
316
+ var site = refine3(text3(253), (v, p) => {
317
+ if (!isNormalizedSiteHost(v) || isBlockedPublicUrlHost(v)) fail3(p, "must be a normalized public site host");
318
+ });
319
+ var path = text3(2048, /^\/(?!\/)[^?#\s\\]*$/);
320
+ var decimal = text3(30, /^(?:0|[1-9][0-9]{0,29})$/);
321
+ var operationKey = text3(200, /^[a-zA-Z0-9._:-]+$/);
322
+ var objectiveCountingUnit = choice2("unique_source", "unique_qualified_contact", "net_order");
323
+ 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"];
324
+ var currency = choice2(...RESONANCE_CURRENCIES);
325
+ var money = object2({ currency, amountMicros: decimal });
326
+ money.schema;
327
+ var sourceMarker = text3(1536, /^rsm1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/);
328
+ sourceMarker.schema;
329
+ var scope = { projectId: uuid, site };
330
+ var resource = object2({ ...scope, module: choice2("funnel", "broadcast", "outreach", "experiment", "files", "business_brain", "publication", "crm", "commerce", "forms", "booking", "prepared_plan"), id: uuid, revision, digest });
331
+ var source = object2({ ...scope, kind: choice2("accepted_form", "qualified_lead", "completed_booking", "net_paid_order", "approved_application"), id: uuid, revision });
332
+ var qualificationFields = { schemaVersion: literal2(1), semantics: literal2("current_at_observation"), positiveStageKeys: list2(revision, 500), finalNegativeStageKeys: list2(revision, 500), pendingStageKeys: list2(revision, 500), existingContactPolicy: literal2("include_source_cohort") };
333
+ var checkQualificationPartitions = (v, p) => {
334
+ unique([...v.positiveStageKeys, ...v.finalNegativeStageKeys, ...v.pendingStageKeys], p + ".stagePartitions");
335
+ };
336
+ var qualificationRule = refine3(object2({ ...qualificationFields, attributionModel: literal2(RESONANCE_ATTRIBUTION_MODEL) }), checkQualificationPartitions);
337
+ qualificationRule.schema;
338
+ var resolvedQualificationRule = refine3(object2({
339
+ ...qualificationFields,
340
+ ref: resource,
341
+ crmVariant: text3(128),
342
+ ladderSnapshot: list2(object2({ id: nullable2(uuid), stage_key: revision, semantic_key: nullable2(revision), is_won: bool, is_lost: bool }), 500, 1),
343
+ // eligibleBookingTypeIds: Sync booking types whose confirmed bookings also count, beside the one form. Absent means forms only.
344
+ eligibleFormIds: list2(uuid, 500, 1),
345
+ eligibleBookingTypeIds: optional2(list2(uuid, 100, 1)),
346
+ attribution: object2({ model: literal2(RESONANCE_ATTRIBUTION_MODEL), resolverRevision: literal2(1) }),
347
+ cohort: object2({ startAt: instant, endAt: instant, maturityDelaySeconds: integer2(0, 31536e3) })
348
+ }), (v, p) => {
349
+ checkQualificationPartitions(v, p);
350
+ if (v.ref.module !== "crm" || v.ref.id !== v.ref.projectId) fail3(p + ".ref", "must reference the actual CRM project configuration");
351
+ unique(v.eligibleFormIds, p + ".eligibleFormIds");
352
+ if (v.eligibleBookingTypeIds) unique(v.eligibleBookingTypeIds.map((x) => x.toLowerCase()), p + ".eligibleBookingTypeIds");
353
+ unique(v.ladderSnapshot.flatMap((x) => x.id ? [x.id] : []), p + ".ladderSnapshot.id");
354
+ unique(v.ladderSnapshot.map((x) => x.stage_key), p + ".ladderSnapshot.stage_key");
355
+ const partitions = [...v.positiveStageKeys, ...v.finalNegativeStageKeys, ...v.pendingStageKeys], keys = new Set(v.ladderSnapshot.map((x) => x.stage_key));
356
+ if (partitions.length !== keys.size || partitions.some((k) => !keys.has(k))) fail3(p + ".stagePartitions", "must exhaust the actual native ladder");
357
+ if (Date.parse(v.cohort.endAt) <= Date.parse(v.cohort.startAt)) fail3(p + ".cohort", "invalid cohort interval");
358
+ });
359
+ resolvedQualificationRule.schema;
360
+ var objective = refine3(object2({
361
+ source,
362
+ measurementRevision: revision,
363
+ countingUnit: objectiveCountingUnit,
364
+ attributionWindowDays: integer2(1, 365),
365
+ maturityDelaySeconds: integer2(0, 31536e3),
366
+ qualificationRuleRef: nullable2(resource),
367
+ qualificationRule: optional2(qualificationRule),
368
+ // Booking types a person reviewed as counting toward the qualified-lead goal, beside its one form. Absent keeps the goal forms-only and the serialization unchanged.
369
+ eligibleBookingTypeIds: optional2(list2(uuid, 100, 1))
370
+ }), (v, p) => {
371
+ if (v.eligibleBookingTypeIds) {
372
+ if (v.source.kind !== "qualified_lead") fail3(p + ".eligibleBookingTypeIds", "requires the native qualified-lead source");
373
+ unique(v.eligibleBookingTypeIds.map((x) => x.toLowerCase()), p + ".eligibleBookingTypeIds");
374
+ }
375
+ if (v.qualificationRule && v.source.kind !== "qualified_lead") fail3(p + ".qualificationRule", "requires the native qualified-lead source");
376
+ if (v.qualificationRule && v.qualificationRuleRef && (v.qualificationRuleRef.module !== "crm" || v.qualificationRuleRef.id !== v.source.projectId)) fail3(p + ".qualificationRuleRef", "must reference actual CRM project configuration");
377
+ });
378
+ var creative = object2({ id: uuid, assetRef: resource, preparedArtifactRef: nullable2(resource), headline: text3(160), body: text3(1e4), callToAction: text3(80), cropDigest: digest });
379
+ var destination = union2(
380
+ object2({ kind: literal2("funnel"), id: uuid, ...scope, path, funnelRef: resource, formSlug: text3(80, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), installationRevision: revision }),
381
+ object2({ kind: literal2("existing_page"), id: uuid, ...scope, path, pageRevision: revision, evidenceDigest: digest })
382
+ );
383
+ 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") });
384
+ var experiment = object2({ ...scope, id: uuid, revision: integer2(1), digest });
385
+ 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) => {
386
+ if (Date.parse(v.endAt) <= Date.parse(v.startAt)) fail3(p, "end must follow start");
387
+ for (const m of [v.reserveMargin, v.maxChange, ...v.dailyAllocationCeiling ? [v.dailyAllocationCeiling] : []]) if (m.currency !== v.total.currency) fail3(p, "currency mismatch");
388
+ if (BigInt(v.reserveMargin.amountMicros) > BigInt(v.total.amountMicros)) fail3(p, "reserve exceeds total");
389
+ });
390
+ var allocationPolicyFields = {
391
+ schemaVersion: literal2(1),
392
+ sourceRef: nullable2(resource),
393
+ decisionKind: literal2("observational_allocation"),
394
+ eligibleGoal: literal2("qualified_lead"),
395
+ algorithm: literal2("mature_cpql_conserved_transfer_v1"),
396
+ minimumMatureExposures: integer2(1),
397
+ minimumMatureOutcomes: integer2(1),
398
+ minimumCoverageBasisPoints: integer2(0, 1e4),
399
+ maxEvidenceAgeSeconds: integer2(1),
400
+ maturityDelaySeconds: integer2(0),
401
+ cooldownSeconds: integer2(0),
402
+ donorTransferBasisPoints: integer2(1, 1e4),
403
+ maxUncertaintyBasisPoints: integer2(0, 1e4),
404
+ uncertaintyMethod: literal2("observational_cpql_missing_outcome_bound_v1"),
405
+ attributionModel: choice2("first_party_source", "first_touch", "last_touch", "provider_reported", RESONANCE_ATTRIBUTION_MODEL),
406
+ requiredChecks: list2(choice2("tracking", "dedupe", "qualification", "uncertainty", "assignment", "power"), 6, 1)
407
+ };
408
+ var matureOptimizationPolicy = object2(allocationPolicyFields);
409
+ var reportedPolicyFields = { ...allocationPolicyFields, algorithm: literal2("reported_cpql_conserved_transfer_v1"), costBasis: literal2("provider_reported_snapshot_v1"), costRevisionRisk: literal2("accepted_provisional") };
410
+ var reportedOptimizationPolicy = object2({ ...reportedPolicyFields, readClockKind: literal2("sql_before_provider_read_lower_bound_v1") });
411
+ function uniqueList(item, max, min = 0) {
412
+ const base = list2(item, max, min);
413
+ return field2({ ...base.schema, uniqueItems: true }, (v, p) => {
414
+ const r = base.read(v, p);
415
+ unique(r, p);
416
+ return r;
417
+ });
418
+ }
419
+ var optimizationCheck = choice2("tracking", "dedupe", "qualification", "uncertainty", "assignment", "power");
420
+ var finiteCandidateAction = choice2("materialize_and_activate", "activate_held", "pause_candidate");
421
+ var finiteStopRule = choice2("exploration_cap", "flight_end", "policy_or_mandate_expiry", "kill", "candidate_identity_or_settings_drift", "source_or_consent_invalid", "required_tracking_unavailable_or_stale", "unknown_effect");
422
+ var positiveMicrosPattern = /^[1-9][0-9]*(?![\s\S])/;
423
+ var positiveMoneyShape = field2({ allOf: [money.schema, { properties: { amountMicros: { pattern: positiveMicrosPattern.source } } }] }, (v, p) => {
424
+ const m = money.read(v, p);
425
+ if (!positiveMicrosPattern.test(m.amountMicros)) fail3(p, "requires positive canonical money");
426
+ return m;
427
+ });
428
+ var finiteMetaCandidatePolicy = object2({
429
+ schemaVersion: literal2(1),
430
+ algorithm: literal2("finite_meta_candidates_v1"),
431
+ decisionKind: literal2("preapproved_candidate_operation"),
432
+ eligibleGoal: literal2("qualified_lead"),
433
+ sourceRef: nullable2(resource),
434
+ candidateChannelIds: uniqueList(uuid, 100, 1),
435
+ selection: object2({ kind: literal2("fixed_reviewed_order"), candidateOrder: uniqueList(uuid, 100, 1), eligibilitySchedule: list2(object2({ channelId: uuid, notBefore: instant, notAfter: instant }), 100, 1) }),
436
+ allowedActions: uniqueList(finiteCandidateAction, 3, 1),
437
+ maxConcurrentCandidates: integer2(1, 100),
438
+ maxActivationsPerCandidate: literal2(1),
439
+ totalExplorationCap: positiveMoneyShape,
440
+ measurementGuard: object2({ sourceRef: source, qualificationRuleRef: resource, attributionModel: literal2(RESONANCE_ATTRIBUTION_MODEL), maturityDelaySeconds: integer2(0, 31536e3), minimumCoverageBasisPoints: integer2(0, 1e4), maxEvidenceAgeSeconds: integer2(1), requiredChecks: uniqueList(optimizationCheck, 6, 1) }),
441
+ performanceDecisionPolicy: literal2(null),
442
+ stopRules: uniqueList(finiteStopRule, 8, 8),
443
+ expiresAt: instant
444
+ });
445
+ var optimizationPolicy = union2(matureOptimizationPolicy, finiteMetaCandidatePolicy, reportedOptimizationPolicy);
446
+ optimizationPolicy.schema;
447
+ var optimization = object2({ enabled: bool, policy: optimizationPolicy, stopLoss: object2({ confirmedSpend: money, unreconciledExposure: money }) });
448
+ var channelBase = { id: uuid, ...scope, destinationId: uuid, creativeIds: list2(uuid, 50, 1) };
449
+ 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") });
450
+ var metaAgeConstraint = union2(refine3(object2({ mode: literal2("bounded"), min: integer2(1, 120), max: integer2(1, 120) }), (v, p) => {
451
+ if (v.min > v.max) fail3(p, "minimum age exceeds maximum");
452
+ }), object2({ mode: literal2("omitted") }), object2({ mode: literal2("provider_managed") }));
453
+ var propertyKey = object2({ key: text3(40, /^[a-z0-9]+(?:-[a-z0-9]+)*$/), label: text3(80) });
454
+ var meta = object2({
455
+ ...channelBase,
456
+ localCampaignKey: text3(80),
457
+ kind: literal2("meta_retargeting"),
458
+ provider: literal2("meta_ads"),
459
+ accountBindingId: uuid,
460
+ capabilityRevision: revision,
461
+ allocation: money,
462
+ budgetMode: choice2("lifetime", "daily"),
463
+ audienceRuleRefs: list2(audience, 50, 1),
464
+ objective: choice2("OUTCOME_LEADS", "OUTCOME_SALES", "OUTCOME_TRAFFIC"),
465
+ pageRef: object2({ connectionId: uuid, externalId: text3(160), revision }),
466
+ instagramRef: nullable2(object2({ connectionId: uuid, externalId: text3(160), revision })),
467
+ datasetRef: object2({ id: text3(160), revision }),
468
+ conversionGoalRef: resource,
469
+ optimization: choice2("landing_page_views", "lead", "purchase"),
470
+ billing: literal2("impressions"),
471
+ bid: union2(object2({ strategy: literal2("lowest_cost") }), object2({ strategy: literal2("cost_cap"), cap: money })),
472
+ localAdSetKey: text3(80),
473
+ localAdKey: text3(80),
474
+ budgetOwner: choice2("campaign", "adset"),
475
+ specialCategories: list2(choice2("housing", "employment", "financial_products_services"), 3),
476
+ countryCodes: list2(text3(2, /^[A-Z]{2}$/), 30, 1),
477
+ placement: literal2("automatic"),
478
+ ageConstraint: optional2(metaAgeConstraint),
479
+ // 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.
480
+ channelGroup: optional2(propertyKey),
481
+ property: optional2(propertyKey),
482
+ tier: optional2(object2({ label: text3(40) })),
483
+ primaryText: optional2(text3(2200)),
484
+ convertersAcknowledged: optional2(literal2(true))
485
+ });
486
+ var owned = object2({ ...channelBase, kind: choice2("funnel", "broadcast", "outreach"), resourceRef: resource });
487
+ var channel = union2(search, meta, owned);
488
+ var definitionFields = { schemaVersion: literal2(1), projectId: uuid, name: text3(160), slug: refine3(text3(80), (v, p) => {
489
+ if (normalizeCampaignSlug(v) !== v) fail3(p, "must be canonical campaign slug");
490
+ }), 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 };
491
+ var definition = object2(definitionFields);
492
+ 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) });
493
+ function scoped(value, projectId, sites, at) {
494
+ if (!value || typeof value !== "object") return;
495
+ if (Array.isArray(value)) {
496
+ value.forEach((x, i) => scoped(x, projectId, sites, `${at}[${i}]`));
497
+ return;
498
+ }
499
+ const v = value;
500
+ if ("projectId" in v && v.projectId !== projectId) fail3(at, "cross-project reference");
501
+ if ("site" in v && !sites.includes(v.site)) fail3(at, "site outside campaign scope");
502
+ for (const [k, x] of Object.entries(v)) scoped(x, projectId, sites, `${at}.${k}`);
503
+ }
504
+ function unique(values, at) {
505
+ if (new Set(values).size !== values.length) fail3(at, "duplicate identity");
506
+ }
507
+ definition.schema;
508
+ draft.schema;
509
+ 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) });
510
+ var mandateRef = object2({ ledgerActionId: uuid, campaignId: uuid, preparedPlanId: uuid, reviewDigest: digest, mandateDigest: digest, expectedKillRevision: integer2(0) });
511
+ var websiteVisitMaxAgeMs = 3e5;
512
+ var RESONANCE_WEBSITE_VISIT_PROFILE = Object.freeze({
513
+ profile: "sonor_sdk_page_view_fresh_v1",
514
+ source: "sdk_reported_first_party_cookie",
515
+ assurance: "sdk_reported",
516
+ matchingFields: Object.freeze(["fbp", "fbc"]),
517
+ maxCaptureAgeMs: websiteVisitMaxAgeMs,
518
+ maxDispatchAgeMs: websiteVisitMaxAgeMs,
519
+ maxFutureSkewMs: 0,
520
+ browserServerPairing: "unsupported"
521
+ });
522
+ var measurementRuleRef = object2({ id: uuid, revision });
523
+ var measurementConfigRef = object2({ configRevision: revision, policyRevision: revision, digest });
524
+ var matchingProfileRef = object2({ id: uuid, revision: integer2(1), digest });
525
+ var mandateAllowedOperations = list2(choice2("launch", "update", "resume", "optimize", "deliver_conversion"), 5, 1);
526
+ var websiteVisitFeed = object2({ profile: literal2(RESONANCE_WEBSITE_VISIT_PROFILE.profile), channels: list2(object2({
527
+ channelId: uuid,
528
+ measurementConfigRef,
529
+ resourceRuleRefs: list2(measurementRuleRef, 500, 1),
530
+ matchingProfileRef
531
+ }), 100, 1) });
532
+ websiteVisitFeed.schema;
533
+ var providerReportingChannelIds = refine3(uniqueList(uuid, 100, 1), (ids, p) => unique(ids.map((id) => id.toLowerCase()), p));
534
+ var RESONANCE_META_QUERY_ATTRIBUTION_WINDOWS = ["1d_click", "7d_click", "1d_view"];
535
+ var metaReportingQuery = object2({ channelId: uuid, attributionWindow: choice2(...RESONANCE_META_QUERY_ATTRIBUTION_WINDOWS), actionReportTime: literal2("conversion"), basis: literal2("explicit_query") });
536
+ var providerReportingMetaQueries = refine3(list2(metaReportingQuery, 100, 1), (queries, p) => unique(queries.map((query) => query.channelId.toLowerCase()), p));
537
+ function checkReportingQuerySubset(v, p) {
538
+ if (v.metaQueries?.some((query) => !v.channelIds.some((id) => id.toLowerCase() === query.channelId.toLowerCase()))) fail3(p + ".metaQueries", "query channel must be selected");
539
+ }
540
+ var providerReportingSelection = refine3(object2({ agentContactId: uuid, channelIds: providerReportingChannelIds, metaQueries: optional2(providerReportingMetaQueries) }), checkReportingQuerySubset);
541
+ 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) => {
542
+ if (v.agentContactId.toLowerCase() === v.principalContactId.toLowerCase()) fail3(p + ".principalContactId", "agent and human principal must remain distinct");
543
+ checkReportingQuerySubset(v, p);
544
+ });
545
+ providerReportingSelection.schema;
546
+ providerReportingGrant.schema;
547
+ var googleContentTarget = { channelId: uuid, adGroupLocalKey: text3(80), adLocalKey: text3(80) };
548
+ var normalizeResonanceGoogleCriterionText = (value) => value.trim().replace(/\s+/gu, " ").toLowerCase().normalize("NFC");
549
+ var googleCriterionText = text3(80, /^(?! +$)[^\x00-\x1f\x7f]+$/);
550
+ var googleExactText = text3(80, /^(?! +$)[^\x00-\x1f\x7f\\\[\]"]+$/);
551
+ var googleContentKeywords = (criterion) => refine3(list2(criterion, 20), (items, p) => {
552
+ const normalized = items.map(normalizeResonanceGoogleCriterionText);
553
+ if (normalized.some((value) => !value || value.length > 80)) fail3(p, "requires nonempty bounded criterion text");
554
+ unique(normalized, p);
555
+ items.splice(0, items.length, ...normalized.sort());
556
+ });
557
+ var rsaAsset = (length) => refine3(text3(length, /^[^\x00-\x1f\x7f]+$/), (asset, p) => {
558
+ if (!asset.trim() || asset.trim() !== asset) fail3(p, "requires trimmed, nonempty asset text");
559
+ });
560
+ var googleContentRsa = object2({
561
+ creativeRef: resource,
562
+ headlines: uniqueList(rsaAsset(30), 15, 3),
563
+ descriptions: uniqueList(rsaAsset(90), 4, 2)
564
+ });
565
+ var googleContentMaterial = {
566
+ negativeRemovals: googleContentKeywords(googleCriterionText),
567
+ exactAdditions: googleContentKeywords(googleExactText),
568
+ rsa: nullable2(googleContentRsa)
569
+ };
570
+ var googleContentEntry = refine3(object2({ ...googleContentTarget, ...googleContentMaterial }), (entry, p) => {
571
+ if (!entry.negativeRemovals.length && !entry.exactAdditions.length && !entry.rsa) fail3(p, "must select at least one bounded content effect");
572
+ });
573
+ var googleSearchContent = refine3(list2(googleContentEntry, 100), (entries, p) => {
574
+ const identity = (entry) => JSON.stringify([entry.channelId.toLowerCase(), entry.adGroupLocalKey, entry.adLocalKey]);
575
+ unique(entries.map(identity), p);
576
+ entries.sort((a, b) => identity(a) < identity(b) ? -1 : identity(a) > identity(b) ? 1 : 0);
577
+ });
578
+ var operatingPolicyFields = {
579
+ schemaVersion: literal2(1),
580
+ agentContactId: uuid,
581
+ googleSearchContent,
582
+ cooldownSeconds: integer2(3600, 2592e3)
583
+ };
584
+ var operatingPolicySelection = object2(operatingPolicyFields);
585
+ var operatingPolicy = refine3(object2({ ...operatingPolicyFields, principalContactId: uuid }), (policy, p) => {
586
+ if (policy.agentContactId.toLowerCase() === policy.principalContactId.toLowerCase()) {
587
+ fail3(p + ".principalContactId", "agent and human principal must remain distinct");
588
+ }
589
+ });
590
+ var operatingPolicyRef = object2({ ledgerActionId: uuid, receiptId: uuid, digest });
591
+ var operatingPolicyBase = object2({
592
+ ledgerActionId: uuid,
593
+ acceptanceReceiptId: uuid,
594
+ expectedKillRevision: integer2(0),
595
+ previousOperatingPolicyRef: nullable2(operatingPolicyRef)
596
+ });
597
+ object2({ mandateDigest: digest, operatingPolicyBase });
598
+ var googleContentUpdateSelection = object2(googleContentTarget);
599
+ var googleContentUpdate = refine3(object2({ ...googleContentTarget, ...googleContentMaterial, policyRef: operatingPolicyRef, beforeDigest: digest }), (update2, p) => {
600
+ if (!update2.negativeRemovals.length && !update2.exactAdditions.length && !update2.rsa) fail3(p, "must select at least one bounded content effect");
601
+ });
602
+ operatingPolicy.schema;
603
+ operatingPolicySelection.schema;
604
+ operatingPolicyBase.schema;
605
+ operatingPolicyRef.schema;
606
+ googleContentUpdateSelection.schema;
607
+ googleContentUpdate.schema;
608
+ 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) });
609
+ object2({ occurredAt: instant, receivedAt: instant });
610
+ var RESONANCE_GOOGLE_SIGNAL_SEMANTICS = "qualified_at_observation_v1";
611
+ var googleSignalSemantics = literal2(RESONANCE_GOOGLE_SIGNAL_SEMANTICS);
612
+ var RESONANCE_GOOGLE_SOURCE_CATEGORIES = Object.freeze({ accepted_form: "SUBMIT_LEAD_FORM", qualified_lead: "QUALIFIED_LEAD", completed_booking: "BOOK_APPOINTMENT", net_paid_order: "PURCHASE", approved_application: "CONVERTED_LEAD" });
613
+ var googleSemanticsInput = object2({ sourceKind: choice2(...Object.keys(RESONANCE_GOOGLE_SOURCE_CATEGORIES)), counting: choice2("one", "every"), clickWindowDays: integer2(1, 90) });
614
+ function googleConversionActionSemantics(input) {
615
+ const v = googleSemanticsInput.read(input, "googleConversionActionSemantics");
616
+ return { type: "UPLOAD_CLICKS", category: RESONANCE_GOOGLE_SOURCE_CATEGORIES[v.sourceKind], countingType: v.counting === "one" ? "ONE_PER_CLICK" : "MANY_PER_CLICK", clickThroughLookbackWindowDays: v.clickWindowDays, primaryForGoal: false };
617
+ }
618
+ var googleSetupPolicyInput = object2({ source, countingUnit: objectiveCountingUnit, attributionWindowDays: integer2(1, 365) });
619
+ function googleUploadClicksSetupSemantics(input) {
620
+ const v = googleSetupPolicyInput.read(input, "googleSetupPolicy");
621
+ if (v.source.kind !== "qualified_lead" || v.countingUnit !== "unique_qualified_contact") fail3("googleSetupPolicy", "unsupported_counting_policy");
622
+ if (v.attributionWindowDays > 90) fail3("googleSetupPolicy.attributionWindowDays", "unsupported_attribution_window");
623
+ return { ...googleConversionActionSemantics({ sourceKind: v.source.kind, counting: "one", clickWindowDays: v.attributionWindowDays }), category: RESONANCE_GOOGLE_SOURCE_CATEGORIES.qualified_lead, countingType: "ONE_PER_CLICK" };
624
+ }
625
+ var googleGoalChoiceFields = {
626
+ externalId: text3(160, /^customers\/[0-9]+\/customConversionGoals\/[0-9]+$/),
627
+ actionIds: list2(text3(160, /^customers\/[0-9]+\/conversionActions\/[0-9]+$/), 100, 1)
628
+ };
629
+ var googleDeclarationChoiceFields = {
630
+ statement: literal2("DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING"),
631
+ category: choice2("general", "housing", "employment", "financial_products_services")
632
+ };
633
+ function normalizeGoogleGoal(value, at) {
634
+ unique(value.actionIds, at + ".actionIds");
635
+ value.actionIds.sort();
636
+ return value;
637
+ }
638
+ var googleSetupSpec = object2({
639
+ schemaVersion: literal2(1),
640
+ kind: literal2("google_upload_clicks_custom_goal_v1"),
641
+ signalSemantics: googleSignalSemantics,
642
+ goalLocalKey: literal2("setup:custom-goal"),
643
+ requestedGoalName: text3(160),
644
+ action: object2({
645
+ localKey: literal2("setup:conversion-action"),
646
+ requestedActionName: text3(160),
647
+ type: literal2("UPLOAD_CLICKS"),
648
+ category: literal2(RESONANCE_GOOGLE_SOURCE_CATEGORIES.qualified_lead),
649
+ countingType: literal2("ONE_PER_CLICK"),
650
+ clickThroughLookbackWindowDays: integer2(1, 90),
651
+ primaryForGoal: literal2(false)
652
+ }),
653
+ goalActionKey: literal2("setup:conversion-action"),
654
+ goalStrategy: literal2("exclusive_custom_goal_v1")
655
+ });
656
+ var googleSaveCommonFields = { schemaVersion: literal2(1), expectedCampaignRevision: integer2(1), expectedRevision: integer2(0), idempotencyKey: operationKey, signalSemantics: googleSignalSemantics, declaration: object2(googleDeclarationChoiceFields) };
657
+ var googleSave = union2(
658
+ object2({ ...googleSaveCommonFields, mode: literal2("existing"), nativeGoal: object2(googleGoalChoiceFields) }),
659
+ object2({ ...googleSaveCommonFields, mode: literal2("admitted_setup"), setupIntent: object2({ requestedGoalName: text3(160), requestedActionName: text3(160) }) })
660
+ );
661
+ var googleGoalDraft = object2({ ...googleGoalChoiceFields, name: nullable2(text3(200, void 0, 0)), revision: nullable2(digest) });
662
+ var googleGoalReviewed = object2({ ...googleGoalChoiceFields, name: text3(200, void 0, 0), revision: digest });
663
+ var googleDeclared = object2({
664
+ ...googleDeclarationChoiceFields,
665
+ creativeDigest: digest,
666
+ locationIds: list2(text3(80), 100, 1),
667
+ excludedLocationIds: list2(text3(80), 100),
668
+ declaredByActorId: uuid,
669
+ declaredAt: instant,
670
+ declaredForCampaignRevision: integer2(1)
671
+ });
672
+ var googleConfigurationFields = {
673
+ projectId: uuid,
674
+ campaignId: uuid,
675
+ channelId: uuid,
676
+ site,
677
+ accountBindingId: uuid,
678
+ configurationRevision: integer2(1),
679
+ configurationDigest: digest,
680
+ signalSemantics: googleSignalSemantics,
681
+ source,
682
+ measurementRevision: revision,
683
+ countingUnit: objectiveCountingUnit,
684
+ attributionWindowDays: integer2(1, 365),
685
+ declaration: googleDeclared
686
+ };
687
+ var googleExistingChoiceFields = { mode: literal2("existing"), nativeGoal: googleGoalDraft };
688
+ var googleSetupChoiceFields = { mode: literal2("admitted_setup"), setupSpec: googleSetupSpec, setupDigest: digest };
689
+ function checkGoogleConfiguration(value, at) {
690
+ if (value.source.projectId !== value.projectId || value.source.site !== value.site) fail3(at + ".source", "source scope mismatch");
691
+ unique(value.declaration.locationIds, at + ".declaration.locationIds");
692
+ unique(value.declaration.excludedLocationIds, at + ".declaration.excludedLocationIds");
693
+ value.declaration.locationIds.sort();
694
+ value.declaration.excludedLocationIds.sort();
695
+ const expected = googleUploadClicksSetupSemantics({ source: value.source, countingUnit: value.countingUnit, attributionWindowDays: value.attributionWindowDays });
696
+ if (value.mode === "existing") {
697
+ normalizeGoogleGoal(value.nativeGoal, at + ".nativeGoal");
698
+ return;
699
+ }
700
+ 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");
701
+ }
702
+ var googleSnapshotBase = union2(object2({ ...googleConfigurationFields, ...googleExistingChoiceFields }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields }));
703
+ var googleConfigurationSnapshot = refine3(googleSnapshotBase, checkGoogleConfiguration);
704
+ var googleConfigurationReview = refine3(union2(object2({ ...googleConfigurationFields, mode: literal2("existing"), nativeGoal: googleGoalReviewed }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields })), checkGoogleConfiguration);
705
+ var { configurationRevision: _configurationRevisionField, ...googleViewContentFields } = googleConfigurationFields;
706
+ var googleReadinessFields = { ready: bool, activationReadiness: choice2("blocked", "pending_setup", "requires_final_verification", "verified"), reasonCodes: list2(text3(200), 100) };
707
+ var googleViewFields = { ...googleViewContentFields, revision: integer2(1), ...googleReadinessFields };
708
+ var googleViewBase = union2(object2({ ...googleViewFields, ...googleExistingChoiceFields }), object2({ ...googleViewFields, ...googleSetupChoiceFields }));
709
+ function checkGoogleView(value, at) {
710
+ checkGoogleConfiguration(value, at);
711
+ if (!value.ready && value.activationReadiness !== "blocked") fail3(at + ".activationReadiness", "unready configuration must be blocked");
712
+ if (value.mode === "existing") {
713
+ if (value.ready && (value.nativeGoal.name === null || value.nativeGoal.revision === null)) fail3(at + ".ready", "unavailable native evidence cannot be ready");
714
+ if (value.ready && value.activationReadiness !== "requires_final_verification" && value.activationReadiness !== "verified") fail3(at + ".activationReadiness", "existing native setup needs current verification");
715
+ } else if (value.ready && value.activationReadiness !== "pending_setup") fail3(at + ".activationReadiness", "reviewed setup intent is not native activation");
716
+ }
717
+ var googleConfigurationView = refine3(googleViewBase, checkGoogleView);
718
+ var googleSaveResultFields = { operationId: uuid, replayed: bool, campaignRevision: integer2(1) };
719
+ var googleConfigurationSaveResponse = refine3(union2(object2({ ...googleViewFields, ...googleExistingChoiceFields, ...googleSaveResultFields }), object2({ ...googleViewFields, ...googleSetupChoiceFields, ...googleSaveResultFields })), checkGoogleView);
720
+ refine3(union2(object2({ ...googleConfigurationFields, ...googleExistingChoiceFields, configurationDigest: optional2(digest) }), object2({ ...googleConfigurationFields, ...googleSetupChoiceFields, configurationDigest: optional2(digest) })), checkGoogleConfiguration);
721
+ googleSetupSpec.schema;
722
+ googleSave.schema;
723
+ googleConfigurationSnapshot.schema;
724
+ googleConfigurationReview.schema;
725
+ googleConfigurationView.schema;
726
+ googleConfigurationSaveResponse.schema;
727
+ var preparedManifestRef = object2({ id: uuid, digest, providerVersion: text3(30), revision });
728
+ 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) });
729
+ 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) });
730
+ var commandBase = { schemaVersion: literal2(1), campaignId: uuid, expectedRevision: integer2(1), idempotencyKey: operationKey, channelIds: list2(uuid, 100) };
731
+ var effect = object2({ ...commandBase, operation: choice2("launch", "update", "resume"), preparedPlanId: uuid, reviewDigest: digest, mandateRef, expectedRemoteSnapshots: list2(object2({ channelId: uuid, digest }), 100) });
732
+ var googleContentEffect = refine3(object2({
733
+ ...commandBase,
734
+ operation: literal2("update"),
735
+ preparedPlanId: uuid,
736
+ reviewDigest: digest,
737
+ mandateRef,
738
+ channelIds: list2(uuid, 1, 1),
739
+ expectedRemoteSnapshots: list2(object2({ channelId: uuid, digest }), 1, 1),
740
+ googleContentUpdate
741
+ }), (command2, p) => {
742
+ const update2 = command2.googleContentUpdate, remote = command2.expectedRemoteSnapshots[0];
743
+ if (command2.channelIds[0] !== update2.channelId || remote.channelId !== update2.channelId || remote.digest !== update2.beforeDigest) {
744
+ fail3(p + ".googleContentUpdate", "requires the same single channel and before snapshot");
745
+ }
746
+ });
747
+ 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) });
748
+ var safety = object2({ ...commandBase, operation: choice2("pause", "finish", "reconcile") });
749
+ var deliverConversion = object2({ ...commandBase, operation: literal2("deliver_conversion"), channelIds: list2(uuid, 1, 1), preparedPlanId: uuid, reviewDigest: digest, mandateRef, conversionId: uuid });
750
+ var deliverWebsiteVisit = object2({ ...commandBase, operation: literal2("deliver_website_visit"), channelIds: list2(uuid, 1, 1), preparedPlanId: uuid, reviewDigest: digest, mandateRef, occurrenceId: uuid });
751
+ var command = union2(effect, googleContentEffect, optimize, safety, deliverConversion, deliverWebsiteVisit);
752
+ command.schema;
753
+ 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) });
754
+ 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) });
755
+ var lifecycle = choice2("not_materialized", "pending", "partially_live", "live", "pausing", "paused", "finished", "needs_attention", "unknown");
756
+ 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) });
757
+ 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) => {
758
+ if (v === "0") fail3(p, "zero denominator");
759
+ }) }));
760
+ 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) })) };
761
+ var metric = union2(object2({ ...metricBase, state: literal2("observed"), value: metricValue }), object2({ ...metricBase, state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text3(80) }));
762
+ var purpose = choice2("analytics_storage", "ad_storage", "ad_user_data", "ad_personalization");
763
+ 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 });
764
+ var exposure = object2({ ...scope, experimentId: uuid, experimentRevision: integer2(1), assignmentId: uuid, variantKey: text3(80), exposureId: uuid, occurredAt: instant });
765
+ 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) });
766
+ conversion.schema;
767
+ prepared.schema;
768
+ capability.schema;
769
+ mandateScope.schema;
770
+ mandateRef.schema;
771
+ receipt.schema;
772
+ view.schema;
773
+ metric.schema;
774
+ consent.schema;
775
+ var mandateTarget = object2({ project_id: uuid, campaign_id: uuid });
776
+ var mandateApproval = object2({ schemaVersion: literal2(1), expectedRevision: integer2(1), preparedPlanId: uuid, reviewDigest: digest, mandateDigest: digest, mandate: mandateScope, operatingPolicyBase: optional2(operatingPolicyBase) });
777
+ mandateApproval.schema;
778
+ mandateTarget.schema;
779
+ function canonical(value) {
780
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
781
+ if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]";
782
+ return "{" + Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + canonical(value[k])).join(",") + "}";
783
+ }
784
+ var positioningTarget = union2(
785
+ object2({ kind: literal2("broadcast"), channelId: uuid }),
786
+ object2({ kind: literal2("meta"), channelId: uuid, creativeId: uuid }),
787
+ object2({ kind: literal2("google_search"), channelId: uuid, adGroupKey: text3(80), adKey: text3(80) })
788
+ );
789
+ var positioningRequest = object2({
790
+ schemaVersion: literal2(1),
791
+ expectedRevision: integer2(1),
792
+ site,
793
+ destination: optional2(object2({ kind: choice2("existing_page", "funnel"), id: uuid })),
794
+ offerId: optional2(uuid),
795
+ target: positioningTarget
796
+ });
797
+ var positioningWitnessFields = {
798
+ id: operationKey,
799
+ kind: choice2("page", "funnel", "offer", "brain", "buyer", "proof"),
800
+ sourceId: text3(160),
801
+ revision,
802
+ observedAt: instant,
803
+ expiresAt: instant,
804
+ permission: choice2("private", "public"),
805
+ certainty: choice2("verified", "reported", "conflicting")
806
+ };
807
+ var positioningWitness = refine3(object2(positioningWitnessFields), checkPositioningWitness);
808
+ var positioningText = (max) => refine3(text3(max), (value, at) => {
809
+ if (!value.trim() || /[\x00-\x08\x0b-\x1f\x7f]/.test(value)) fail3(at, "requires nonblank text without control characters");
810
+ });
811
+ var positioningEvidence = refine3(object2({ ...positioningWitnessFields, text: positioningText(1600) }), checkPositioningWitness);
812
+ function checkPositioningWitness(value, at) {
813
+ if (Date.parse(value.observedAt) >= Date.parse(value.expiresAt)) fail3(at, "requires a positive witness lifetime");
814
+ }
815
+ var positioningScopeFields = { schemaVersion: literal2(1), projectId: uuid, campaignId: uuid, request: positioningRequest, observedAt: instant, expiresAt: instant };
816
+ function checkPositioningWindow(value, at) {
817
+ if (Date.parse(value.observedAt) >= Date.parse(value.expiresAt)) fail3(at, "requires a positive review lifetime");
818
+ unique(value.evidence.map((item) => item.id), at + ".evidence");
819
+ if (value.evidence.some((item) => Date.parse(item.observedAt) > Date.parse(value.observedAt))) fail3(at + ".evidence", "witness observation postdates the preview");
820
+ }
821
+ var positioningContext = refine3(object2({
822
+ ...positioningScopeFields,
823
+ orgId: uuid,
824
+ evidence: list2(positioningEvidence, 32)
825
+ }), (value, at) => {
826
+ checkPositioningWindow(value, at);
827
+ if (value.evidence.reduce((total, witness) => total + witness.text.length, 0) > 16e3) {
828
+ fail3(at + ".evidence", "exceeds the combined source text budget");
829
+ }
830
+ });
831
+ var positioningEvidenceIds = uniqueList(operationKey, 8);
832
+ var positioningSupportedText = object2({ text: positioningText(320), evidenceIds: positioningEvidenceIds });
833
+ var positioningAlternative = refine3(object2({
834
+ text: positioningText(320),
835
+ kind: choice2("status_quo", "alternative"),
836
+ basis: choice2("evidence", "hypothesis"),
837
+ evidenceIds: positioningEvidenceIds
838
+ }), (value, at) => {
839
+ if (value.basis === "evidence" !== value.evidenceIds.length > 0) fail3(at, "requires evidence references exactly for evidenced alternatives");
840
+ });
841
+ var positioningClaim = object2({
842
+ attribute: positioningText(320),
843
+ value: positioningText(320),
844
+ evidenceIds: uniqueList(operationKey, 8, 1),
845
+ publicProofIds: positioningEvidenceIds
846
+ });
847
+ var positioningClaimIndexes = list2(integer2(0, 7), 8, 1);
848
+ var positioningCopy = union2(
849
+ object2({ kind: literal2("broadcast"), caption: positioningText(2200), claimIndexes: positioningClaimIndexes }),
850
+ object2({
851
+ kind: literal2("meta"),
852
+ primaryText: positioningText(2200),
853
+ headline: positioningText(160),
854
+ body: positioningText(1e4),
855
+ claimIndexes: positioningClaimIndexes
856
+ }),
857
+ object2({
858
+ kind: literal2("google_search"),
859
+ headlines: uniqueList(positioningText(30), 15, 3),
860
+ descriptions: uniqueList(positioningText(90), 4, 2),
861
+ claimIndexes: positioningClaimIndexes
862
+ })
863
+ );
864
+ var positioningReasonCodes = choice2(
865
+ "destination_missing",
866
+ "destination_unverified",
867
+ "offer_unverified",
868
+ "offer_conflicting",
869
+ "brain_unavailable",
870
+ "buyer_evidence_sparse",
871
+ "public_proof_unavailable",
872
+ "fit_not_established",
873
+ "status_quo_sufficient",
874
+ "channel_mismatch",
875
+ "source_stale",
876
+ "evidence_conflicting",
877
+ "generation_unavailable"
878
+ );
879
+ var RESONANCE_POSITIONING_METHOD_VERSION = "positioning_v1";
880
+ var positioningResult = refine3(object2({
881
+ methodVersion: literal2(RESONANCE_POSITIONING_METHOD_VERSION),
882
+ state: choice2("ready", "provisional", "no_fit"),
883
+ reasonCodes: uniqueList(positioningReasonCodes, 12),
884
+ alternatives: list2(positioningAlternative, 8),
885
+ claims: list2(positioningClaim, 8),
886
+ bestFit: list2(positioningSupportedText, 8),
887
+ category: nullable2(object2({ text: positioningText(160), style: choice2("existing_category", "focused_subcategory", "new_category"), evidenceIds: positioningEvidenceIds })),
888
+ timelyContext: nullable2(positioningSupportedText),
889
+ unknowns: list2(positioningText(320), 8),
890
+ questions: list2(positioningText(320), 8),
891
+ copy: nullable2(positioningCopy)
892
+ }), (value, at) => {
893
+ if (value.state !== "ready") {
894
+ if (value.copy || !value.reasonCodes.length) fail3(at, "requires a reason and no draft copy when held");
895
+ return;
896
+ }
897
+ const { copy, claims, category, bestFit, alternatives } = value;
898
+ if (!copy || value.reasonCodes.length || !claims.length || !category || !bestFit.length || !alternatives.length) {
899
+ return fail3(at, "requires a supported ready brief and channel draft");
900
+ }
901
+ unique(copy.claimIndexes.map(String), at + ".copy.claimIndexes");
902
+ if (copy.claimIndexes.some((index) => index >= claims.length)) fail3(at + ".copy.claimIndexes", "requires an existing claim index");
903
+ });
904
+ function checkPositioningEvidence(result, context, at) {
905
+ const evidence = new Map(context.evidence.map((witness) => [witness.id, witness]));
906
+ const current = (witness) => witness.certainty === "verified" && Date.parse(witness.expiresAt) >= Date.parse(context.expiresAt);
907
+ const cited = [
908
+ ...result.alternatives,
909
+ ...result.claims,
910
+ ...result.bestFit,
911
+ ...result.category ? [result.category] : [],
912
+ ...result.timelyContext ? [result.timelyContext] : []
913
+ ];
914
+ if (cited.some((item) => item.evidenceIds.some((id) => !evidence.has(id)))) fail3(at, "references unknown evidence");
915
+ for (const claim of result.claims) {
916
+ for (const id of claim.publicProofIds) {
917
+ const witness = evidence.get(id);
918
+ if (!witness || witness.permission !== "public" || !current(witness)) fail3(at, "public proof requires a current permitted witness");
919
+ }
920
+ }
921
+ if (result.timelyContext && (!result.timelyContext.evidenceIds.length || result.timelyContext.evidenceIds.some((id) => {
922
+ const witness = evidence.get(id);
923
+ return !witness || !current(witness);
924
+ }))) fail3(at, "timely context requires current verified evidence");
925
+ if (!result.copy) return;
926
+ if (result.copy.kind !== context.request.target.kind) fail3(at, "copy target differs from the request");
927
+ const { destination: selected, offerId } = context.request;
928
+ const owns = (kind, id) => {
929
+ const witnesses = context.evidence.filter((w) => w.kind === kind && (!id || w.sourceId.toLowerCase() === id.toLowerCase()));
930
+ return witnesses.some(current) && !witnesses.some((w) => w.certainty === "conflicting");
931
+ };
932
+ if (!selected || !owns(selected.kind === "existing_page" ? "page" : "funnel", selected.id) || !owns("brain") || offerId && !owns("offer", offerId)) {
933
+ fail3(at, "ready copy requires current destination, Brain and selected offer witnesses");
934
+ }
935
+ for (const index of result.copy.claimIndexes) {
936
+ const claim = result.claims[index];
937
+ if (![...claim.evidenceIds, ...claim.publicProofIds].every((id) => {
938
+ const witness = evidence.get(id);
939
+ return witness && witness.permission === "public" && current(witness);
940
+ })) fail3(at, "selected copy requires current verified public claim evidence");
941
+ }
942
+ }
943
+ var positioningApplicationToken = text3(32e3, /^[a-zA-Z0-9._-]+$/);
944
+ var positioningPreview = refine3(object2({
945
+ ...positioningScopeFields,
946
+ evidence: list2(positioningWitness, 32),
947
+ result: positioningResult,
948
+ applicationToken: nullable2(positioningApplicationToken)
949
+ }), (value, at) => {
950
+ checkPositioningWindow(value, at);
951
+ checkPositioningEvidence(value.result, value, at + ".result");
952
+ if (value.result.state === "ready" !== (value.applicationToken !== null)) fail3(at, "requires an application token exactly for ready copy");
953
+ });
954
+ var positioningApplyRequest = object2({ applicationToken: positioningApplicationToken });
955
+ positioningRequest.schema;
956
+ positioningContext.schema;
957
+ positioningResult.schema;
958
+ positioningPreview.schema;
959
+ positioningApplyRequest.schema;
960
+ var positioningConsistencyAssessment = object2({
961
+ state: choice2("compatible", "conflicting", "unknown"),
962
+ evidenceDigest: digest,
963
+ coveredSourceIds: uniqueList(operationKey, 32)
964
+ });
965
+ positioningConsistencyAssessment.schema;
966
+ var prepareCommand = object2({ expectedRevision: integer2(1), idempotencyKey: operationKey, googleContentUpdate: optional2(googleContentUpdateSelection) });
967
+ var commandPreparation = object2({ command: nullable2(command), covered: bool, approvalRequirement: nullable2(choice2("existing_mandate", "current_owner")), reasonCodes: list2(text3(200), 100) });
968
+ prepareCommand.schema;
969
+ var preparationLookupRequest = object2({ expectedRevision: integer2(1), idempotencyKey: operationKey });
970
+ var preparationLookupOperation = object2({
971
+ operationId: uuid,
972
+ preparedPlanId: uuid,
973
+ executionState: choice2("reserved", "claimed", "dispatched", "succeeded", "rejected", "uncertain", "cancelled"),
974
+ createdAt: instant,
975
+ hasAdDispatch: bool,
976
+ artifactCount: integer2(0, 512),
977
+ completedArtifactCount: integer2(0, 512),
978
+ originalActorMatches: bool,
979
+ originalPrincipalMatches: bool
980
+ });
981
+ var preparationLookupResponse = object2({
982
+ schemaVersion: literal2(1),
983
+ projectId: uuid,
984
+ campaignId: uuid,
985
+ request: preparationLookupRequest,
986
+ state: choice2("not_found", "working", "recovery_required", "succeeded", "rejected", "cancelled"),
987
+ currentRevision: integer2(1),
988
+ operation: nullable2(preparationLookupOperation),
989
+ preparedPlan: nullable2(prepared),
990
+ readiness: object2({ reasonCodes: list2(choice2(
991
+ "PREPARATION_NOT_FOUND",
992
+ "PREPARATION_WORKING",
993
+ "PREPARATION_RECOVERY_REQUIRED",
994
+ "PREPARATION_REJECTED",
995
+ "PREPARATION_CANCELLED",
996
+ "PREPARATION_OWNER_MISMATCH",
997
+ "PREPARATION_REVISION_CHANGED",
998
+ "PREPARATION_HAS_AD_DISPATCH",
999
+ "PREPARATION_INVENTORY_UNAVAILABLE",
1000
+ "PREPARATION_TERMINAL_PROVIDER_REJECTION",
1001
+ "PREPARATION_ACCEPTED_REVIEW_AVAILABLE",
1002
+ "PREPARATION_FINANCIAL_EXPOSURE",
1003
+ "OWNER_STEP_FAILED",
1004
+ "OWNER_SOURCE_CHANGED",
1005
+ "SIGNER_CHANGED"
1006
+ ), 30), canResume: bool })
1007
+ });
1008
+ preparationLookupRequest.schema;
1009
+ preparationLookupResponse.schema;
1010
+ var preparationRetireRequest = object2({ expectedRevision: integer2(1), reason: literal2("retain_unpublished_artifacts") });
1011
+ var preparationRetireResponse = refine3(object2({
1012
+ schemaVersion: literal2(1),
1013
+ projectId: uuid,
1014
+ campaignId: uuid,
1015
+ preparationOperationId: uuid,
1016
+ state: literal2("cancelled"),
1017
+ replayed: bool,
1018
+ retainedArtifactCount: integer2(0, 512),
1019
+ unrecordedSlotCount: integer2(0, 512),
1020
+ retiredAt: instant,
1021
+ reasonCodes: list2(text3(100), 0)
1022
+ }), (v, p) => {
1023
+ if (v.retainedArtifactCount + v.unrecordedSlotCount > 512) fail3(p, "artifact and unrecorded slot total exceeds bound");
1024
+ });
1025
+ preparationRetireRequest.schema;
1026
+ preparationRetireResponse.schema;
1027
+ var diagnosticsCode = text3(100, /^[A-Za-z][A-Za-z0-9_]*$/);
1028
+ var diagnosticsReasons = list2(diagnosticsCode, 64);
1029
+ var diagnosticsId = text3(30, /^[1-9][0-9]*$/);
1030
+ var diagnosticsResource = text3(200, /^customers\/[0-9]+\/(?:conversionActions|customConversionGoals)\/[0-9]+$/);
1031
+ var diagnosticsDay = refine3(text3(10, /^\d{4}-\d{2}-\d{2}$/), (v, p) => {
1032
+ if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().slice(0, 10) !== v || v.startsWith("0000")) fail3(p, "invalid calendar date");
1033
+ });
1034
+ var RESONANCE_GOOGLE_DIAGNOSTICS_SECTIONS = ["campaign", "totals", "daily", "keywords", "searchTerms", "goals", "uploadDiagnostics"];
1035
+ var googleDiagnosticsRequestFields = {
1036
+ channelId: uuid,
1037
+ startDate: diagnosticsDay,
1038
+ endDate: diagnosticsDay,
1039
+ sections: list2(choice2(...RESONANCE_GOOGLE_DIAGNOSTICS_SECTIONS), 7, 1),
1040
+ directive: text3(2e3)
1041
+ };
1042
+ var checkDiagnosticsRequest = (v, p) => {
1043
+ unique(v.sections, p + ".sections");
1044
+ const days = (Date.parse(v.endDate) - Date.parse(v.startDate)) / 864e5 + 1;
1045
+ if (days < 1 || days > 31) fail3(p, "requires one to 31 calendar days");
1046
+ if (!v.directive.trim()) fail3(p + ".directive", "requires an explicit command");
1047
+ };
1048
+ var googleDiagnosticsRequest = refine3(object2(googleDiagnosticsRequestFields), checkDiagnosticsRequest);
1049
+ googleDiagnosticsRequest.schema;
1050
+ var googleDiagnosticsPayload = refine3(object2({
1051
+ schemaVersion: literal2(1),
1052
+ campaignId: uuid,
1053
+ expectedRevision: integer2(1),
1054
+ ...googleDiagnosticsRequestFields,
1055
+ accountBindingId: uuid,
1056
+ site,
1057
+ idempotencyKey: operationKey
1058
+ }), checkDiagnosticsRequest);
1059
+ googleDiagnosticsPayload.schema;
1060
+ var diagnosticsMetricsFields = {
1061
+ spendMicros: nullable2(decimal),
1062
+ impressions: nullable2(decimal),
1063
+ clicks: nullable2(decimal),
1064
+ conversions: nullable2(text3(61, /^(?:0|[1-9][0-9]{0,29})(?:\.[0-9]{0,29}[1-9])?$/)),
1065
+ allConversions: nullable2(text3(61, /^(?:0|[1-9][0-9]{0,29})(?:\.[0-9]{0,29}[1-9])?$/))
1066
+ };
1067
+ var diagnosticsMetrics = object2(diagnosticsMetricsFields);
1068
+ var diagnosticsCampaignRow = object2({
1069
+ status: diagnosticsCode,
1070
+ primaryStatus: nullable2(diagnosticsCode),
1071
+ primaryStatusReasons: diagnosticsReasons,
1072
+ servingStatus: nullable2(diagnosticsCode),
1073
+ biddingStrategyType: nullable2(diagnosticsCode),
1074
+ startDate: nullable2(diagnosticsDay),
1075
+ endDate: nullable2(diagnosticsDay),
1076
+ budgetAmountMicros: nullable2(decimal),
1077
+ budgetPeriod: nullable2(diagnosticsCode),
1078
+ searchNetwork: nullable2(bool),
1079
+ searchPartners: nullable2(bool),
1080
+ displayNetwork: nullable2(bool),
1081
+ positiveGeoTargetType: nullable2(diagnosticsCode),
1082
+ negativeGeoTargetType: nullable2(diagnosticsCode),
1083
+ locationCriterionIds: list2(diagnosticsId, 100)
1084
+ });
1085
+ var diagnosticsKeywordRow = object2({
1086
+ criterionId: diagnosticsId,
1087
+ adGroupId: diagnosticsId,
1088
+ matchType: nullable2(diagnosticsCode),
1089
+ status: nullable2(diagnosticsCode),
1090
+ negative: bool,
1091
+ ...diagnosticsMetricsFields
1092
+ });
1093
+ var diagnosticsTermRow = object2({
1094
+ rowId: digest,
1095
+ adGroupId: diagnosticsId,
1096
+ status: nullable2(diagnosticsCode),
1097
+ keywordCriterionId: nullable2(diagnosticsId),
1098
+ matchType: nullable2(diagnosticsCode),
1099
+ ...diagnosticsMetricsFields
1100
+ });
1101
+ var diagnosticsGoalRow = object2({
1102
+ goalConfigLevel: nullable2(diagnosticsCode),
1103
+ customGoalResourceName: nullable2(diagnosticsResource),
1104
+ customGoalStatus: nullable2(diagnosticsCode),
1105
+ actionResourceName: diagnosticsResource,
1106
+ actionStatus: nullable2(diagnosticsCode),
1107
+ type: nullable2(diagnosticsCode),
1108
+ category: nullable2(diagnosticsCode),
1109
+ primaryForGoal: nullable2(bool),
1110
+ countingType: nullable2(diagnosticsCode),
1111
+ clickThroughLookbackWindowDays: nullable2(integer2(1, 365))
1112
+ });
1113
+ var diagnosticsUploadRow = object2({
1114
+ actionResourceName: diagnosticsResource,
1115
+ client: nullable2(diagnosticsCode),
1116
+ status: nullable2(diagnosticsCode),
1117
+ 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})?$/)),
1118
+ totalEventCount: nullable2(decimal),
1119
+ successfulEventCount: nullable2(decimal),
1120
+ pendingEventCount: nullable2(decimal),
1121
+ alertCodes: diagnosticsReasons
1122
+ });
1123
+ function diagnosticsSection(row, max) {
1124
+ return refine3(object2({
1125
+ state: choice2("available", "unavailable", "capped"),
1126
+ reasonCodes: diagnosticsReasons,
1127
+ rows: list2(row, max),
1128
+ pagesRead: integer2(0, 100)
1129
+ }), (v, p) => {
1130
+ if (v.state === "unavailable" && v.rows.length) fail3(p, "unavailable sections cannot assert observed rows");
1131
+ if (v.state !== "available" && !v.reasonCodes.length) fail3(p, "incomplete sections require a reason");
1132
+ });
1133
+ }
1134
+ var googleDiagnosticsReport = object2({
1135
+ schemaVersion: literal2(1),
1136
+ provider: literal2("google_ads"),
1137
+ projectId: uuid,
1138
+ campaignId: uuid,
1139
+ channelId: uuid,
1140
+ site,
1141
+ accountBindingId: uuid,
1142
+ externalCampaignId: diagnosticsId,
1143
+ currency,
1144
+ accountTimeZone: timeZone,
1145
+ window: object2({ startDate: diagnosticsDay, endDate: diagnosticsDay, completeness: literal2("completed_days") }),
1146
+ observedAt: instant,
1147
+ sections: object2({
1148
+ campaign: diagnosticsSection(diagnosticsCampaignRow, 1),
1149
+ totals: diagnosticsSection(diagnosticsMetrics, 1),
1150
+ daily: diagnosticsSection(object2({ localDate: diagnosticsDay, ...diagnosticsMetricsFields }), 31),
1151
+ keywords: diagnosticsSection(diagnosticsKeywordRow, 500),
1152
+ searchTerms: diagnosticsSection(diagnosticsTermRow, 1e3),
1153
+ goals: diagnosticsSection(diagnosticsGoalRow, 100),
1154
+ uploadDiagnostics: diagnosticsSection(diagnosticsUploadRow, 300)
1155
+ }),
1156
+ searchTermCoverage: object2({
1157
+ state: choice2("available", "unavailable"),
1158
+ reasonCodes: diagnosticsReasons,
1159
+ disclosed: nullable2(diagnosticsMetrics),
1160
+ remainder: nullable2(diagnosticsMetrics)
1161
+ }),
1162
+ providerAuthored: object2({
1163
+ campaignName: nullable2(text3(300)),
1164
+ keywords: list2(object2({ adGroupId: diagnosticsId, criterionId: diagnosticsId, text: text3(500) }), 500),
1165
+ searchTerms: list2(object2({ rowId: digest, text: text3(500) }), 1e3),
1166
+ locations: list2(object2({ criterionId: diagnosticsId, name: text3(300) }), 100)
1167
+ })
1168
+ });
1169
+ googleDiagnosticsReport.schema;
1170
+ commandPreparation.schema;
1171
+ var saveCommand = object2({ definition: draft, expectedRevision: optional2(integer2(0)), idempotencyKey: operationKey });
1172
+ var acceptCommand = object2({ expectedRevision: integer2(1), ledgerActionId: uuid });
1173
+ var bindingCommand = object2({ connectionId: uuid, provider: choice2("google_ads", "meta_ads"), externalAccountId: text3(160), expectedConnectionRevision: revision, idempotencyKey: operationKey });
1174
+ saveCommand.schema;
1175
+ acceptCommand.schema;
1176
+ bindingCommand.schema;
1177
+ var RESONANCE_CPQL_UNCERTAINTY_METHOD = "observational_cpql_missing_outcome_bound_v1";
1178
+ var allocationHorizon = union2(
1179
+ refine3(object2({ kind: literal2("finite_period"), startAt: instant, endAt: instant, timeZone, sourceRef: revision }), (r, p) => {
1180
+ if (Date.parse(r.endAt) <= Date.parse(r.startAt)) fail3(p, "invalid finite horizon");
1181
+ }),
1182
+ object2({ kind: literal2("daily_average"), timeZone, sourceRef: revision })
1183
+ );
1184
+ var uncertaintySource = object2({ method: literal2(RESONANCE_CPQL_UNCERTAINTY_METHOD), eligibleContacts: decimal, fullyResolvedContacts: decimal, qualifiedContacts: decimal, verifiedSpend: money, sourceRevision: revision, qualificationRuleRef: resource, universeComplete: literal2(true), spendPeriodComplete: literal2(true) });
1185
+ var allocationEvidenceFields = {
1186
+ id: uuid,
1187
+ revision,
1188
+ evidenceDigest: digest,
1189
+ projectId: uuid,
1190
+ campaignId: uuid,
1191
+ preparedPlanId: uuid,
1192
+ reviewDigest: digest,
1193
+ observedAt: instant,
1194
+ windowStart: instant,
1195
+ windowEnd: instant,
1196
+ dataThrough: nullable2(instant),
1197
+ lastAdjustmentAt: nullable2(instant),
1198
+ currentKillRevision: integer2(0),
1199
+ goalRevision: revision,
1200
+ objective,
1201
+ policyDigest: digest,
1202
+ resolvedPolicy: matureOptimizationPolicy,
1203
+ trackingState: choice2("healthy", "blocked", "unknown"),
1204
+ coverageBasisPoints: nullable2(integer2(0, 1e4)),
1205
+ assignmentCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1206
+ powerCheck: choice2("pass", "failed", "unknown", "not_applicable")
1207
+ };
1208
+ 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) => {
1209
+ if (![0, 2, 3, 6].includes(v)) fail3(p, "unsupported provider exponent");
1210
+ }), providerMaxUnits: decimal };
1211
+ var { uncertaintySource: _legacyUncertaintyField, ...reportedChannelFields } = allocationChannelFields;
1212
+ var matureOptimizationEvidence = object2({ ...allocationEvidenceFields, resolvedPolicy: matureOptimizationPolicy, channels: list2(object2({ ...allocationChannelFields, uncertaintySource: nullable2(uncertaintySource) }), 100, 1) });
1213
+ 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) };
1214
+ var reportedOutcomeSource = object2({ method: literal2(RESONANCE_CPQL_UNCERTAINTY_METHOD), eligibleContacts: decimal, fullyResolvedContacts: decimal, qualifiedContacts: decimal, sourceRevision: revision, qualificationRuleRef: resource, universeComplete: literal2(true) });
1215
+ 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) => {
1216
+ const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(v);
1217
+ const projected = match[1] + "." + (match[2] ?? "").padEnd(3, "0").slice(0, 3) + "Z";
1218
+ if (!Number.isFinite(Date.parse(projected)) || new Date(projected).toISOString() !== projected) fail3(p, "invalid native SQL UTC instant");
1219
+ });
1220
+ var providerReadClock = object2({ kind: literal2("sql_before_provider_read_lower_bound_v1"), notBeforeAt: nativeSqlReadInstant });
1221
+ var channelReportedCost = object2({ ...reportedCostFields, readClock: providerReadClock });
1222
+ var reportedOptimizationEvidence = object2({
1223
+ ...allocationEvidenceFields,
1224
+ evidenceKind: literal2("reported_cpql_sql_clock_v1"),
1225
+ resolvedPolicy: reportedOptimizationPolicy,
1226
+ channels: list2(object2({ ...reportedChannelFields, channelReportedCost, outcomeSource: reportedOutcomeSource }), 100, 1)
1227
+ });
1228
+ var optimizationEvidenceRefFields = { id: uuid, revision, evidenceDigest: digest };
1229
+ var optimizationEvidenceRef = object2(optimizationEvidenceRefFields);
1230
+ var finiteOwnMeasurement = union2(
1231
+ object2({ state: literal2("unobserved"), observations: literal2(null), reasonCodes: list2(text3(80), 50) }),
1232
+ object2({ state: choice2("pending", "blocked"), observations: nullable2(list2(metric, 100)), reasonCodes: list2(text3(80), 50) }),
1233
+ object2({ state: literal2("mature"), observations: list2(metric, 100, 1), reasonCodes: list2(text3(80), 50) })
1234
+ );
1235
+ var finiteCandidateObservation = object2({
1236
+ channelId: uuid,
1237
+ site,
1238
+ accountBindingId: uuid,
1239
+ graphDigest: digest,
1240
+ manifestRef: preparedManifestRef,
1241
+ cap: positiveMoneyShape,
1242
+ flight: object2({ startAt: instant, endAt: instant, timeZone }),
1243
+ lifecycle: choice2("not_materialized", "paused", "active", "stopped", "unknown"),
1244
+ nativeStateEvidenceRef: nullable2(optimizationEvidenceRef),
1245
+ commitmentEvidenceRef: nullable2(object2({ ...optimizationEvidenceRefFields, commitmentOperationId: uuid })),
1246
+ activationsObserved: integer2(0, 1),
1247
+ trackingState: choice2("healthy", "blocked", "unknown"),
1248
+ coverageBasisPoints: nullable2(integer2(0, 1e4)),
1249
+ dedupeCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1250
+ qualificationCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1251
+ reasonCodes: list2(text3(80), 50),
1252
+ ownMeasurement: finiteOwnMeasurement
1253
+ });
1254
+ var finiteOptimizationEvidence = object2({
1255
+ id: uuid,
1256
+ revision,
1257
+ evidenceDigest: digest,
1258
+ projectId: uuid,
1259
+ campaignId: uuid,
1260
+ preparedPlanId: uuid,
1261
+ reviewDigest: digest,
1262
+ observedAt: instant,
1263
+ windowStart: instant,
1264
+ windowEnd: instant,
1265
+ dataThrough: nullable2(instant),
1266
+ lastAdjustmentAt: nullable2(instant),
1267
+ currentKillRevision: integer2(0),
1268
+ goalRevision: revision,
1269
+ objective,
1270
+ policyDigest: digest,
1271
+ resolvedPolicy: finiteMetaCandidatePolicy,
1272
+ trackingState: choice2("healthy", "blocked", "unknown"),
1273
+ coverageBasisPoints: nullable2(integer2(0, 1e4)),
1274
+ assignmentCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1275
+ powerCheck: choice2("pass", "failed", "unknown", "not_applicable"),
1276
+ evidenceKind: literal2("finite_candidate_lifecycle_v1"),
1277
+ inventoryState: choice2("complete", "incomplete", "unknown"),
1278
+ candidates: list2(finiteCandidateObservation, 100, 1)
1279
+ });
1280
+ var optimizationEvidence = union2(matureOptimizationEvidence, finiteOptimizationEvidence, reportedOptimizationEvidence);
1281
+ var matureOptimizationDecision = object2({
1282
+ id: uuid,
1283
+ revision,
1284
+ projectId: uuid,
1285
+ campaignId: uuid,
1286
+ preparedPlanId: uuid,
1287
+ reviewDigest: digest,
1288
+ evidenceRef: optimizationEvidenceRef,
1289
+ policyDigest: digest,
1290
+ requestDigest: digest,
1291
+ expiresAt: instant,
1292
+ algorithmRevision: revision,
1293
+ sourceRefs: list2(revision, 200),
1294
+ state: choice2("actionable", "noop", "blocked"),
1295
+ decisionKind: choice2("observational_allocation", "experimental_promotion"),
1296
+ executionOrder: literal2("reduce_then_increase"),
1297
+ reasonCodes: list2(text3(80), 50),
1298
+ adjustments: list2(object2({ channelId: uuid, site, budgetMode: choice2("campaign_total", "average_daily", "lifetime", "daily"), providerUnitExponent: refine3(integer2(0, 6), (v, p) => {
1299
+ if (![0, 2, 3, 6].includes(v)) fail3(p, "unsupported provider exponent");
1300
+ }), providerMaxUnits: decimal, before: money, after: money, remoteSnapshotDigest: digest }), 100),
1301
+ createdAt: instant
1302
+ });
1303
+ var finiteCandidateActionFields = { channelId: uuid, graphDigest: digest, nativeStateEvidenceRef: optimizationEvidenceRef };
1304
+ var finiteCandidateActionBody = union2(
1305
+ object2({ action: literal2("materialize_and_activate"), ...finiteCandidateActionFields }),
1306
+ object2({ action: literal2("activate_held"), ...finiteCandidateActionFields, commitmentOperationId: uuid }),
1307
+ object2({ action: literal2("pause_candidate"), ...finiteCandidateActionFields })
1308
+ );
1309
+ var finiteDecisionFields = {
1310
+ id: uuid,
1311
+ revision,
1312
+ projectId: uuid,
1313
+ campaignId: uuid,
1314
+ preparedPlanId: uuid,
1315
+ reviewDigest: digest,
1316
+ evidenceRef: optimizationEvidenceRef,
1317
+ policyDigest: digest,
1318
+ requestDigest: digest,
1319
+ expiresAt: instant,
1320
+ createdAt: instant,
1321
+ algorithmRevision: literal2("finite_meta_candidates_v1"),
1322
+ sourceRefs: list2(revision, 200),
1323
+ decisionKind: literal2("preapproved_candidate_operation"),
1324
+ reasonCodes: list2(text3(80), 50, 1)
1325
+ };
1326
+ var finiteOptimizationDecision = union2(
1327
+ object2({ ...finiteDecisionFields, state: literal2("actionable"), candidateActions: list2(finiteCandidateActionBody, 1, 1) }),
1328
+ object2({ ...finiteDecisionFields, state: choice2("noop", "blocked"), candidateActions: list2(finiteCandidateActionBody, 0) })
1329
+ );
1330
+ var optimizationDecision = union2(matureOptimizationDecision, finiteOptimizationDecision);
1331
+ optimizationEvidence.schema;
1332
+ optimizationDecision.schema;
1333
+ var metaBrowserWitness = object2({ controlsRevision: text3(60, /^[A-Z][A-Z0-9_]*$/), policyRevision: revision, witnessId: uuid, assertedAt: instant });
1334
+ var publicDestination = union2(
1335
+ object2({ provider: literal2("google_ads"), id: uuid, tagId: text3(40, /^AW-[0-9]+$/) }),
1336
+ // browserWitness and tagManagerAttested are optional so configurations from before the Meta loader keep parsing; absent means no Meta browser loading.
1337
+ object2({ provider: literal2("meta_ads"), id: uuid, pixelId: text3(40, /^[0-9]+$/), browserWitness: optional2(metaBrowserWitness), tagManagerAttested: optional2(bool) })
1338
+ );
1339
+ var interestResource = object2({ ...scope, type: choice2("page", "article", "product", "listing"), id: text3(160, /^[a-zA-Z0-9._:-]+$/), revision });
1340
+ var measurementConfig = object2({
1341
+ schemaVersion: literal2(1),
1342
+ ...scope,
1343
+ configRevision: revision,
1344
+ policyRevision: revision,
1345
+ expiresAt: instant,
1346
+ enabled: bool,
1347
+ consentPolicy: object2({ mode: literal2("basic"), requiredPurposes: list2(purpose, 4, 1) }),
1348
+ destinations: list2(publicDestination, 10),
1349
+ // metaEligible is set by a person with owner or admin standing; absent means false. The browser never decides it.
1350
+ resourceRules: list2(object2({ id: uuid, revision, site, resource: interestResource, path, interestKey: text3(100, /^[a-zA-Z0-9._:-]+$/), metaEligible: optional2(bool) }), 500)
1351
+ });
1352
+ function parseResonanceMeasurementConfig(v) {
1353
+ const r = measurementConfig.read(v, "measurementConfig");
1354
+ scoped(r, r.projectId, [r.site], "measurementConfig");
1355
+ unique(r.destinations.map((d) => d.id), "measurementConfig.destinations");
1356
+ unique(r.consentPolicy.requiredPurposes, "measurementConfig.consentPolicy.requiredPurposes");
1357
+ unique(r.resourceRules.map((rule) => rule.id), "measurementConfig.resourceRules");
1358
+ 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");
1359
+ return r;
1360
+ }
1361
+ var clickIdentifierPattern = /^[^\s\u0000-\u001f\u007f-\u009f]+(?![\s\S])/;
1362
+ 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"));
1363
+ var clickIdentifiersShape = union2(object2({ gclid: clickIdentifier }), object2({ gbraid: clickIdentifier }), object2({ wbraid: clickIdentifier }));
1364
+ var clickIdentifiers = field2(clickIdentifiersShape.schema, clickIdentifiersShape.read);
1365
+ clickIdentifiers.schema;
1366
+ var observedPathControl = /[\s\u0000-\u001f\u007f-\u009f]/;
1367
+ var observedPagePath = field2({ ...path.schema, allOf: [{ not: { pattern: observedPathControl.source } }] }, (v, p) => {
1368
+ const result = path.read(v, p);
1369
+ if (observedPathControl.test(result)) fail3(p, "invalid observed path");
1370
+ return result;
1371
+ });
1372
+ var metaCookieShape = object2({ source: literal2(RESONANCE_WEBSITE_VISIT_PROFILE.source), fbp: optional2(clickIdentifier), fbc: optional2(clickIdentifier) });
1373
+ var metaCookieObservation = field2({ ...metaCookieShape.schema, anyOf: [{ required: ["fbp"] }, { required: ["fbc"] }] }, (v, p) => {
1374
+ const result = metaCookieShape.read(v, p);
1375
+ if (!result.fbp && !result.fbc) fail3(p, "requires an actual reported cookie value");
1376
+ return result;
1377
+ });
1378
+ var occurrenceShape = object2({
1379
+ schemaVersion: literal2(1),
1380
+ ...scope,
1381
+ configRevision: revision,
1382
+ eventId: uuid,
1383
+ navigationId: uuid,
1384
+ occurredAt: instant,
1385
+ kind: choice2("page_view", "content_interest", "experiment_exposure"),
1386
+ sourceMarker: optional2(sourceMarker),
1387
+ resourceRef: nullable2(interestResource),
1388
+ campaignPlanId: nullable2(uuid),
1389
+ experiment: nullable2(exposure),
1390
+ clickIdentifiers: optional2(clickIdentifiers),
1391
+ pagePath: optional2(observedPagePath),
1392
+ metaCookieObservation: optional2(metaCookieObservation),
1393
+ consentReceiptRefs: list2(object2({ purpose, receiptId: uuid, consentRevision: integer2(1) }), 4)
1394
+ });
1395
+ var occurrence = field2({ ...occurrenceShape.schema, allOf: [
1396
+ { if: { required: ["clickIdentifiers"] }, then: { properties: { kind: { const: "page_view" } } } },
1397
+ { if: { required: ["pagePath"] }, then: { properties: { kind: { enum: ["page_view", "experiment_exposure"] } } } },
1398
+ { if: { required: ["metaCookieObservation"] }, then: { required: ["pagePath"], properties: { kind: { const: "page_view" }, resourceRef: interestResource.schema } } }
1399
+ ] }, (v, p) => {
1400
+ const r = occurrenceShape.read(v, p);
1401
+ if (r.clickIdentifiers && r.kind !== "page_view") fail3(p + ".clickIdentifiers", "requires page_view");
1402
+ if (r.pagePath !== void 0 && r.kind !== "page_view" && r.kind !== "experiment_exposure") fail3(p + ".pagePath", "requires page_view or experiment_exposure");
1403
+ if (r.metaCookieObservation && (r.kind !== "page_view" || r.pagePath === void 0 || !r.resourceRef)) fail3(p + ".metaCookieObservation", "requires the same page_view path and resource");
1404
+ return r;
1405
+ });
1406
+ 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) });
1407
+ measurementConfig.schema;
1408
+ occurrence.schema;
1409
+ consentUpdate.schema;
1410
+ var consentResult = object2({ subjectProof: text3(200, /^[a-zA-Z0-9_-]{32,}$/), expiresAt: instant, currentConsentRevision: integer2(1), receipts: list2(consent, 4, 4) });
1411
+ var occurrenceResult = object2({ eventId: uuid, accepted: literal2(true), replayed: bool, exposureId: nullable2(uuid) });
1412
+ consentResult.schema;
1413
+ occurrenceResult.schema;
1414
+ var subjectRenew = object2({ schemaVersion: literal2(1), ...scope, expectedConsentRevision: integer2(1), configRevision: revision, policyRevision: revision });
1415
+ subjectRenew.schema;
1416
+ resource.schema;
1417
+ audience.schema;
1418
+ experiment.schema;
1419
+ var audienceDraft = object2({
1420
+ schemaVersion: literal2(1),
1421
+ expectedRevision: optional2(integer2(1)),
1422
+ idempotencyKey: operationKey,
1423
+ 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 })
1424
+ });
1425
+ audienceDraft.schema;
1426
+ var managedExperimentBase = { expectedRevision: integer2(1), idempotencyKey: operationKey };
1427
+ var experimentCreateField = field2(SIGNAL_EXPERIMENT_CREATE_JSON_SCHEMA, (v, p) => {
1428
+ try {
1429
+ return parseSignalExperimentCreate(v);
1430
+ } catch (error) {
1431
+ return fail3(p, error instanceof Error ? error.message : "invalid experiment");
1432
+ }
1433
+ });
1434
+ var experimentUpdateField = field2(SIGNAL_EXPERIMENT_UPDATE_JSON_SCHEMA, (v, p) => {
1435
+ try {
1436
+ return parseSignalExperimentUpdate(v);
1437
+ } catch (error) {
1438
+ return fail3(p, error instanceof Error ? error.message : "invalid experiment");
1439
+ }
1440
+ });
1441
+ var managedExperimentCreate = object2({ ...managedExperimentBase, experiment: experimentCreateField });
1442
+ var managedExperimentUpdate = object2({ ...managedExperimentBase, experiment: experimentUpdateField });
1443
+ var managedExperimentLifecycle = object2(managedExperimentBase);
1444
+ var managedExperimentComplete = object2({ ...managedExperimentBase, winnerVariant: text3(80) });
1445
+ var managedExperimentLink = object2({ ...managedExperimentBase, experimentId: uuid });
1446
+ managedExperimentCreate.schema;
1447
+ managedExperimentUpdate.schema;
1448
+ managedExperimentLifecycle.schema;
1449
+ managedExperimentComplete.schema;
1450
+ managedExperimentLink.schema;
1451
+ 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) => {
1452
+ const result = instant.read(v, p);
1453
+ if (new Date(result).toISOString() !== result) fail3(p, "requires canonical UTC milliseconds");
1454
+ return result;
1455
+ });
1456
+ var positiveRevision = text3(128, /^[1-9][0-9]*(?![\s\S])/);
1457
+ var friendlyName = field2({ type: "string", minLength: 0, maxLength: 200 }, (v, p) => typeof v === "string" && [...v].length <= 200 ? v : fail3(p, "invalid friendly name"));
1458
+ var setupConsentPolicyShape = object2({ mode: literal2("basic"), requiredPurposes: uniqueList(purpose, 4, 3) });
1459
+ var setupConsentPolicy = field2({ ...setupConsentPolicyShape.schema, allOf: [{ properties: { requiredPurposes: { allOf: ["ad_storage", "ad_user_data", "ad_personalization"].map((value) => ({ contains: { const: value } })) } } }] }, (input, p) => {
1460
+ const v = setupConsentPolicyShape.read(input, p);
1461
+ for (const required of ["ad_storage", "ad_user_data", "ad_personalization"]) if (!v.requiredPurposes.includes(required)) fail3(p, "all advertising purpose requirements are mandatory");
1462
+ return v;
1463
+ });
1464
+ var measurementSave = refine3(object2({
1465
+ schemaVersion: literal2(1),
1466
+ site,
1467
+ expectedCampaignRevision: integer2(1),
1468
+ expectedConfigurationRevision: integer2(0),
1469
+ idempotencyKey: operationKey,
1470
+ enabled: bool,
1471
+ consentPolicy: setupConsentPolicy,
1472
+ pages: list2(object2({ pageId: uuid, observedRevision: nativePageRevision, observedDigest: digest }), 500, 1)
1473
+ }), (v, p) => unique(v.pages.map((page2) => page2.pageId), p + ".pages"));
1474
+ var measurementPage = object2({ pageId: uuid, label: friendlyName, path: observedPagePath, pageRevision: nativePageRevision, evidenceDigest: digest, resourceRuleId: uuid, resourceRuleRevision: digest });
1475
+ var measurementSavedFields = { configurationRevision: integer2(1), configurationDigest: digest, configuration: measurementConfig, saveOperationId: uuid, pages: list2(measurementPage, 500, 1) };
1476
+ object2(measurementSavedFields);
1477
+ function checkMeasurementSaved(v, p) {
1478
+ const config = parseResonanceMeasurementConfig(v.configuration);
1479
+ if (config.projectId !== v.projectId || config.site !== v.site) fail3(p + ".configuration", "configuration scope mismatch");
1480
+ positiveRevision.read(config.configRevision, p + ".configuration.configRevision");
1481
+ positiveRevision.read(config.policyRevision, p + ".configuration.policyRevision");
1482
+ setupConsentPolicy.read(config.consentPolicy, p + ".configuration.consentPolicy");
1483
+ unique(v.pages.map((page2) => page2.pageId), p + ".pages");
1484
+ if (v.pages.length !== config.resourceRules.length) fail3(p + ".pages", "must cover the exact native page rules");
1485
+ for (const page2 of v.pages) {
1486
+ const rule = config.resourceRules.find((rule2) => rule2.id === page2.resourceRuleId);
1487
+ 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");
1488
+ }
1489
+ }
1490
+ var measurementCurrent = refine3(union2(
1491
+ object2({ schemaVersion: literal2(1), kind: literal2("unconfigured"), ...scope, configurationRevision: literal2(0) }),
1492
+ object2({ schemaVersion: literal2(1), kind: literal2("configured"), ...scope, ...measurementSavedFields, reasonCodes: uniqueList(text3(200), 100) })
1493
+ ), (v, p) => {
1494
+ if (v.kind === "configured") checkMeasurementSaved(v, p);
1495
+ });
1496
+ var measurementSnapshotFields = { schemaVersion: literal2(1), ...scope, campaignId: uuid, operationId: uuid, configurationRevision: integer2(1), configurationDigest: digest, configuration: measurementConfig, pages: list2(measurementPage, 500, 1) };
1497
+ var measurementSnapshotShape = object2(measurementSnapshotFields);
1498
+ function checkMeasurementSnapshot(v, p) {
1499
+ checkMeasurementSaved({ ...v, saveOperationId: v.operationId }, p);
1500
+ }
1501
+ var measurementSnapshot = refine3(measurementSnapshotShape, checkMeasurementSnapshot);
1502
+ var measurementSaveResponse = refine3(object2({ ...measurementSnapshotFields, replayed: bool }), checkMeasurementSnapshot);
1503
+ object2({ projectId: uuid, current: measurementCurrent, pages: list2(object2({ pageId: uuid, label: friendlyName, path: observedPagePath, pageRevision: nativePageRevision, evidenceDigest: digest }), 500, 1), expiresAt: instant });
1504
+ measurementSave.schema;
1505
+ measurementCurrent.schema;
1506
+ measurementSnapshot.schema;
1507
+ measurementSaveResponse.schema;
1508
+ var nativeAudienceId = text3(160, /^[0-9]+(?![\s\S])/);
1509
+ var RESONANCE_META_DATASET_NAME_MAX_LENGTH = 160;
1510
+ var metaDatasetName = refine3(text3(RESONANCE_META_DATASET_NAME_MAX_LENGTH), (value, at) => {
1511
+ if (!value.trim() || value !== value.trim() || /[\x00-\x1f\x7f]/.test(value)) fail3(at, "requires a trimmed dataset name without control characters");
1512
+ });
1513
+ var metaDatasetExistingSelection = object2({ kind: literal2("existing"), externalId: nativeAudienceId });
1514
+ var metaDatasetSetupSelection = union2(
1515
+ metaDatasetExistingSelection,
1516
+ object2({ kind: literal2("create_if_none"), name: metaDatasetName })
1517
+ );
1518
+ var metaDatasetSetupPrepareFields = {
1519
+ schemaVersion: literal2(1),
1520
+ site,
1521
+ accountBindingId: uuid,
1522
+ expectedDraftRevision: integer2(1),
1523
+ idempotencyKey: operationKey,
1524
+ selection: metaDatasetSetupSelection
1525
+ };
1526
+ var metaDatasetSetupPrepare = object2(metaDatasetSetupPrepareFields);
1527
+ metaDatasetSetupPrepare.schema;
1528
+ var metaDatasetSelectionRequest = object2({ ...metaDatasetSetupPrepareFields, selection: metaDatasetExistingSelection });
1529
+ var metaDatasetSelectionWitness = object2({ externalId: nativeAudienceId, resourceRevision: revision, observedAt: instant });
1530
+ metaDatasetSelectionRequest.schema;
1531
+ metaDatasetSelectionWitness.schema;
1532
+ var metaSetupOwnerFields = {
1533
+ orgId: uuid,
1534
+ projectId: uuid,
1535
+ campaignId: uuid,
1536
+ connectionId: uuid,
1537
+ accountBindingRevision: integer2(1),
1538
+ connectionRevision: revision,
1539
+ capabilityRevision: revision,
1540
+ expectedKillRevision: integer2(0),
1541
+ externalAccountId: nativeAudienceId,
1542
+ businessId: nativeAudienceId
1543
+ };
1544
+ var metaDatasetSetupIntent = object2({ ...metaDatasetSetupPrepareFields, ...metaSetupOwnerFields });
1545
+ var metaDatasetSetupReview = object2({ intent: metaDatasetSetupIntent, requestDigest: digest });
1546
+ metaDatasetSetupReview.schema;
1547
+ var metaDatasetSetupFirstOutcome = object2({
1548
+ admission: choice2("accepted", "rejected", "unknown"),
1549
+ externalId: nullable2(nativeAudienceId),
1550
+ providerRequestId: nullable2(text3(200)),
1551
+ providerRequestDigest: digest
1552
+ });
1553
+ var metaSetupVerificationFields = {
1554
+ externalId: nativeAudienceId,
1555
+ externalAccountId: nativeAudienceId,
1556
+ businessId: nativeAudienceId,
1557
+ resourceRevision: revision,
1558
+ observedAt: instant
1559
+ };
1560
+ var metaDatasetSetupVerification = object2(metaSetupVerificationFields);
1561
+ var metaSetupReceiptFields = {
1562
+ schemaVersion: literal2(1),
1563
+ operationId: uuid,
1564
+ projectId: uuid,
1565
+ campaignId: uuid,
1566
+ site,
1567
+ accountBindingId: uuid,
1568
+ requestDigest: digest,
1569
+ status: choice2("pending", "selected", "created_unverified", "verified", "rejected", "uncertain", "cancelled"),
1570
+ firstOutcome: nullable2(metaDatasetSetupFirstOutcome),
1571
+ reasonCodes: uniqueList(text3(80, /^[a-z][a-z0-9_]*$/), 30)
1572
+ };
1573
+ function checkMetaSetupReceipt(value, at, resource2) {
1574
+ const { status, firstOutcome, currentVerification } = value;
1575
+ if (firstOutcome && firstOutcome.admission === "accepted" !== (firstOutcome.externalId !== null)) {
1576
+ fail3(at + ".firstOutcome", "requires the original provider ID exactly when creation was accepted");
1577
+ }
1578
+ switch (status) {
1579
+ case "pending":
1580
+ case "cancelled":
1581
+ if (firstOutcome || currentVerification) fail3(at, "cannot carry a creation outcome or verification");
1582
+ break;
1583
+ case "selected":
1584
+ if (firstOutcome || !currentVerification) fail3(at, "requires verified existing selection without a creation outcome");
1585
+ break;
1586
+ case "created_unverified":
1587
+ if (firstOutcome?.admission !== "accepted" || currentVerification) fail3(at, "requires accepted creation and no verified readback");
1588
+ break;
1589
+ case "verified":
1590
+ if (firstOutcome?.admission !== "accepted" || !currentVerification || firstOutcome.externalId !== currentVerification.externalId) {
1591
+ fail3(at, `requires verified readback of the exact created ${resource2}`);
1592
+ }
1593
+ break;
1594
+ case "rejected":
1595
+ if (firstOutcome?.admission !== "rejected") fail3(at, "requires the original rejection");
1596
+ break;
1597
+ case "uncertain":
1598
+ if (firstOutcome?.admission !== "unknown" || currentVerification) fail3(at, `requires an unknown outcome without an attributable ${resource2}`);
1599
+ break;
1600
+ }
1601
+ }
1602
+ var metaSetupReceiptState = object2({ ...metaSetupReceiptFields, currentVerification: nullable2(metaDatasetSetupVerification) });
1603
+ var metaDatasetSetupReceipt = refine3(metaSetupReceiptState, (value, at) => checkMetaSetupReceipt(value, at, "dataset"));
1604
+ metaDatasetSetupReceipt.schema;
1605
+ var metaAudienceSetupResource = object2({ externalId: nativeAudienceId, resourceRevision: revision });
1606
+ var metaAudienceSetupSelection = union2(
1607
+ object2({ kind: literal2("existing"), externalId: nativeAudienceId, resourceRevision: revision }),
1608
+ object2({ kind: literal2("create_if_none") })
1609
+ );
1610
+ var websiteVisitSetupChoice = union2(
1611
+ object2({ kind: literal2("off") }),
1612
+ object2({ kind: literal2("enable"), expiresAt: instant })
1613
+ );
1614
+ var metaAudienceSetupPrepareFields = {
1615
+ schemaVersion: literal2(1),
1616
+ site,
1617
+ accountBindingId: uuid,
1618
+ expectedDraftRevision: integer2(1),
1619
+ idempotencyKey: operationKey,
1620
+ dataset: metaAudienceSetupResource,
1621
+ audienceRule: measurementRuleRef,
1622
+ selection: metaAudienceSetupSelection,
1623
+ feed: websiteVisitSetupChoice
1624
+ };
1625
+ var metaAudienceSetupPrepare = object2(metaAudienceSetupPrepareFields);
1626
+ metaAudienceSetupPrepare.schema;
1627
+ var metaAudienceSetupIntent = refine3(object2({
1628
+ ...metaAudienceSetupPrepareFields,
1629
+ ...metaSetupOwnerFields,
1630
+ audienceRuleRef: audience,
1631
+ resourceRuleRef: measurementRuleRef,
1632
+ excludedResourceRuleRefs: list2(measurementRuleRef, 50),
1633
+ measurementConfigRef,
1634
+ matchingProfileRef,
1635
+ audienceSpecDigest: digest,
1636
+ name: friendlyName,
1637
+ expiresAt: instant
1638
+ }), (value, at) => {
1639
+ const { audienceRule, audienceRuleRef, resourceRuleRef, excludedResourceRuleRefs, measurementConfigRef: measurementConfigRef2 } = value;
1640
+ 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");
1641
+ const excludedIds = excludedResourceRuleRefs.map((ref) => ref.id);
1642
+ unique(excludedIds, at + ".excludedResourceRuleRefs");
1643
+ if (excludedIds.includes(resourceRuleRef.id) || canonical([...audienceRuleRef.exclusionRuleIds].sort()) !== canonical(excludedIds.sort())) {
1644
+ fail3(at + ".excludedResourceRuleRefs", "requires the exact exclusions disjoint from the positive rule");
1645
+ }
1646
+ checkAudienceBand(audienceRuleRef, "meta_ads", at + ".audienceRuleRef");
1647
+ });
1648
+ var metaAudienceSetupReview = object2({ intent: metaAudienceSetupIntent, requestDigest: digest });
1649
+ metaAudienceSetupReview.schema;
1650
+ var META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS = 180;
1651
+ var metaAudienceSetupVerification = object2({
1652
+ ...metaSetupVerificationFields,
1653
+ datasetExternalId: nativeAudienceId,
1654
+ datasetResourceRevision: revision,
1655
+ audienceSpecDigest: digest,
1656
+ retentionDays: integer2(1, META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS)
1657
+ });
1658
+ var metaAudienceSetupReceipt = refine3(object2({
1659
+ ...metaSetupReceiptFields,
1660
+ currentVerification: nullable2(metaAudienceSetupVerification)
1661
+ }), (value, at) => checkMetaSetupReceipt(value, at, "audience"));
1662
+ metaAudienceSetupReceipt.schema;
1663
+ var websiteVisitSetupGrantProof = refine3(object2({
1664
+ schemaVersion: literal2(1),
1665
+ grantOperationId: uuid,
1666
+ audienceOperationId: uuid,
1667
+ approvalActionId: uuid,
1668
+ requestDigest: digest,
1669
+ audienceReceiptDigest: digest,
1670
+ generation: integer2(1),
1671
+ activatedAt: instant,
1672
+ expiresAt: instant,
1673
+ projectId: uuid,
1674
+ campaignId: uuid,
1675
+ site,
1676
+ accountBindingId: uuid,
1677
+ audience: metaAudienceSetupVerification
1678
+ }), (value, at) => {
1679
+ if (value.grantOperationId.toLowerCase() === value.audienceOperationId.toLowerCase()) fail3(at + ".grantOperationId", "requires a distinct native grant operation");
1680
+ 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");
1681
+ });
1682
+ var websiteVisitSetupGrantStatus = refine3(object2({
1683
+ proof: websiteVisitSetupGrantProof,
1684
+ status: choice2("active", "revoked", "expired", "invalidated"),
1685
+ checkedAt: instant,
1686
+ revokedAt: nullable2(instant),
1687
+ reasonCodes: metaSetupReceiptFields.reasonCodes
1688
+ }), (value, at) => {
1689
+ const checked = Date.parse(value.checkedAt), activated = Date.parse(value.proof.activatedAt), expires = Date.parse(value.proof.expiresAt);
1690
+ if (checked < activated) fail3(at + ".checkedAt", "cannot predate activation");
1691
+ if (value.status === "revoked") {
1692
+ if (!value.revokedAt || Date.parse(value.revokedAt) < activated || Date.parse(value.revokedAt) > checked) {
1693
+ fail3(at + ".revokedAt", "requires the recorded revocation between activation and observation");
1694
+ }
1695
+ } else if (value.revokedAt) fail3(at + ".revokedAt", "requires revoked status");
1696
+ if (value.status === "active" && checked >= expires || value.status === "expired" && checked < expires) {
1697
+ fail3(at + ".status", "must agree with the original expiry");
1698
+ }
1699
+ });
1700
+ websiteVisitSetupGrantProof.schema;
1701
+ websiteVisitSetupGrantStatus.schema;
1702
+ var metaAudienceSetupStatusFields = { receipt: metaAudienceSetupReceipt, grant: nullable2(websiteVisitSetupGrantStatus) };
1703
+ function checkMetaAudienceSetupStatus({ receipt: receipt2, grant }, at) {
1704
+ if (!grant) return;
1705
+ const { proof } = grant;
1706
+ if (receipt2.status !== "selected" && receipt2.status !== "verified" || !receipt2.currentVerification || canonical(receipt2.currentVerification) !== canonical(proof.audience)) {
1707
+ fail3(at + ".grant", "requires the same verified audience witness as the setup receipt");
1708
+ }
1709
+ 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) {
1710
+ fail3(at + ".grant", "requires the grant linked to this exact setup operation");
1711
+ }
1712
+ }
1713
+ var metaAudienceSetupStatusShape = object2(metaAudienceSetupStatusFields);
1714
+ var metaAudienceSetupStatus = refine3(metaAudienceSetupStatusShape, checkMetaAudienceSetupStatus);
1715
+ metaAudienceSetupStatus.schema;
1716
+ var metaAudienceSetupListItem = refine3(object2({ ledgerActionId: uuid, ...metaAudienceSetupStatusFields }), (item, at) => {
1717
+ checkMetaAudienceSetupStatus(item, at);
1718
+ if (item.grant && item.grant.proof.approvalActionId.toLowerCase() !== item.ledgerActionId.toLowerCase()) {
1719
+ fail3(at + ".ledgerActionId", "requires the original approval linked to this grant");
1720
+ }
1721
+ });
1722
+ var metaAudienceSetupList = refine3(object2({
1723
+ items: list2(metaAudienceSetupListItem, 25),
1724
+ nextCursor: nullable2(uuid)
1725
+ }), ({ items }, at) => {
1726
+ unique(items.map((item) => item.receipt.operationId.toLowerCase()), at + ".items");
1727
+ });
1728
+ metaAudienceSetupList.schema;
1729
+ refine3(object2({
1730
+ proof: websiteVisitSetupGrantProof,
1731
+ intent: metaAudienceSetupIntent
1732
+ }), (value, at) => {
1733
+ const { proof, intent } = value;
1734
+ const { audience: witness } = proof;
1735
+ 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");
1736
+ 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) {
1737
+ fail3(at, "requires the exact original scope and verified destination");
1738
+ }
1739
+ if (intent.selection.kind === "existing" && (witness.externalId !== intent.selection.externalId || witness.resourceRevision !== intent.selection.resourceRevision)) {
1740
+ fail3(at, "requires verification of the exact existing audience");
1741
+ }
1742
+ });
1743
+ var websiteVisitSetupOrigin = object2({ kind: literal2("setup"), grantOperationId: uuid, generation: integer2(1) });
1744
+ var websiteVisitSetupAcceptedVisitFields = { acceptedVisits: integer2(0), checkedAt: instant };
1745
+ var websiteVisitSetupGrantAcceptedVisits = object2({ grantOperationId: uuid, ...websiteVisitSetupAcceptedVisitFields });
1746
+ websiteVisitSetupGrantAcceptedVisits.schema;
1747
+ var websiteVisitSetupDeliveryCommand = object2({
1748
+ schemaVersion: literal2(1),
1749
+ operation: literal2("deliver_website_visit"),
1750
+ campaignId: uuid,
1751
+ occurrenceId: uuid,
1752
+ idempotencyKey: operationKey,
1753
+ setupOrigin: websiteVisitSetupOrigin
1754
+ });
1755
+ websiteVisitSetupDeliveryCommand.schema;
1756
+ object2({ activatedAt: instant, expiresAt: instant, now: instant });
1757
+ var nativeAudienceRef = object2({ externalId: nativeAudienceId, revision: digest });
1758
+ var metaSave = refine3(object2({
1759
+ schemaVersion: literal2(1),
1760
+ expectedCampaignRevision: integer2(1),
1761
+ expectedConfigurationRevision: integer2(0),
1762
+ idempotencyKey: operationKey,
1763
+ audiences: list2(union2(object2({ audienceRuleId: uuid, mode: literal2("existing"), nativeAudienceRef }), object2({ audienceRuleId: uuid, mode: literal2("admitted_setup") })), 50, 1)
1764
+ }), (v, p) => unique(v.audiences.map((a) => a.audienceRuleId), p + ".audiences"));
1765
+ var metaResolvedAudience = object2({ audienceRuleRef: audience, name: friendlyName, resourceRuleRef: measurementRuleRef, excludedResourceRuleRefs: list2(measurementRuleRef, 50), selection: union2(
1766
+ object2({ mode: literal2("existing"), nativeAudienceRef, nativeAudienceName: nullable2(friendlyName) }),
1767
+ object2({ mode: literal2("admitted_setup"), setup: object2({ kind: literal2("meta_website_audience_v1"), localOutputKey: operationKey, specDigest: digest }) })
1768
+ ) });
1769
+ var metaMaterialFields = {
1770
+ schemaVersion: literal2(1),
1771
+ projectId: uuid,
1772
+ campaignId: uuid,
1773
+ channelId: uuid,
1774
+ site,
1775
+ campaignRevision: integer2(1),
1776
+ reviewedDefinitionDigest: digest,
1777
+ configurationRevision: integer2(1),
1778
+ saveOperationId: uuid,
1779
+ channel: meta,
1780
+ account: object2({ id: uuid, externalId: text3(160), name: nullable2(friendlyName) }),
1781
+ datasetName: nullable2(friendlyName),
1782
+ pageName: nullable2(friendlyName),
1783
+ instagramName: nullable2(friendlyName),
1784
+ measurementConfigRef,
1785
+ matchingProfileRef,
1786
+ rules: list2(object2({ id: uuid, revision, resource: interestResource, path: observedPagePath, label: friendlyName }), 500, 1),
1787
+ audiences: list2(metaResolvedAudience, 50, 1)
1788
+ };
1789
+ object2(metaMaterialFields);
1790
+ function checkMetaMaterial(v, p) {
1791
+ scoped(v, v.projectId, [v.site], p);
1792
+ 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");
1793
+ if (!v.channel.instagramRef && v.instagramName !== null) fail3(p + ".instagramName", "absent original Instagram identity requires null");
1794
+ unique(v.rules.map((rule) => rule.id), p + ".rules");
1795
+ unique(v.audiences.map((a) => a.audienceRuleRef.id), p + ".audiences");
1796
+ unique(v.channel.audienceRuleRefs.map((a) => a.id), p + ".channel.audienceRuleRefs");
1797
+ if (v.audiences.length !== v.channel.audienceRuleRefs.length) fail3(p + ".audiences", "must cover exactly the original logical audiences");
1798
+ checkMetaAudienceBands(v.channel, p + ".channel.audienceRuleRefs");
1799
+ for (const a of v.audiences) {
1800
+ if (!v.channel.audienceRuleRefs.some((ref) => canonical(ref) === canonical(a.audienceRuleRef))) fail3(p + ".audiences", "original logical audience version mismatch");
1801
+ unique(a.excludedResourceRuleRefs.map((ref) => ref.id), p + ".audiences.excludedResourceRuleRefs");
1802
+ unique(a.audienceRuleRef.exclusionRuleIds, p + ".audiences.audienceRuleRef.exclusionRuleIds");
1803
+ 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");
1804
+ 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");
1805
+ 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");
1806
+ }
1807
+ }
1808
+ var metaSnapshot = refine3(object2({ ...metaMaterialFields, configurationDigest: digest }), checkMetaMaterial);
1809
+ var parseResonanceMetaConfigurationSnapshot = (v) => metaSnapshot.read(v, "metaConfigurationSnapshot");
1810
+ refine3(object2({ ...metaMaterialFields, configurationDigest: optional2(digest) }), checkMetaMaterial);
1811
+ object2({ currentCampaignRevision: integer2(1), currentDefinitionDigest: digest, observedAt: instant, expiresAt: nullable2(instant), reasonCodes: uniqueList(text3(200), 100), pendingRequirements: uniqueList(text3(200), 100) });
1812
+ function metaReviewable(snapshot, metadata) {
1813
+ return metadata.currentCampaignRevision >= snapshot.campaignRevision && metadata.currentDefinitionDigest === snapshot.reviewedDefinitionDigest && metadata.reasonCodes.length === 0 && metadata.expiresAt !== null && Date.parse(metadata.expiresAt) > Date.parse(metadata.observedAt);
1814
+ }
1815
+ var metaView = refine3(union2(
1816
+ object2({ schemaVersion: literal2(1), kind: literal2("unconfigured"), projectId: uuid, campaignId: uuid, channelId: uuid, configurationRevision: literal2(0) }),
1817
+ object2({
1818
+ schemaVersion: literal2(1),
1819
+ kind: literal2("configured"),
1820
+ projectId: uuid,
1821
+ campaignId: uuid,
1822
+ channelId: uuid,
1823
+ configurationRevision: integer2(1),
1824
+ snapshot: metaSnapshot,
1825
+ currentCampaignRevision: integer2(1),
1826
+ currentDefinitionDigest: digest,
1827
+ observedAt: instant,
1828
+ expiresAt: nullable2(instant),
1829
+ readyForReview: bool,
1830
+ reasonCodes: uniqueList(text3(200), 100),
1831
+ pendingRequirements: uniqueList(text3(200), 100)
1832
+ })
1833
+ ), (v, p) => {
1834
+ if (v.kind !== "configured") return;
1835
+ const s = parseResonanceMetaConfigurationSnapshot(v.snapshot);
1836
+ 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");
1837
+ if (v.readyForReview !== metaReviewable(s, v)) fail3(p + ".readyForReview", "must reflect current review prerequisites only");
1838
+ });
1839
+ var RESONANCE_META_AUDIENCE_VERDICTS = ["ready", "too_small", "blocked", "unknown"];
1840
+ var RESONANCE_META_AUDIENCE_REASONS = [
1841
+ "meta_audience_status_unreadable",
1842
+ "meta_audience_status_unrecognized",
1843
+ "meta_audience_integrity_flagged",
1844
+ "meta_audience_account_inactive",
1845
+ "meta_audience_pixel_problem",
1846
+ "meta_audience_error",
1847
+ "meta_audience_out_of_date",
1848
+ "meta_audience_too_small",
1849
+ "meta_audience_not_usable",
1850
+ "meta_audience_prefill_failed",
1851
+ "meta_audience_filling",
1852
+ "meta_audience_category_unknown",
1853
+ "meta_url_audience_unverified",
1854
+ "meta_core_setup_suspected",
1855
+ "meta_audience_fill_mismatch",
1856
+ "meta_core_setup_attestation_missing",
1857
+ "meta_flight_too_short_after_wait",
1858
+ "meta_terms_nondiscrimination_pending",
1859
+ "meta_terms_custom_audience_unconfirmed",
1860
+ "meta_terms_business_tools_pending",
1861
+ "meta_special_category_age_must_be_provider_managed",
1862
+ "meta_special_category_genders_not_allowed",
1863
+ "meta_audience_name_sensitive"
1864
+ ];
1865
+ var metaReadinessPage = object2({ resourceRuleRef: measurementRuleRef, path: observedPagePath, label: nullable2(friendlyName) });
1866
+ var metaAudienceSize = refine3(object2({ lower: integer2(0), upper: integer2(0) }), (v, p) => {
1867
+ if (v.upper < v.lower) fail3(p, "size bounds must be ordered");
1868
+ });
1869
+ var metaAudienceReadinessFields = {
1870
+ verdict: choice2(...RESONANCE_META_AUDIENCE_VERDICTS),
1871
+ reasonCodes: uniqueList(choice2(...RESONANCE_META_AUDIENCE_REASONS), 50),
1872
+ size: nullable2(metaAudienceSize)
1873
+ };
1874
+ var metaAudienceSetupReadiness = refine3(object2({
1875
+ status: metaAudienceSetupStatus,
1876
+ delivery: nullable2(object2(websiteVisitSetupAcceptedVisitFields)),
1877
+ providerAudience: nullable2(object2({ externalId: nativeAudienceId, observedAt: instant, readiness: object2(metaAudienceReadinessFields) }))
1878
+ }), ({ status, delivery, providerAudience }, at) => {
1879
+ if (delivery && (!status.grant || Date.parse(delivery.checkedAt) < Date.parse(status.grant.proof.activatedAt))) {
1880
+ fail3(at + ".delivery", "requires the grant and an observation at or after activation");
1881
+ }
1882
+ if (providerAudience && (status.receipt.status !== "selected" && status.receipt.status !== "verified" || status.receipt.currentVerification?.externalId !== providerAudience.externalId)) {
1883
+ fail3(at + ".providerAudience", "requires observation of the exact verified audience");
1884
+ }
1885
+ });
1886
+ metaAudienceSetupReadiness.schema;
1887
+ var metaReadinessCheck = union2(
1888
+ object2({ state: literal2("not_checked"), reasonCode: choice2("configuration_unavailable", "native_mapping_unavailable") }),
1889
+ object2({ state: literal2("observed"), mappingSource: choice2("selected_external_audience", "current_materialized_audience"), ...metaAudienceReadinessFields, observedAt: instant, expiresAt: nullable2(instant), sizeObservedAt: literal2(null), sizeExpiresAt: literal2(null) })
1890
+ );
1891
+ var metaReadinessAudience = object2({ audienceRuleRef: audience, name: friendlyName, includedPage: metaReadinessPage, excludedPages: list2(metaReadinessPage, 50), nativeAudienceId: nullable2(nativeAudienceId), check: metaReadinessCheck });
1892
+ 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) => {
1893
+ const sameId = (a, b) => a.toLowerCase() === b.toLowerCase();
1894
+ const config = v.configuration;
1895
+ if (!sameId(config.projectId, v.projectId) || !sameId(config.campaignId, v.campaignId) || !sameId(config.channelId, v.channelId)) fail3(p + ".configuration", "configuration scope mismatch");
1896
+ 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");
1897
+ unique(v.audiences.map((row) => row.audienceRuleRef.id.toLowerCase()), p + ".audiences");
1898
+ for (const row of v.audiences) {
1899
+ if (!sameId(row.audienceRuleRef.projectId, v.projectId) || row.audienceRuleRef.site !== v.site) fail3(p + ".audiences", "audience scope mismatch");
1900
+ const excluded = row.excludedPages.map((page2) => page2.resourceRuleRef.id.toLowerCase());
1901
+ unique(excluded, p + ".audiences.excludedPages");
1902
+ const expected = row.audienceRuleRef.exclusionRuleIds.map((id) => id.toLowerCase());
1903
+ unique(expected, p + ".audiences.audienceRuleRef.exclusionRuleIds");
1904
+ 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");
1905
+ 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");
1906
+ if (config.kind === "configured" && config.currentDefinitionDigest === config.snapshot.reviewedDefinitionDigest) {
1907
+ const original = config.snapshot.audiences.find((a) => sameId(a.audienceRuleRef.id, row.audienceRuleRef.id));
1908
+ 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");
1909
+ }
1910
+ }
1911
+ });
1912
+ metaRetargetingReadiness.schema;
1913
+ var metaSaveResponse = object2({ schemaVersion: literal2(1), snapshot: metaSnapshot, replayed: bool });
1914
+ metaSave.schema;
1915
+ metaSnapshot.schema;
1916
+ metaView.schema;
1917
+ metaSaveResponse.schema;
1918
+ var feedSelection = refine3(object2({ channels: list2(object2({ channelId: uuid, expectedConfigurationRevision: integer2(1), resourceRuleRefs: list2(measurementRuleRef, 500, 1) }), 100, 1) }), (v, p) => {
1919
+ unique(v.channels.map((c) => c.channelId), p + ".channels");
1920
+ for (const c of v.channels) unique(c.resourceRuleRefs.map((ref) => ref.id), p + ".resourceRuleRefs");
1921
+ });
1922
+ var mandateDraftRequest = object2({ expectedRevision: integer2(1), allowedOperations: mandateAllowedOperations, expiresAt: instant, websiteVisitFeedSelection: optional2(feedSelection), providerReporting: optional2(providerReportingSelection), operatingPolicySelection: optional2(operatingPolicySelection), activation: optional2(literal2("operating_policy")) });
1923
+ mandateDraftRequest.schema;
1924
+ 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) }) });
1925
+ feedReview.schema;
1926
+ var observationIdentity = { observationId: uuid, channelId: uuid, versionId: uuid, accountBindingId: uuid };
1927
+ var publicObservationMetric = union2(
1928
+ object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: literal2("observed"), value: metricValue }),
1929
+ object2({ ...metricBase, ...observationIdentity, source: choice2("provider", "first_party"), state: choice2("unknown", "insufficient", "delayed", "unavailable"), value: literal2(null), reasonCode: text3(80) })
1930
+ );
1931
+ var observationDenominators = object2({ eligibleContacts: nullable2(decimal), fullyResolvedContacts: nullable2(decimal), qualifiedContacts: nullable2(decimal) });
1932
+ var observationSupportFields = { ...observationIdentity, currency, fetchedAt: instant, dataThrough: nullable2(instant), coverage: choice2("unknown", "partial", "complete"), reasonCode: nullable2(text3(80)), denominators: observationDenominators };
1933
+ var firstPartyObservationSupport = object2({ ...observationSupportFields, source: literal2("first_party") });
1934
+ var providerObservationSupport = object2({
1935
+ ...observationSupportFields,
1936
+ source: literal2("provider"),
1937
+ firstReceivedAt: nullable2(instant),
1938
+ receivedAt: nullable2(instant),
1939
+ recordedAt: nullable2(instant),
1940
+ readClock: nullable2(providerReadClock),
1941
+ providerFinality: literal2("unknown"),
1942
+ correctionsPossible: literal2(true),
1943
+ coverageBasis: choice2("closed_query_snapshot", "not_established")
1944
+ });
1945
+ var observationSupport = union2(firstPartyObservationSupport, providerObservationSupport);
1946
+ var observationsPage = object2({ items: list2(publicObservationMetric, 500), nextCursor: nullable2(uuid), observedAt: instant, support: list2(observationSupport, 500) });
1947
+ publicObservationMetric.schema;
1948
+ observationSupport.schema;
1949
+ observationsPage.schema;
1950
+ var META_AUDIENCE_RULE_LIMIT = 10;
1951
+ var usesPropertyModel = (c) => c.channelGroup !== void 0 || c.audienceRuleRefs.some((ref) => ref.minDaysSinceVisit !== void 0);
1952
+ function checkAudienceBand(ref, provider = "meta_ads", at = "audienceRuleRef") {
1953
+ const min = ref.minDaysSinceVisit;
1954
+ if (min !== void 0 && min >= ref.retentionDays) fail3(at + ".minDaysSinceVisit", "must be shorter than the retention window");
1955
+ if (provider === "google_ads") {
1956
+ if (min !== void 0) fail3(at + ".minDaysSinceVisit", "Google audiences have no recency band");
1957
+ return;
1958
+ }
1959
+ 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`);
1960
+ 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`);
1961
+ }
1962
+ function checkMetaAudienceBands(channel2, at) {
1963
+ if (!usesPropertyModel(channel2)) return;
1964
+ channel2.audienceRuleRefs.forEach((ref, index) => checkAudienceBand(ref, "meta_ads", `${at}[${index}]`));
1965
+ }
1966
+
1967
+ // src/contracts/delegated-command.ts
1968
+ var DelegatedCommandValidationError = class extends Error {
1969
+ constructor(path2, reason) {
1970
+ super(`${path2}: ${reason}`);
1971
+ this.path = path2;
1972
+ this.name = "DelegatedCommandValidationError";
1973
+ }
1974
+ };
1975
+ var fail4 = (path2, reason) => {
1976
+ throw new DelegatedCommandValidationError(path2, reason);
1977
+ };
1978
+ var { field: field3, text: text4, choice: choice3, literal: literal3, integer: integer3, bool: bool2, nullable: nullable3, list: list3, object: object3, union: union3, refine: refine4 } = createWireSchema(fail4, (error) => error instanceof DelegatedCommandValidationError);
1979
+ var uuid2 = text4(36, UUID_V1_TO_V8_PATTERN);
1980
+ var digest2 = text4(64, /^[a-f0-9]{64}$/);
1981
+ var micros = text4(30, /^(?:0|[1-9][0-9]{0,29})$/);
1982
+ var instant2 = refine4(text4(30, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/), (v, p) => {
1983
+ if (!Number.isFinite(Date.parse(v)) || new Date(v).toISOString().slice(0, 19) !== v.slice(0, 19) || v.startsWith("0000")) fail4(p, "invalid UTC instant");
1984
+ });
1985
+ var utcMicros = (v) => BigInt(Date.parse(v.slice(0, 19) + "Z")) * 1000n + BigInt((v.includes(".") ? v.slice(20, -1) : "").padEnd(6, "0"));
1986
+ var nativeCasTimestamp = field3(NATIVE_CAS_TIMESTAMP_JSON_SCHEMA, (v, p) => {
1987
+ try {
1988
+ return parseNativeCasTimestamp(v);
1989
+ } catch {
1990
+ return fail4(p, "invalid native CAS timestamp");
1991
+ }
1992
+ });
1993
+ var site2 = refine4(text4(253), (v, p) => {
1994
+ if (!isNormalizedSiteHost(v) || isBlockedPublicUrlHost(v)) fail4(p, "requires normalized public host");
1995
+ });
1996
+ var unique2 = (values, path2) => {
1997
+ if (new Set(values.map((v) => v.toLowerCase())).size !== values.length) fail4(path2, "duplicate scope");
1998
+ };
1999
+ var DELEGATED_COMMAND_FAMILIES = ["resonance.mandate", "resonance.operating_policy", "resonance.optimize", "resonance.diagnostics"];
2000
+ var family = choice3(...DELEGATED_COMMAND_FAMILIES);
2001
+ var DELEGATED_COMMAND_REASON_CODES = [
2002
+ "POLICY_MISSING",
2003
+ "POLICY_DISABLED",
2004
+ "POLICY_NOT_YET_VALID",
2005
+ "POLICY_EXPIRED",
2006
+ "POLICY_REVOKED",
2007
+ "POLICY_REVISION_CHANGED",
2008
+ "TOKEN_REVOKED",
2009
+ "ACTOR_INACTIVE",
2010
+ "PRINCIPAL_INACTIVE",
2011
+ "MEMBERSHIP_REQUIRED",
2012
+ "SCOPE_MISMATCH",
2013
+ "FAMILY_NOT_GRANTED",
2014
+ "NATIVE_AUTHORITY_REQUIRED",
2015
+ "STATE_CONFLICT",
2016
+ "KILL_ACTIVE",
2017
+ "CURRENCY_MISMATCH",
2018
+ "CAMPAIGN_CEILING_EXCEEDED",
2019
+ "OUTSTANDING_CEILING_EXCEEDED",
2020
+ "CHANGE_LIMIT_EXCEEDED",
2021
+ "FLIGHT_LIMIT_EXCEEDED",
2022
+ "OPERATION_LIMIT_EXCEEDED",
2023
+ "ACTION_DIGEST_MISMATCH",
2024
+ "UNKNOWN_ACTION_KIND"
2025
+ ];
2026
+ var reasons = list3(choice3(...DELEGATED_COMMAND_REASON_CODES), DELEGATED_COMMAND_REASON_CODES.length);
2027
+ var campaignScope = union3(
2028
+ refine4(object3({ mode: literal3("selected"), campaignIds: list3(uuid2, 500) }), (v, p) => unique2(v.campaignIds, p + ".campaignIds")),
2029
+ object3({ mode: literal3("all_in_projects") })
2030
+ );
2031
+ var scopeFields = {
2032
+ projects: list3(uuid2, 500),
2033
+ campaignScope,
2034
+ accountBindingIds: list3(uuid2, 500),
2035
+ sites: list3(site2, 500)
2036
+ };
2037
+ var checkScope = (v, p) => {
2038
+ for (const key of ["projects", "accountBindingIds", "sites"]) unique2(v[key], p + "." + key);
2039
+ };
2040
+ var financialLimits = object3({
2041
+ currency: choice3(...RESONANCE_CURRENCIES),
2042
+ maxCampaignBudgetMicros: micros,
2043
+ maxOutstandingMicros: micros,
2044
+ maxChangeBasisPoints: integer3(0, 1e4)
2045
+ });
2046
+ var executionPolicy = refine4(object3({
2047
+ schemaVersion: literal3(1),
2048
+ enabled: bool2,
2049
+ ...scopeFields,
2050
+ actionFamilies: list3(family, 4),
2051
+ notBefore: instant2,
2052
+ expiresAt: instant2,
2053
+ financialLimits,
2054
+ maxOperations: integer3(1, 1e3),
2055
+ maxFlightDays: integer3(1, 365)
2056
+ }), (v, p) => {
2057
+ checkScope(v, p);
2058
+ unique2(v.actionFamilies, p + ".actionFamilies");
2059
+ if (utcMicros(v.expiresAt) <= utcMicros(v.notBefore)) fail4(p + ".expiresAt", "must follow notBefore");
2060
+ });
2061
+ var parseAgentExecutionPolicy = (v) => executionPolicy.read(v, "executionPolicy");
2062
+ var AGENT_EXECUTION_POLICY_JSON_SCHEMA = executionPolicy.schema;
2063
+ var policyUpdate = object3({ expectedRevision: integer3(0), policy: nullable3(executionPolicy) });
2064
+ var parseAgentExecutionPolicyUpdate = (v) => policyUpdate.read(v, "executionPolicyUpdate");
2065
+ var AGENT_EXECUTION_POLICY_UPDATE_JSON_SCHEMA = policyUpdate.schema;
2066
+ var effectiveScope = refine4(object3({
2067
+ ...scopeFields,
2068
+ financialLimits,
2069
+ notBefore: instant2,
2070
+ expiresAt: instant2,
2071
+ maxOperations: integer3(1, 1e3),
2072
+ operationsUsed: integer3(0, 1e3),
2073
+ operationsRemaining: integer3(0, 1e3),
2074
+ maxFlightDays: integer3(1, 365)
2075
+ }), (v, p) => {
2076
+ checkScope(v, p);
2077
+ if (utcMicros(v.expiresAt) <= utcMicros(v.notBefore)) fail4(p, "invalid validity interval");
2078
+ if (v.operationsUsed + v.operationsRemaining !== v.maxOperations) fail4(p, "operation counts must reconcile");
2079
+ });
2080
+ var capability2 = refine4(object3({
2081
+ family,
2082
+ mode: choice3("direct", "propose_only", "unavailable"),
2083
+ reasonCodes: reasons,
2084
+ effectiveScope: nullable3(effectiveScope)
2085
+ }), (v, p) => {
2086
+ unique2(v.reasonCodes, p + ".reasonCodes");
2087
+ if (v.mode === "direct" && (!v.effectiveScope || v.reasonCodes.length || !v.effectiveScope.operationsRemaining || ["projects", "accountBindingIds", "sites"].some((key) => !v.effectiveScope[key].length) || v.effectiveScope.campaignScope.mode === "selected" && !v.effectiveScope.campaignScope.campaignIds.length)) fail4(p, "direct requires an available bounded scope");
2088
+ if (v.mode !== "direct" && !v.reasonCodes.length) fail4(p, "non-direct capability requires a reason");
2089
+ });
2090
+ var authoritySummary = refine4(object3({
2091
+ schemaVersion: literal3(1),
2092
+ actorContactId: uuid2,
2093
+ principalContactId: uuid2,
2094
+ organizationId: uuid2,
2095
+ policyRevision: nullable3(integer3(1)),
2096
+ policyState: choice3("active", "missing", "disabled", "expired", "revoked", "not_yet_valid"),
2097
+ capabilities: list3(capability2, 4, 4),
2098
+ observedAt: instant2
2099
+ }), (v, p) => {
2100
+ if (v.actorContactId.toLowerCase() === v.principalContactId.toLowerCase()) fail4(p, "agent and principal must remain distinct");
2101
+ unique2(v.capabilities.map((c) => c.family), p + ".capabilities");
2102
+ if (v.policyState === "missing" !== (v.policyRevision === null)) fail4(p, "missing policy alone has no revision");
2103
+ for (const c of v.capabilities) if (c.mode === "direct") {
2104
+ if (v.policyState !== "active") fail4(p, "inactive policy cannot grant direct execution");
2105
+ if (utcMicros(v.observedAt) < utcMicros(c.effectiveScope.notBefore) || utcMicros(v.observedAt) >= utcMicros(c.effectiveScope.expiresAt)) fail4(p, "direct scope must be current at observation");
2106
+ }
2107
+ });
2108
+ var parseDelegatedCommandAuthoritySummary = (v) => authoritySummary.read(v, "delegatedCommandAuthoritySummary");
2109
+ var DELEGATED_COMMAND_AUTHORITY_SUMMARY_JSON_SCHEMA = authoritySummary.schema;
2110
+ var delegation = object3({ schemaVersion: literal3(1), tokenId: uuid2, policyRevision: integer3(1), ledgerActionId: uuid2, payloadDigest: digest2 });
2111
+ var parseDelegatedCommandProofReference = (v) => delegation.read(v, "delegation");
2112
+ var DELEGATED_COMMAND_PROOF_REFERENCE_JSON_SCHEMA = delegation.schema;
2113
+ var approval = object3({ by: uuid2, via: literal3("mcp"), at: instant2, basis: literal3("delegated_agent"), delegation });
2114
+ var parseDelegatedCommandApproval = (v) => approval.read(v, "delegatedCommandApproval");
2115
+ var DELEGATED_COMMAND_APPROVAL_JSON_SCHEMA = approval.schema;
2116
+ var DELEGATED_COMMAND_CLAIM_ROUTE = "/agents/me/execution-actions/:ledgerId/claim";
2117
+ var claimRequest = object3({ projectId: uuid2, expectedUpdatedAt: nativeCasTimestamp, expectedPolicyRevision: integer3(1) });
2118
+ var parseDelegatedCommandClaimRequest = (v) => claimRequest.read(v, "delegatedCommandClaimRequest");
2119
+ var DELEGATED_COMMAND_CLAIM_REQUEST_JSON_SCHEMA = claimRequest.schema;
2120
+ var RESONANCE_OPERATING_POLICY_RECOVERY_ROUTE = "/resonance/projects/:projectId/campaigns/:campaignId/operating-policies/:actionId/recover";
2121
+ var policyRecoveryRequest = object3({ expectedUpdatedAt: nativeCasTimestamp });
2122
+ var parseResonanceOperatingPolicyRecoveryRequest = (v) => policyRecoveryRequest.read(v, "operatingPolicyRecoveryRequest");
2123
+ var RESONANCE_OPERATING_POLICY_RECOVERY_REQUEST_JSON_SCHEMA = policyRecoveryRequest.schema;
2124
+ var admissionFields = {
2125
+ schemaVersion: literal3(1),
2126
+ tokenId: uuid2,
2127
+ actorContactId: uuid2,
2128
+ principalContactId: uuid2,
2129
+ organizationId: uuid2,
2130
+ projectId: uuid2,
2131
+ campaignId: uuid2,
2132
+ policyRevision: integer3(1),
2133
+ ledgerActionId: uuid2,
2134
+ actionKind: choice3("resonance_mandate", "resonance_operation", "resonance_diagnostics"),
2135
+ family,
2136
+ effectKey: text4(200, /^[a-zA-Z0-9._:-]+$/),
2137
+ payloadDigest: digest2,
2138
+ targetScope: object3({ accountBindingIds: list3(uuid2, 500, 1), sites: list3(site2, 500, 1), channelIds: list3(uuid2, 500, 1), preparedPlanId: uuid2 }),
2139
+ expectedRevision: integer3(1),
2140
+ expectedKillRevision: integer3(0),
2141
+ admittedAt: instant2,
2142
+ expiresAt: instant2,
2143
+ proof: delegation
2144
+ };
2145
+ var originalReview = object3({ reviewerContactId: uuid2, reviewedAt: instant2, approvalDigest: digest2 });
2146
+ var admission = refine4(union3(object3({ ...admissionFields, basis: literal3("delegated_agent") }), object3({
2147
+ ...admissionFields,
2148
+ basis: literal3("human_review_recovery"),
2149
+ executorKind: literal3("agent"),
2150
+ originalReview
2151
+ }), object3({
2152
+ ...admissionFields,
2153
+ basis: literal3("human_review_recovery"),
2154
+ executorKind: literal3("human"),
2155
+ tokenId: literal3(null),
2156
+ policyRevision: literal3(null),
2157
+ proof: literal3(null),
2158
+ originalReview
2159
+ })), (v, p) => {
2160
+ const sameActor = v.actorContactId.toLowerCase() === v.principalContactId.toLowerCase();
2161
+ if (v.basis === "human_review_recovery" && v.executorKind === "human" ? !sameActor : sameActor) fail4(p, "executor identity must match its native kind");
2162
+ for (const key of ["accountBindingIds", "sites", "channelIds"]) unique2(v.targetScope[key], p + ".targetScope." + key);
2163
+ if (utcMicros(v.expiresAt) <= utcMicros(v.admittedAt)) fail4(p + ".expiresAt", "must follow admission");
2164
+ if (v.proof) {
2165
+ for (const key of ["tokenId", "ledgerActionId"]) if (v[key].toLowerCase() !== v.proof[key].toLowerCase()) fail4(p + ".proof." + key, "must match original admission");
2166
+ if (v.policyRevision !== v.proof.policyRevision || v.payloadDigest !== v.proof.payloadDigest) fail4(p + ".proof", "must match original admission");
2167
+ }
2168
+ if (v.actionKind === "resonance_operation" && v.family !== "resonance.optimize" || v.actionKind === "resonance_diagnostics" && v.family !== "resonance.diagnostics" || v.actionKind === "resonance_mandate" && v.family !== "resonance.mandate" && v.family !== "resonance.operating_policy") fail4(p + ".family", "must match the registered action kind");
2169
+ if (v.basis === "human_review_recovery" && (v.actionKind !== "resonance_mandate" || v.family !== "resonance.operating_policy" || v.originalReview.reviewerContactId.toLowerCase() !== v.principalContactId.toLowerCase() || utcMicros(v.originalReview.reviewedAt) > utcMicros(v.admittedAt))) fail4(p + ".originalReview", "requires the preserved principal review for the original operating policy");
2170
+ });
2171
+ var parseDelegatedCommandAdmission = (v) => admission.read(v, "delegatedCommandAdmission");
2172
+ var DELEGATED_COMMAND_ADMISSION_JSON_SCHEMA = admission.schema;
2173
+ function parseDelegatedCommandClaimResponse(v, parseNativeAction) {
2174
+ if (typeof parseNativeAction !== "function") fail4("delegatedCommandClaimResponse.action", "requires the native Ledger parser");
2175
+ const response = object3({ action: field3({ type: "object" }, (value, p) => {
2176
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail4(p, "requires native Ledger row");
2177
+ return parseNativeAction(value);
2178
+ }), admission: nullable3(admission), replayed: bool2 }).read(v, "delegatedCommandClaimResponse");
2179
+ if (!response.replayed && !response.admission) fail4("delegatedCommandClaimResponse.admission", "a new claim requires native admission");
2180
+ return response;
2181
+ }
2182
+ function delegatedCommandFamilyForAction(kind, payload) {
2183
+ if (!payload || typeof payload !== "object" || Array.isArray(payload) || ![Object.prototype, null].includes(Object.getPrototypeOf(payload))) return null;
2184
+ const data = payload;
2185
+ const own = (key) => Object.getOwnPropertyDescriptor(data, key);
2186
+ if (kind === "resonance_mandate") {
2187
+ const base = own("operatingPolicyBase");
2188
+ return base ? "value" in base && base.value && typeof base.value === "object" && !Array.isArray(base.value) ? "resonance.operating_policy" : null : "resonance.mandate";
2189
+ }
2190
+ if (kind === "resonance_operation") {
2191
+ const operation = own("operation");
2192
+ return operation && "value" in operation && operation.value === "optimize" ? "resonance.optimize" : null;
2193
+ }
2194
+ return kind === "resonance_diagnostics" ? "resonance.diagnostics" : null;
2195
+ }
2196
+
2197
+ export { AGENT_EXECUTION_POLICY_JSON_SCHEMA, AGENT_EXECUTION_POLICY_UPDATE_JSON_SCHEMA, DELEGATED_COMMAND_ADMISSION_JSON_SCHEMA, DELEGATED_COMMAND_APPROVAL_JSON_SCHEMA, DELEGATED_COMMAND_AUTHORITY_SUMMARY_JSON_SCHEMA, DELEGATED_COMMAND_CLAIM_REQUEST_JSON_SCHEMA, DELEGATED_COMMAND_CLAIM_ROUTE, DELEGATED_COMMAND_FAMILIES, DELEGATED_COMMAND_PROOF_REFERENCE_JSON_SCHEMA, DELEGATED_COMMAND_REASON_CODES, DelegatedCommandValidationError, NATIVE_CAS_TIMESTAMP_JSON_SCHEMA, NativeCasTimestampValidationError, RESONANCE_OPERATING_POLICY_RECOVERY_REQUEST_JSON_SCHEMA, RESONANCE_OPERATING_POLICY_RECOVERY_ROUTE, delegatedCommandFamilyForAction, parseAgentExecutionPolicy, parseAgentExecutionPolicyUpdate, parseDelegatedCommandAdmission, parseDelegatedCommandApproval, parseDelegatedCommandAuthoritySummary, parseDelegatedCommandClaimRequest, parseDelegatedCommandClaimResponse, parseDelegatedCommandProofReference, parseNativeCasTimestamp, parseResonanceOperatingPolicyRecoveryRequest };