Independently review the record. Ignore claimed conclusions. Recompute with the engine; do not repair supplied facts by rewriting them. Preserve supplied values exactly. Null means unknown; do not invent a receipt, owner, date, source, rule, count or result. The source schema rejects unknown fields and missing nested members. A valid incomplete source record is importable. Use the embedded shared evaluator as the executable contract. PRE_TEST_PLAN uses LinkedIn-only and Mixed placement, campaign-arm CRM identity, collection feasibility, budget AND time bounds, owner, suitability, proposed controls and application check, buyer success/failure, coverage, maturity, stop and review rules. Historical delivery and applied receipts are not prerequisites. EXISTING_CAMPAIGN_REVIEW requires On/Off delivery, current publisher review, controls applied during the reviewed period, comparable scope/windows/attribution/units/denominator definitions, complete CRM evidence and a placement-to-lead source, join method, coverage counts and deduplication. Campaign-overall CRM cannot yield placement rates or continuation. Different numeric cohort sizes are allowed; different definitions are not. A scoped suitability veto or confirmed unavailable mandatory control wins without unrelated history. A conclusive mature failure can disable only after every required evidence gate passes. Complete first/replacement plans and complete immature observation are bounded. Otherwise missing or conflicting evidence holds. Mature executable success permits continuation with current controls. Never infer quality from CPC/CTR alone or move a supplied cutoff. Request IDs are req-lan:{origin}:{encodeURIComponent(exact field JSON Pointer)}. Stable entity IDs replace array indexes. Preserve external/native field-ID pairs and supplied request text; local findings are regenerated. Responsible owner falls back to campaign.owner, then null with an assignment flag. OUTPUT: If execution is available, run the embedded shared engine and return its exact result through toMarkdown. Without execution, return only a schema-valid supplied record inside one fenced JSON block under # Machine-readable record, preceded by Unexecuted draft. Do not fabricate an evaluation, hash or verified receipt. The browser accepts that source record and computes the decision. Preserve external findings and never call synthetic fixtures real client results. EXECUTABLE STANDALONE CONTRACT Save the following complete code as lan-engine.mjs in an execution environment. It includes the full schema, blank source, contract, evaluator and renderers; no other article file is required. Import evaluate, blank, ruleFingerprint and toMarkdown from that file. Use the supplied evaluation timestamp or actual current UTC time; never invent a timestamp. A buyer-confirmation fingerprint may be recorded only after the named buyer actually confirms the exact scope and rule. Unknown confirmation remains null. Return toMarkdown(evaluate(record, {asOf})) when executed. ```javascript /* One deterministic engine for CLI, browser, prompts and exports. No network calls. */ /* Generated; do not edit. */ const schema={"type": "object", "additionalProperties": false, "required": ["schema_version", "contract_version", "record_id", "revision", "fictional", "mode", "campaign", "publisher", "suitability", "controls", "sources", "pre_test", "existing", "replacement_pre_test", "external_requests", "history"], "properties": {"schema_version": {"const": "maestro.linkedin-audience-network.record.v1"}, "contract_version": {"const": "1.0.0"}, "record_id": {"type": ["string", "null"], "maxLength": 12000}, "revision": {"type": "integer", "minimum": 1, "maximum": 9007199254740991}, "fictional": {"type": "boolean"}, "mode": {"enum": ["PRE_TEST_PLAN", "EXISTING_CAMPAIGN_REVIEW", null]}, "campaign": {"type": "object", "additionalProperties": false, "required": ["name", "account_ref", "campaign_ref", "ad_set_refs", "owner", "measurement_owner", "suitability_owner", "currency", "timezone", "format", "eligibility", "eligibility_source_ref", "audience_ref", "offer_ref", "creative_ref", "destination_refs", "conversion_definition", "accepted_definition", "qualified_definition", "counting_unit"], "properties": {"name": {"type": ["string", "null"], "maxLength": 12000}, "account_ref": {"type": ["string", "null"], "maxLength": 12000}, "campaign_ref": {"type": ["string", "null"], "maxLength": 12000}, "ad_set_refs": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "owner": {"type": ["string", "null"], "maxLength": 12000}, "measurement_owner": {"type": ["string", "null"], "maxLength": 12000}, "suitability_owner": {"type": ["string", "null"], "maxLength": 12000}, "currency": {"type": ["string", "null"], "maxLength": 12000}, "timezone": {"type": ["string", "null"], "maxLength": 12000}, "format": {"enum": ["SINGLE_IMAGE", "CAROUSEL", "DOCUMENT", "VIDEO", null]}, "eligibility": {"enum": ["CONFIRMED", "NOT_ELIGIBLE", "UNKNOWN", null]}, "eligibility_source_ref": {"type": ["string", "null"], "maxLength": 12000}, "audience_ref": {"type": ["string", "null"], "maxLength": 12000}, "offer_ref": {"type": ["string", "null"], "maxLength": 12000}, "creative_ref": {"type": ["string", "null"], "maxLength": 12000}, "destination_refs": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "conversion_definition": {"type": ["string", "null"], "maxLength": 12000}, "accepted_definition": {"type": ["string", "null"], "maxLength": 12000}, "qualified_definition": {"type": ["string", "null"], "maxLength": 12000}, "counting_unit": {"enum": ["PERSON", "ACCOUNT", null]}}}, "publisher": {"type": "object", "additionalProperties": false, "required": ["source_ref", "retrieved_at", "reviewed_at", "reviewed_by", "valid_until", "next_review_at", "lag_acknowledged"], "properties": {"source_ref": {"type": ["string", "null"], "maxLength": 12000}, "retrieved_at": {"type": ["string", "null"], "maxLength": 12000}, "reviewed_at": {"type": ["string", "null"], "maxLength": 12000}, "reviewed_by": {"type": ["string", "null"], "maxLength": 12000}, "valid_until": {"type": ["string", "null"], "maxLength": 12000}, "next_review_at": {"type": ["string", "null"], "maxLength": 12000}, "lag_acknowledged": {"type": ["boolean", "null"]}}}, "suitability": {"type": "object", "additionalProperties": false, "required": ["requirements", "status", "source_ref", "reviewed_at", "owner", "reason", "reconsideration_condition"], "properties": {"requirements": {"type": "array", "items": {"type": "object", "additionalProperties": false, "required": ["requirement_id", "description"], "properties": {"requirement_id": {"type": ["string", "null"], "maxLength": 12000}, "description": {"type": ["string", "null"], "maxLength": 12000}}}, "maxItems": 200}, "status": {"enum": ["VETO", "CLEAR", "UNKNOWN", null]}, "source_ref": {"type": ["string", "null"], "maxLength": 12000}, "reviewed_at": {"type": ["string", "null"], "maxLength": 12000}, "owner": {"type": ["string", "null"], "maxLength": 12000}, "reason": {"type": ["string", "null"], "maxLength": 12000}, "reconsideration_condition": {"type": ["string", "null"], "maxLength": 12000}}}, "controls": {"type": "array", "items": {"$ref": "#/$defs/control"}, "maxItems": 200}, "sources": {"type": "array", "items": {"$ref": "#/$defs/source"}, "maxItems": 200}, "pre_test": {"$ref": "#/$defs/plan"}, "existing": {"type": "object", "additionalProperties": false, "required": ["platform_source_ref", "crm_source_ref", "on_linkedin", "audience_network", "join", "rules", "stop_observation", "campaign_overall_crm"], "properties": {"platform_source_ref": {"type": ["string", "null"], "maxLength": 12000}, "crm_source_ref": {"type": ["string", "null"], "maxLength": 12000}, "on_linkedin": {"$ref": "#/$defs/cohort"}, "audience_network": {"$ref": "#/$defs/cohort"}, "join": {"$ref": "#/$defs/join"}, "rules": {"$ref": "#/$defs/rules"}, "stop_observation": {"type": "object", "additionalProperties": false, "required": ["source_ref", "suitability_breach", "source_failure", "spend_minor"], "properties": {"source_ref": {"type": ["string", "null"], "maxLength": 12000}, "suitability_breach": {"type": ["boolean", "null"]}, "source_failure": {"type": ["boolean", "null"]}, "spend_minor": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}}}, "campaign_overall_crm": {"type": "object", "additionalProperties": false, "required": ["source_ref", "eligible_records", "accepted_records", "qualified_records", "limitation"], "properties": {"source_ref": {"type": ["string", "null"], "maxLength": 12000}, "eligible_records": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "accepted_records": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "qualified_records": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "limitation": {"type": ["string", "null"], "maxLength": 12000}}}}}, "replacement_pre_test": {"$ref": "#/$defs/plan"}, "external_requests": {"type": "array", "items": {"$ref": "#/$defs/request"}, "maxItems": 200}, "history": {"type": "array", "items": {"$ref": "#/$defs/history"}, "maxItems": 200}}, "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://maestrogtm.com/schemas/linkedin-audience-network-record-v1.json", "$defs": {"attribution": {"type": "object", "additionalProperties": false, "required": ["model", "click_days", "view_days"], "properties": {"model": {"type": ["string", "null"], "maxLength": 12000}, "click_days": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "view_days": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}}}, "window": {"type": "object", "additionalProperties": false, "required": ["delivery_start", "delivery_end", "outcome_cutoff", "collected_through"], "properties": {"delivery_start": {"type": ["string", "null"], "maxLength": 12000}, "delivery_end": {"type": ["string", "null"], "maxLength": 12000}, "outcome_cutoff": {"type": ["string", "null"], "maxLength": 12000}, "collected_through": {"type": ["string", "null"], "maxLength": 12000}}}, "source": {"type": "object", "additionalProperties": false, "required": ["source_id", "kind", "evidence_state", "reference", "observed_by", "captured_at", "account_ref", "campaign_ref", "ad_set_refs", "window", "attribution", "completeness", "carried_dimensions", "counting_unit", "population_ref", "audience_ref", "currency", "accepted_definition", "qualified_definition", "support_boundary"], "properties": {"source_id": {"type": ["string", "null"], "maxLength": 12000}, "kind": {"enum": ["ELIGIBILITY_CHECK", "PUBLISHER_SNAPSHOT", "SUITABILITY_REVIEW", "CONTROL_CAPABILITY", "CONTROL_APPLICATION_RECEIPT", "PLATFORM_ON_OFF_EXPORT", "CRM_EXPORT", "PLACEMENT_TO_LEAD_EVENT_EXPORT", "JOIN_AUDIT", "STOP_CHECK", null]}, "evidence_state": {"enum": ["OBSERVED", "PLANNED", "PENDING", "DENIED", "UNKNOWN", null]}, "reference": {"type": ["string", "null"], "maxLength": 12000}, "observed_by": {"type": ["string", "null"], "maxLength": 12000}, "captured_at": {"type": ["string", "null"], "maxLength": 12000}, "account_ref": {"type": ["string", "null"], "maxLength": 12000}, "campaign_ref": {"type": ["string", "null"], "maxLength": 12000}, "ad_set_refs": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "window": {"$ref": "#/$defs/window"}, "attribution": {"$ref": "#/$defs/attribution"}, "completeness": {"enum": ["COMPLETE_THROUGH_CUTOFF", "PARTIAL", "UNKNOWN", null]}, "carried_dimensions": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "counting_unit": {"enum": ["PERSON", "ACCOUNT", null]}, "population_ref": {"type": ["string", "null"], "maxLength": 12000}, "audience_ref": {"type": ["string", "null"], "maxLength": 12000}, "currency": {"type": ["string", "null"], "maxLength": 12000}, "accepted_definition": {"type": ["string", "null"], "maxLength": 12000}, "qualified_definition": {"type": ["string", "null"], "maxLength": 12000}, "support_boundary": {"type": ["string", "null"], "maxLength": 12000}}}, "receipt": {"type": "object", "additionalProperties": false, "required": ["application_state", "source_ref", "configuration_ref", "applied_at", "effective_from", "effective_until", "reviewed_at", "next_review_at"], "properties": {"application_state": {"enum": ["APPLIED", "NOT_APPLIED", "UNKNOWN", null]}, "source_ref": {"type": ["string", "null"], "maxLength": 12000}, "configuration_ref": {"type": ["string", "null"], "maxLength": 12000}, "applied_at": {"type": ["string", "null"], "maxLength": 12000}, "effective_from": {"type": ["string", "null"], "maxLength": 12000}, "effective_until": {"type": ["string", "null"], "maxLength": 12000}, "reviewed_at": {"type": ["string", "null"], "maxLength": 12000}, "next_review_at": {"type": ["string", "null"], "maxLength": 12000}}}, "control": {"type": "object", "additionalProperties": false, "required": ["control_id", "kind", "mandatory", "requirement_ids", "owner", "configuration_ref", "capability", "capability_source_ref", "planned_application_check", "receipt"], "properties": {"control_id": {"type": ["string", "null"], "maxLength": 12000}, "kind": {"enum": ["CATEGORY_EXCLUSION", "BLOCK_LIST", "ALLOW_LIST", "DOUBLEVERIFY_PROFILE", null]}, "mandatory": {"type": ["boolean", "null"]}, "requirement_ids": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "owner": {"type": ["string", "null"], "maxLength": 12000}, "configuration_ref": {"type": ["string", "null"], "maxLength": 12000}, "capability": {"enum": ["OPERABLE", "UNAVAILABLE", "UNKNOWN", null]}, "capability_source_ref": {"type": ["string", "null"], "maxLength": 12000}, "planned_application_check": {"type": ["string", "null"], "maxLength": 12000}, "receipt": {"$ref": "#/$defs/receipt"}}}, "predicate": {"type": "object", "additionalProperties": false, "required": ["metric", "cohort", "operator", "threshold"], "properties": {"metric": {"enum": ["QUALIFIED_RATE_BP", "ACCEPTED_RATE_BP", "QUALIFIED_COUNT", "ACCEPTED_COUNT", "CPC_MINOR", "CTR_BP", null]}, "cohort": {"enum": ["ON_LINKEDIN", "AUDIENCE_NETWORK", "LINKEDIN_ONLY", "MIXED_PLACEMENT", null]}, "operator": {"enum": ["LT", "LTE", "EQ", "GTE", "GT", null]}, "threshold": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}}}, "stopCondition": {"type": "object", "additionalProperties": false, "required": ["metric", "operator", "threshold"], "properties": {"metric": {"enum": ["SUITABILITY_BREACH", "SOURCE_FAILURE", "SPEND_MINOR", null]}, "operator": {"enum": ["EQ", "GTE", null]}, "threshold": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}}}, "rules": {"type": "object", "additionalProperties": false, "required": ["confirmed_fingerprint", "rule_id", "owner", "confirmed_at", "verbatim", "success", "failure_action", "reconsideration_condition", "minimum_join_coverage_bp", "minimum_joined_per_cohort", "observe_until", "review_cutoff", "next_review_at", "collection_schedule", "stop_owner", "stop_collection_method", "stop_conditions", "stop_action"], "properties": {"confirmed_fingerprint": {"type": ["string", "null"], "maxLength": 12000}, "rule_id": {"type": ["string", "null"], "maxLength": 12000}, "owner": {"type": ["string", "null"], "maxLength": 12000}, "confirmed_at": {"type": ["string", "null"], "maxLength": 12000}, "verbatim": {"type": ["string", "null"], "maxLength": 12000}, "success": {"type": "array", "items": {"$ref": "#/$defs/predicate"}, "maxItems": 200}, "failure_action": {"enum": ["DISABLE", "REDESIGN", null]}, "reconsideration_condition": {"type": ["string", "null"], "maxLength": 12000}, "minimum_join_coverage_bp": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "minimum_joined_per_cohort": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "observe_until": {"type": ["string", "null"], "maxLength": 12000}, "review_cutoff": {"type": ["string", "null"], "maxLength": 12000}, "next_review_at": {"type": ["string", "null"], "maxLength": 12000}, "collection_schedule": {"type": ["string", "null"], "maxLength": 12000}, "stop_owner": {"type": ["string", "null"], "maxLength": 12000}, "stop_collection_method": {"type": ["string", "null"], "maxLength": 12000}, "stop_conditions": {"type": "array", "items": {"$ref": "#/$defs/stopCondition"}, "maxItems": 200}, "stop_action": {"enum": ["PAUSE_AND_REVIEW", null]}}}, "arm": {"type": "object", "additionalProperties": false, "required": ["arm_id", "label", "audience_network_enabled", "campaign_ref", "budget_ceiling_minor"], "properties": {"arm_id": {"type": ["string", "null"], "maxLength": 12000}, "label": {"type": ["string", "null"], "maxLength": 12000}, "audience_network_enabled": {"type": ["boolean", "null"]}, "campaign_ref": {"type": ["string", "null"], "maxLength": 12000}, "budget_ceiling_minor": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}}}, "collection": {"type": "object", "additionalProperties": false, "required": ["source_kind", "method", "owner", "schedule", "feasibility_basis"], "properties": {"source_kind": {"enum": ["PLATFORM_ON_OFF_EXPORT", "CRM_EXPORT", "CONTROL_APPLICATION_RECEIPT", null]}, "method": {"type": ["string", "null"], "maxLength": 12000}, "owner": {"type": ["string", "null"], "maxLength": 12000}, "schedule": {"type": ["string", "null"], "maxLength": 12000}, "feasibility_basis": {"type": ["string", "null"], "maxLength": 12000}}}, "plan": {"type": "object", "additionalProperties": false, "required": ["plan_id", "owner", "hypothesis", "linkedin_only", "mixed_placement", "shared_audience_ref", "shared_offer_ref", "shared_creative_ref", "shared_destination_refs", "shared_conversion_definition", "attribution", "differences", "comparison_limitations", "crm_scope", "crm_arm_identity_method", "deduplication_method", "collection", "total_budget_ceiling_minor", "currency", "delivery_start", "delivery_end", "outcome_cutoff", "rules", "planned_application_check"], "properties": {"plan_id": {"type": ["string", "null"], "maxLength": 12000}, "owner": {"type": ["string", "null"], "maxLength": 12000}, "hypothesis": {"type": ["string", "null"], "maxLength": 12000}, "linkedin_only": {"$ref": "#/$defs/arm"}, "mixed_placement": {"$ref": "#/$defs/arm"}, "shared_audience_ref": {"type": ["string", "null"], "maxLength": 12000}, "shared_offer_ref": {"type": ["string", "null"], "maxLength": 12000}, "shared_creative_ref": {"type": ["string", "null"], "maxLength": 12000}, "shared_destination_refs": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "shared_conversion_definition": {"type": ["string", "null"], "maxLength": 12000}, "attribution": {"$ref": "#/$defs/attribution"}, "differences": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "comparison_limitations": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "crm_scope": {"enum": ["CAMPAIGN_ARM", null]}, "crm_arm_identity_method": {"type": ["string", "null"], "maxLength": 12000}, "deduplication_method": {"type": ["string", "null"], "maxLength": 12000}, "collection": {"type": "array", "items": {"$ref": "#/$defs/collection"}, "maxItems": 200}, "total_budget_ceiling_minor": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "currency": {"type": ["string", "null"], "maxLength": 12000}, "delivery_start": {"type": ["string", "null"], "maxLength": 12000}, "delivery_end": {"type": ["string", "null"], "maxLength": 12000}, "outcome_cutoff": {"type": ["string", "null"], "maxLength": 12000}, "rules": {"$ref": "#/$defs/rules"}, "planned_application_check": {"type": ["string", "null"], "maxLength": 12000}}}, "cohort": {"type": "object", "additionalProperties": false, "required": ["cohort_id", "placement", "account_ref", "campaign_ref", "ad_set_refs", "audience_ref", "window", "attribution", "currency", "counting_unit", "population_ref", "denominator_definition", "spend_minor", "impressions", "clicks", "landing_page_clicks", "platform_conversions", "eligible_records", "accepted_records", "qualified_records"], "properties": {"cohort_id": {"type": ["string", "null"], "maxLength": 12000}, "placement": {"enum": ["ON_LINKEDIN", "AUDIENCE_NETWORK", null]}, "account_ref": {"type": ["string", "null"], "maxLength": 12000}, "campaign_ref": {"type": ["string", "null"], "maxLength": 12000}, "ad_set_refs": {"type": "array", "items": {"type": ["string", "null"], "maxLength": 12000}, "maxItems": 200}, "audience_ref": {"type": ["string", "null"], "maxLength": 12000}, "window": {"$ref": "#/$defs/window"}, "attribution": {"$ref": "#/$defs/attribution"}, "currency": {"type": ["string", "null"], "maxLength": 12000}, "counting_unit": {"enum": ["PERSON", "ACCOUNT", null]}, "population_ref": {"type": ["string", "null"], "maxLength": 12000}, "denominator_definition": {"enum": ["JOINED_UNIQUE_RECORDS", null]}, "spend_minor": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "impressions": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "clicks": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "landing_page_clicks": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "platform_conversions": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "eligible_records": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "accepted_records": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "qualified_records": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}}}, "joinCounts": {"type": "object", "additionalProperties": false, "required": ["eligible", "joined", "unmatched", "ambiguous", "deduplicated"], "properties": {"eligible": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "joined": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "unmatched": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "ambiguous": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "deduplicated": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}}}, "join": {"type": "object", "additionalProperties": false, "required": ["placement_source_ref", "crm_source_ref", "audit_source_ref", "placement_carrier_field", "method_or_key", "cardinality", "eligible_population_ref", "deduplication_method", "deduplication_evidence_ref", "audited_by", "audited_at", "on_linkedin", "audience_network", "limitations"], "properties": {"placement_source_ref": {"type": ["string", "null"], "maxLength": 12000}, "crm_source_ref": {"type": ["string", "null"], "maxLength": 12000}, "audit_source_ref": {"type": ["string", "null"], "maxLength": 12000}, "placement_carrier_field": {"type": ["string", "null"], "maxLength": 12000}, "method_or_key": {"type": ["string", "null"], "maxLength": 12000}, "cardinality": {"enum": ["ONE_PLACEMENT_PER_UNIQUE_RECORD", null]}, "eligible_population_ref": {"type": ["string", "null"], "maxLength": 12000}, "deduplication_method": {"type": ["string", "null"], "maxLength": 12000}, "deduplication_evidence_ref": {"type": ["string", "null"], "maxLength": 12000}, "audited_by": {"type": ["string", "null"], "maxLength": 12000}, "audited_at": {"type": ["string", "null"], "maxLength": 12000}, "on_linkedin": {"$ref": "#/$defs/joinCounts"}, "audience_network": {"$ref": "#/$defs/joinCounts"}, "limitations": {"type": ["string", "null"], "maxLength": 12000}}}, "request": {"type": "object", "additionalProperties": false, "required": ["request_id", "origin", "field", "subject", "owning_system", "owner", "reason", "action", "completion_observation", "blocking_scope", "resolution_state", "resolution_ref"], "properties": {"request_id": {"type": ["string", "null"], "maxLength": 12000}, "origin": {"enum": ["external", "native", null]}, "field": {"type": ["string", "null"], "maxLength": 12000}, "subject": {"type": ["string", "null"], "maxLength": 12000}, "owning_system": {"type": ["string", "null"], "maxLength": 12000}, "owner": {"type": ["string", "null"], "maxLength": 12000}, "reason": {"type": ["string", "null"], "maxLength": 12000}, "action": {"type": ["string", "null"], "maxLength": 12000}, "completion_observation": {"type": ["string", "null"], "maxLength": 12000}, "blocking_scope": {"enum": ["ALL", "PRE_TEST_PLAN", "EXISTING_CAMPAIGN_REVIEW", null]}, "resolution_state": {"enum": ["OPEN", "RESOLVED", null]}, "resolution_ref": {"type": ["string", "null"], "maxLength": 12000}}}, "history": {"type": "object", "additionalProperties": false, "required": ["revision", "input_fingerprint", "decision", "saved_at", "reference"], "properties": {"revision": {"type": ["integer", "null"], "minimum": -9007199254740991, "maximum": 9007199254740991}, "input_fingerprint": {"type": ["string", "null"], "maxLength": 12000}, "decision": {"type": ["string", "null"], "maxLength": 12000}, "saved_at": {"type": ["string", "null"], "maxLength": 12000}, "reference": {"type": ["string", "null"], "maxLength": 12000}}}}, "title": "LinkedIn Audience Network supplied record"}; const contract={"contract_id": "maestro.linkedin-audience-network.decision.v1", "contract_version": "1.0.0", "schema_version": "maestro.linkedin-audience-network.record.v1", "schema_file": "audience-network-record.schema.json", "engine": "audience-network-evaluator.mjs", "runtime_dependencies": ["audience-network-data.mjs"], "as_of_policy": "Explicit UTC timestamp for replay; live evaluation uses current UTC. Never slide a cutoff.", "decision_precedence": ["SCOPED_SUITABILITY_VETO", "CONFIRMED_MANDATORY_CONTROL_UNAVAILABLE", "COMPLETE_MATURE_FAILURE_DISABLE", "APPLICABLE_MISSING_INVALID_OR_CONFLICTING_EVIDENCE", "COMPLETE_PRE_TEST", "COMPLETE_IMMATURE_OBSERVATION", "MATURE_SAMPLE_UNMET", "MATURE_FAILURE_REDESIGN", "MATURE_SUCCESS", "NON_EXECUTABLE_FALLBACK"], "existing_scope": "PLATFORM_PLACEMENT; continuation always requires placement-to-lead join. Campaign-overall CRM is separate context.", "pre_test_scope": "CAMPAIGN_ARM; LinkedIn-only versus Mixed placement. Budget AND time bounds are mandatory.", "request_id_rule": "req-lan:{origin}:{encodeURIComponent(exact field JSON Pointer)}; entity IDs replace array indexes. Subject cannot rename field.", "owner_rule": "Responsible owner, then campaign.owner, else null and owner_assignment_required true.", "import_rule": "Stage; validate every nested member; verify envelope hash; recompute at explicit as_of; commit once. Rejection preserves prior accepted state.", "number_rule": "Safe integers; money in minor units and rate thresholds in basis points. Unknown/zero denominator stays unavailable. Exact rational predicate comparison.", "fact_rule": "Preserve source facts and external/native request objects. Recompute local findings, metrics and decisions.", "evidence_boundary": "Local evaluation checks supplied record consistency; it does not authenticate LinkedIn or CRM exports. A transport hash is not evidence authentication. Synthetic fixtures prove evaluator behavior only.", "cutoff_rule": "Sources complete through collected_through. Mature review needs observe_until reached and final cutoff collected. Applied controls cover reviewed delivery; later application cannot rewrite history.", "outcomes": ["KEEP_DISABLED", "INSUFFICIENT_EVIDENCE", "BOUNDED_TEST", "CONTINUE_WITH_CONTROLS"], "metric_registry": {"QUALIFIED_RATE_BP": "qualified / joined unique records × 10000", "ACCEPTED_RATE_BP": "accepted / joined unique records × 10000", "QUALIFIED_COUNT": "qualified records", "ACCEPTED_COUNT": "accepted records", "CPC_MINOR": "spend_minor / clicks", "CTR_BP": "clicks / impressions × 10000"}}; const blank={"schema_version": "maestro.linkedin-audience-network.record.v1", "contract_version": "1.0.0", "record_id": "blank-review", "revision": 1, "fictional": false, "mode": null, "campaign": {"name": null, "account_ref": null, "campaign_ref": null, "ad_set_refs": [], "owner": null, "measurement_owner": null, "suitability_owner": null, "currency": null, "timezone": null, "format": null, "eligibility": null, "eligibility_source_ref": null, "audience_ref": null, "offer_ref": null, "creative_ref": null, "destination_refs": [], "conversion_definition": null, "accepted_definition": null, "qualified_definition": null, "counting_unit": null}, "publisher": {"source_ref": null, "retrieved_at": null, "reviewed_at": null, "reviewed_by": null, "valid_until": null, "next_review_at": null, "lag_acknowledged": null}, "suitability": {"requirements": [], "status": null, "source_ref": null, "reviewed_at": null, "owner": null, "reason": null, "reconsideration_condition": null}, "controls": [], "sources": [], "pre_test": {"plan_id": null, "owner": null, "hypothesis": null, "linkedin_only": {"arm_id": null, "label": null, "audience_network_enabled": null, "campaign_ref": null, "budget_ceiling_minor": null}, "mixed_placement": {"arm_id": null, "label": null, "audience_network_enabled": null, "campaign_ref": null, "budget_ceiling_minor": null}, "shared_audience_ref": null, "shared_offer_ref": null, "shared_creative_ref": null, "shared_destination_refs": [], "shared_conversion_definition": null, "attribution": {"model": null, "click_days": null, "view_days": null}, "differences": [], "comparison_limitations": [], "crm_scope": null, "crm_arm_identity_method": null, "deduplication_method": null, "collection": [], "total_budget_ceiling_minor": null, "currency": null, "delivery_start": null, "delivery_end": null, "outcome_cutoff": null, "rules": {"confirmed_fingerprint": null, "rule_id": null, "owner": null, "confirmed_at": null, "verbatim": null, "success": [], "failure_action": null, "reconsideration_condition": null, "minimum_join_coverage_bp": null, "minimum_joined_per_cohort": null, "observe_until": null, "review_cutoff": null, "next_review_at": null, "collection_schedule": null, "stop_owner": null, "stop_collection_method": null, "stop_conditions": [], "stop_action": null}, "planned_application_check": null}, "existing": {"platform_source_ref": null, "crm_source_ref": null, "on_linkedin": {"cohort_id": null, "placement": null, "account_ref": null, "campaign_ref": null, "ad_set_refs": [], "audience_ref": null, "window": {"delivery_start": null, "delivery_end": null, "outcome_cutoff": null, "collected_through": null}, "attribution": {"model": null, "click_days": null, "view_days": null}, "currency": null, "counting_unit": null, "population_ref": null, "denominator_definition": null, "spend_minor": null, "impressions": null, "clicks": null, "landing_page_clicks": null, "platform_conversions": null, "eligible_records": null, "accepted_records": null, "qualified_records": null}, "audience_network": {"cohort_id": null, "placement": null, "account_ref": null, "campaign_ref": null, "ad_set_refs": [], "audience_ref": null, "window": {"delivery_start": null, "delivery_end": null, "outcome_cutoff": null, "collected_through": null}, "attribution": {"model": null, "click_days": null, "view_days": null}, "currency": null, "counting_unit": null, "population_ref": null, "denominator_definition": null, "spend_minor": null, "impressions": null, "clicks": null, "landing_page_clicks": null, "platform_conversions": null, "eligible_records": null, "accepted_records": null, "qualified_records": null}, "join": {"placement_source_ref": null, "crm_source_ref": null, "audit_source_ref": null, "placement_carrier_field": null, "method_or_key": null, "cardinality": null, "eligible_population_ref": null, "deduplication_method": null, "deduplication_evidence_ref": null, "audited_by": null, "audited_at": null, "on_linkedin": {"eligible": null, "joined": null, "unmatched": null, "ambiguous": null, "deduplicated": null}, "audience_network": {"eligible": null, "joined": null, "unmatched": null, "ambiguous": null, "deduplicated": null}, "limitations": null}, "rules": {"confirmed_fingerprint": null, "rule_id": null, "owner": null, "confirmed_at": null, "verbatim": null, "success": [], "failure_action": null, "reconsideration_condition": null, "minimum_join_coverage_bp": null, "minimum_joined_per_cohort": null, "observe_until": null, "review_cutoff": null, "next_review_at": null, "collection_schedule": null, "stop_owner": null, "stop_collection_method": null, "stop_conditions": [], "stop_action": null}, "stop_observation": {"source_ref": null, "suitability_breach": null, "source_failure": null, "spend_minor": null}, "campaign_overall_crm": {"source_ref": null, "eligible_records": null, "accepted_records": null, "qualified_records": null, "limitation": null}}, "replacement_pre_test": {"plan_id": null, "owner": null, "hypothesis": null, "linkedin_only": {"arm_id": null, "label": null, "audience_network_enabled": null, "campaign_ref": null, "budget_ceiling_minor": null}, "mixed_placement": {"arm_id": null, "label": null, "audience_network_enabled": null, "campaign_ref": null, "budget_ceiling_minor": null}, "shared_audience_ref": null, "shared_offer_ref": null, "shared_creative_ref": null, "shared_destination_refs": [], "shared_conversion_definition": null, "attribution": {"model": null, "click_days": null, "view_days": null}, "differences": [], "comparison_limitations": [], "crm_scope": null, "crm_arm_identity_method": null, "deduplication_method": null, "collection": [], "total_budget_ceiling_minor": null, "currency": null, "delivery_start": null, "delivery_end": null, "outcome_cutoff": null, "rules": {"confirmed_fingerprint": null, "rule_id": null, "owner": null, "confirmed_at": null, "verbatim": null, "success": [], "failure_action": null, "reconsideration_condition": null, "minimum_join_coverage_bp": null, "minimum_joined_per_cohort": null, "observe_until": null, "review_cutoff": null, "next_review_at": null, "collection_schedule": null, "stop_owner": null, "stop_collection_method": null, "stop_conditions": [], "stop_action": null}, "planned_application_check": null}, "external_requests": [], "history": []}; export {schema, contract, blank}; export const ENGINE_VERSION = '1.0.0'; export const clone = value => JSON.parse(JSON.stringify(value)); export const canonical = value => value === null || typeof value !== 'object' ? JSON.stringify(value) : Array.isArray(value) ? '[' + value.map(canonical).join(',') + ']' : '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}'; const esc = x => String(x).replace(/~/g,'~0').replace(/\//g,'~1'); export const requestId = (field, origin='local') => `req-lan:${origin}:${encodeURIComponent(field)}`; const known = x => typeof x === 'string' && x.trim() !== '' && !/^(unknown|pending|tbd|to be determined|n\/a|na|not applicable|unavailable|denied|none|not supplied|not verified)$/i.test(x.trim()); const evidenceRef = x => known(x) && !/\s/.test(x) && (/^[a-z][a-z0-9+.-]*:\/\//i.test(x) || x.startsWith('/') || /^[\w./-]+\.(csv|json|pdf|png|jpg|txt|md)$/i.test(x)); const nat = x => Number.isSafeInteger(x) && x >= 0; const positive = x => Number.isSafeInteger(x) && x > 0; export const utc = x => typeof x === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(x) && Number.isFinite(Date.parse(x)) && new Date(x).toISOString().replace('.000Z','Z') === x; const now = () => new Date().toISOString().replace(/\.\d{3}Z$/,'Z'); const list = xs => Array.isArray(xs) && xs.length > 0 && xs.every(known) && new Set(xs).size === xs.length; const sameSet = (a,b) => canonical([...a].sort()) === canonical([...b].sort()); const same = (a,b) => canonical(a) === canonical(b); const label = path => path.split('/').filter(Boolean).join(' → ').replaceAll('_',' '); const findingOrder=(a,b)=>a.rank-b.rank||(a.fieldb.field?1:0); // SHA-256 over UTF-8, kept synchronous for identical browser/CLI evaluations. export function sha256(text) { const bytes = new TextEncoder().encode(text), n = Math.ceil((bytes.length + 9) / 64) * 64; const data = new Uint8Array(n); data.set(bytes); data[bytes.length] = 128; const dv = new DataView(data.buffer); dv.setUint32(n-8,Math.floor(bytes.length/536870912)); dv.setUint32(n-4,(bytes.length*8)>>>0); const k=[0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]; const h=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19], w=new Uint32Array(64), rr=(x,n)=>(x>>>n)|(x<<(32-n)); for(let block=0;block>>3))+w[i-7]+(rr(b,17)^rr(b,19)^(b>>>10)))>>>0;} let [a,b,c,d,e,f,g,hh]=h; for(let i=0;i<64;i++){const t1=(hh+(rr(e,6)^rr(e,11)^rr(e,25))+((e&f)^((~e)&g))+k[i]+w[i])>>>0,t2=((rr(a,2)^rr(a,13)^rr(a,22))+((a&b)^(a&c)^(b&c)))>>>0;hh=g;g=f;f=e;e=(d+t1)>>>0;d=c;c=b;b=a;a=(t1+t2)>>>0;} [a,b,c,d,e,f,g,hh].forEach((v,i)=>h[i]=(h[i]+v)>>>0); } return h.map(x=>x.toString(16).padStart(8,'0')).join(''); } export function ruleFingerprint(rules,campaign){const {confirmed_fingerprint,...definition}=rules;return sha256(canonical({campaign,rules:definition}));} export function validateShape(value, spec=schema, path='') { if(spec.$ref) return validateShape(value,schema.$defs[spec.$ref.split('/').pop()],path); const errors=[]; if('const' in spec && value !== spec.const) errors.push(`${path}: wrong constant`); if(spec.enum && !spec.enum.includes(value)) errors.push(`${path}: invalid enum`); const actual=value===null?'null':Array.isArray(value)?'array':typeof value==='number'&&Number.isSafeInteger(value)?'integer':typeof value; const types=Array.isArray(spec.type)?spec.type:[spec.type]; if(spec.type && !types.includes(actual)){errors.push(`${path}: expected ${types.join('|')}, received ${actual}`);return errors;} if(actual==='object'){ for(const k of spec.required||[])if(!Object.hasOwn(value,k))errors.push(`${path}/${esc(k)}: required member absent`); for(const k of Object.keys(value)){if(!spec.properties?.[k])errors.push(`${path}/${esc(k)}: unknown member`);else errors.push(...validateShape(value[k],spec.properties[k],`${path}/${esc(k)}`));} } if(actual==='array'){if(value.length>(spec.maxItems??Infinity))errors.push(`${path}: too many items`);value.forEach((v,i)=>errors.push(...validateShape(v,spec.items,`${path}/${i}`)));} if(actual==='string' && [...value].length>(spec.maxLength??Infinity))errors.push(`${path}: string exceeds cap`); if(actual==='integer'&&(value<(spec.minimum??-Infinity)||value>(spec.maximum??Infinity)))errors.push(`${path}: integer outside schema bounds`); return errors; } function assertShape(record){const errors=validateShape(record);if(errors.length)throw new Error('INVALID_RECORD: '+errors.join('; '));} function compare(n,d,op,t){const left=BigInt(n),right=BigInt(t)*BigInt(d);return ({LT:left=right,GT:left>right})[op];} function fraction(n,d,scale=1){return nat(n)&&positive(d)?{numerator:n,denominator:d,scale,value:n/d*scale}:null;} export function evaluate(record, options={}) { assertShape(record); const r=clone(record), asOf=typeof options==='string'?options:(options.asOf||now()); if(!utc(asOf))throw new Error('INVALID_AS_OF: use an exact UTC timestamp with second precision.'); const c=r.campaign,s=r.suitability,p=r.publisher,e=r.existing; const findings=new Map(), sources=new Map(); const add=(field,code,reason,action,rank=50,owner=null)=>{ const id=requestId(field);if(findings.has(id))return false; const actualOwner=known(owner)?owner:known(c.owner)?c.owner:null; findings.set(id,{request_id:id,origin:'local',field,subject:label(field),owning_system:field.startsWith('/existing')?'Measurement':field.startsWith('/controls')||field.startsWith('/publisher')||field.startsWith('/suitability')?'Publisher controls':'Campaign planning',owner:actualOwner,owner_assignment_required:actualOwner===null,reason_code:code,reason,action,completion_observation:'The named field has current, scoped evidence and passes reevaluation.',blocking_scope:r.mode||'ALL',resolution_state:'OPEN',resolution_ref:null,rank});return false; }; const need=(ok,path,code,reason,action,rank=50,owner=null)=>ok||add(path,code,reason,action,rank,owner); const txt=(value,path,rank=50,owner=null)=>need(known(value),path,'REQUIRED_FIELD',`${label(path)} is missing or unresolved.`,`Supply ${label(path)}.`,rank,owner); const date=(value,path,rank=50)=>need(utc(value),path,'INVALID_OR_MISSING_DATE',`${label(path)} needs a real UTC date and time.`,`Enter a valid UTC timestamp for ${label(path)}.`,rank); const validPast=(value,path,rank=50)=>date(value,path,rank)&&need(value<=asOf,path,'FUTURE_EVIDENCE',`${label(path)} is after the evaluation time.`,`Supply evidence observed on or before ${asOf}.`,rank); for(const src of r.sources){if(!known(src.source_id)||sources.has(src.source_id))add('/sources','SOURCE_IDENTITY_INVALID','Source IDs are blank or duplicated.','Assign one distinct stable ID to every source.',5);else sources.set(src.source_id,src);} const proof=(id,kind,path,rank=50,data=false)=>{ const src=sources.get(id); if(!src)return add(path,'SOURCE_MISSING',`No source resolves for ${id??'Unknown'}.`,`Supply a ${kind} source and reference its exact source ID.`,rank); let ok=true; const fail=(code,reason,action)=>{ok=false;add(path,code,reason,action,rank);}; if(src.kind!==kind)fail('WRONG_SOURCE_KIND',`Expected ${kind}; supplied ${src.kind} from ${id}.`,`Supply ${kind} evidence instead of ${src.kind} (${id}).`); if(src.evidence_state!=='OBSERVED'||!evidenceRef(src.reference)||!known(src.observed_by)||!known(src.support_boundary)||!list(src.carried_dimensions))fail('SOURCE_NOT_OBSERVED',`Source ${id} is not an affirmative observed receipt with reference, observer, complete dimensions and boundary.`,`Supply observed ${kind} evidence; planned, pending and denied evidence cannot pass.`); if(!r.fictional&&src.reference?.startsWith('synthetic://'))fail('SYNTHETIC_SOURCE_IN_REAL_RECORD',`Source ${id} is synthetic but the record is not labeled fictional.`,`Keep this example labeled fictional or replace its sources with actual scoped evidence.`); if(!utc(src.captured_at)||src.captured_at>asOf)fail('SOURCE_DATE_INVALID',`Source ${id} has an invalid or future observation time.`,`Record the actual observed time, on or before ${asOf}.`); if(src.account_ref!==c.account_ref||src.campaign_ref!==c.campaign_ref||!list(src.ad_set_refs)||!sameSet(src.ad_set_refs,c.ad_set_refs))fail('SOURCE_SCOPE_MISMATCH',`Expected ${c.account_ref}/${c.campaign_ref}/${c.ad_set_refs.join(', ')}; supplied ${src.account_ref}/${src.campaign_ref}/${src.ad_set_refs.join(', ')}.`,`Collect ${id} for the exact expected account, campaign and ad sets.`); if(data){ if(src.completeness!=='COMPLETE_THROUGH_CUTOFF')fail('SOURCE_INCOMPLETE',`Source ${id} is ${src.completeness??'Unknown'}.`,`Collect the complete source through the declared collected-through cutoff.`); const platform=kind==='PLATFORM_ON_OFF_EXPORT'; const windowMatches=platform?src.window.delivery_start===e.on_linkedin.window.delivery_start&&src.window.delivery_end===e.on_linkedin.window.delivery_end&&utc(src.window.collected_through)&&src.window.collected_through>=src.window.delivery_end&&src.window.collected_through<=asOf:same(src.window,e.on_linkedin.window); if(!windowMatches||!same(src.attribution,e.on_linkedin.attribution)||(!platform&&(src.counting_unit!==c.counting_unit||src.population_ref!==e.on_linkedin.population_ref)))fail('SOURCE_WINDOW_MISMATCH',`Source ${id} does not match the reviewed windows, attribution or applicable unit/population.`,`Collect ${id} with the exact reviewed delivery scope and its applicable outcome definitions.`); if(src.audience_ref!==c.audience_ref||src.currency!==c.currency||(!platform&&(src.accepted_definition!==c.accepted_definition||src.qualified_definition!==c.qualified_definition)))fail('SOURCE_DEFINITION_MISMATCH',`Source ${id} does not match the reviewed audience, currency or applicable CRM definitions.`,`Collect ${id} for the exact audience, currency and applicable outcome definitions.`); if(!utc(src.window.collected_through)||!utc(src.captured_at)||src.captured_at{ const local=[...findings.values()].sort(findingOrder).map(({rank,...x})=>x); const external=r.external_requests.filter(x=>(x.blocking_scope==='ALL'||x.blocking_scope===r.mode)&&x.resolution_state==='OPEN'); const requests=[...local,...external]; const primary=requests[0]; const action=extra.next_action||(primary?`${primary.owner||'Assign an owner'}: ${primary.action}`:'No collection request is open.'); return {schema_version:r.schema_version,contract_id:contract.contract_id,contract_version:ENGINE_VERSION,record_id:r.record_id,mode:r.mode,evaluated_as_of:asOf,input_fingerprint:sha256(canonical(r)),decision,reason_code:code,reason,placement_crm_state:'UNKNOWN',publisher_control_state:'UNVERIFIED',placement_evidence_state:'UNVERIFIED',metrics:{on_linkedin:null,audience_network:null},rule_result:'UNKNOWN',maturity_result:'UNKNOWN',bounded_test_kind:null,observe_until:null,review_cutoff:null,next_review_at:null,claim_boundary:contract.evidence_boundary,provenance_summary:`${r.fictional?'Synthetic example. ':''}Evaluated ${asOf}. ${r.sources.length} supplied source records; external truth is not authenticated.`,requests,next_action:action,...extra,input:r}; }; // A scoped veto is deliberately independent of unrelated CRM and plan fields. const vetoScope=[c.name,c.account_ref,c.campaign_ref,c.owner,s.owner,s.reason,s.reconsideration_condition].every(known)&&list(c.ad_set_refs)&&s.requirements.length>0&&s.requirements.every(x=>known(x.requirement_id)&&known(x.description))&&utc(s.reviewed_at)&&s.reviewed_at<=asOf; if(s.status==='VETO'&&vetoScope&&proof(s.source_ref,'SUITABILITY_REVIEW','/suitability/source_ref',2))return finish('KEEP_DISABLED','SUITABILITY_VETO',s.reason,{controlling_evidence_refs:[s.source_ref],next_action:`Keep Audience Network disabled. Reconsider only when: ${s.reconsideration_condition}`}); for(const control of r.controls){ if(control.mandatory===true&&control.capability==='UNAVAILABLE'&&[c.name,c.account_ref,c.campaign_ref,c.owner,control.control_id,control.owner,control.configuration_ref,s.reconsideration_condition].every(known)&&list(control.requirement_ids)&&control.requirement_ids.every(id=>s.requirements.some(x=>x.requirement_id===id))&&proof(control.capability_source_ref,'CONTROL_CAPABILITY',`/controls/${esc(control.control_id)}/capability_source_ref`,3))return finish('KEEP_DISABLED','MANDATORY_CONTROL_UNAVAILABLE',`Mandatory control ${control.control_id} is confirmed unavailable.`,{controlling_evidence_refs:[control.capability_source_ref],next_action:`Keep Audience Network disabled. Reconsider only when: ${s.reconsideration_condition}`}); } need(r.mode!==null,'/mode','MODE_REQUIRED','Choose the evidence mode.','Choose PRE_TEST_PLAN or EXISTING_CAMPAIGN_REVIEW.',0); for(const key of ['name','account_ref','campaign_ref','owner'])txt(c[key],`/campaign/${key}`,key==='owner'?2:1); if([...findings.values()].some(x=>x.rank<=2)) {const f=[...findings.values()].sort(findingOrder)[0];return finish('INSUFFICIENT_EVIDENCE',f.reason_code,f.reason);} need(known(r.record_id)&&positive(r.revision),'/record_id','RECORD_IDENTITY_INVALID','Record identity or revision is invalid.','Supply a stable record ID and positive revision.',4); for(const key of ['measurement_owner','suitability_owner','currency','timezone','format','audience_ref','offer_ref','creative_ref','conversion_definition','accepted_definition','qualified_definition','counting_unit'])txt(c[key],`/campaign/${key}`,10); for(const key of ['ad_set_refs','destination_refs'])need(list(c[key]),`/campaign/${key}`,'REQUIRED_LIST',`${key} needs distinct meaningful members.`,`Supply every ${key} member.`,10); if(known(c.timezone)){try{new Intl.DateTimeFormat('en',{timeZone:c.timezone});}catch{add('/campaign/timezone','INVALID_TIMEZONE','Timezone is not a valid IANA zone.','Supply an IANA timezone.',10);}} need(/^[A-Z]{3}$/.test(c.currency||''),'/campaign/currency','INVALID_CURRENCY','Currency needs a three-letter code.','Supply the campaign currency code.',10); for(const dest of c.destination_refs){try{const u=new URL(dest);if(!['http:','https:'].includes(u.protocol)||/\s/.test(dest))throw Error();}catch{add('/campaign/destination_refs','INVALID_DESTINATION','A destination is not a valid HTTP(S) URL.','Supply valid campaign destination URLs.',10);}} need(c.eligibility==='CONFIRMED','/campaign/eligibility','ELIGIBILITY_UNCONFIRMED','The exact format/setup is not confirmed eligible.','Verify eligibility for this account, format and setup.',11); proof(c.eligibility_source_ref,'ELIGIBILITY_CHECK','/campaign/eligibility_source_ref',11); need(s.status==='CLEAR','/suitability/status','SUITABILITY_UNRESOLVED','Suitability is unknown or a claimed veto lacks support.','Complete a scoped suitability review and record its supported decision.',12,s.owner); need(s.requirements.length>0&&s.requirements.every(x=>known(x.requirement_id)&&known(x.description))&&new Set(s.requirements.map(x=>x.requirement_id)).size===s.requirements.length,'/suitability/requirements','SUITABILITY_REQUIREMENTS_MISSING','Suitability requirements are absent or invalid.','Define distinct suitability requirement IDs and descriptions.',12,s.owner); for(const key of ['owner','reason','reconsideration_condition'])txt(s[key],`/suitability/${key}`,12,s.owner); validPast(s.reviewed_at,'/suitability/reviewed_at',12);proof(s.source_ref,'SUITABILITY_REVIEW','/suitability/source_ref',12); proof(p.source_ref,'PUBLISHER_SNAPSHOT','/publisher/source_ref',13); for(const key of ['retrieved_at','reviewed_at'])validPast(p[key],`/publisher/${key}`,13); txt(p.reviewed_by,'/publisher/reviewed_by',13,c.suitability_owner); need(utc(p.valid_until)&&p.valid_until>asOf,'/publisher/valid_until','PUBLISHER_SNAPSHOT_STALE','Publisher snapshot is undated or outside the buyer-owned validity cutoff.','Collect and review a current publisher snapshot; record its fixed validity cutoff.',13,c.suitability_owner); need(utc(p.next_review_at)&&p.next_review_at>asOf&&utc(p.valid_until)&&p.next_review_at<=p.valid_until,'/publisher/next_review_at','PUBLISHER_REVIEW_DUE','The next publisher review is missing, due or later than snapshot validity.','Set the next publisher review on or before the validity cutoff.',13,c.suitability_owner); need(p.lag_acknowledged===true,'/publisher/lag_acknowledged','PUBLISHER_LAG_UNACKNOWLEDGED','The publisher-list lag limitation has not been recorded.','Acknowledge that publisher additions/removals may precede the downloaded list.',13); if(utc(p.retrieved_at)&&utc(p.reviewed_at))need(p.reviewed_at>=p.retrieved_at,'/publisher/reviewed_at','PUBLISHER_DATE_CONFLICT','Publisher review predates retrieval.','Supply the actual review date for this snapshot.',13); need(r.controls.length>0,'/controls','CONTROLS_REQUIRED','Required publisher controls are not documented.','List the planned controls and their owners.',14,c.suitability_owner); need(r.controls.some(x=>x.mandatory===true),'/controls','MANDATORY_CONTROL_REQUIRED','The record does not identify the mandatory controls for its suitability requirements.','Identify at least one required control; optional proposals remain separate.',14,c.suitability_owner); need(new Set(r.controls.map(x=>x.control_id)).size===r.controls.length,'/controls','CONTROL_IDENTITY_INVALID','Control IDs are duplicated.','Use distinct stable control IDs.',14); for(const control of r.controls){ const path=`/controls/${esc(control.control_id??'unassigned')}`; if(control.mandatory===false&&control.receipt.application_state!=='APPLIED'){ for(const key of ['control_id','kind'])txt(control[key],`${path}/${key}`,14,control.owner); continue; // Optional proposed controls cannot block the selected required controls. } for(const key of ['control_id','kind','owner','configuration_ref','planned_application_check'])txt(control[key],`${path}/${key}`,14,control.owner); need(typeof control.mandatory==='boolean',`${path}/mandatory`,'MANDATORY_STATE_UNKNOWN','Control requirement status is unknown.','Record whether this control is mandatory.',14); need(list(control.requirement_ids)&&control.requirement_ids.every(id=>s.requirements.some(x=>x.requirement_id===id)),`${path}/requirement_ids`,'CONTROL_REQUIREMENT_MISMATCH','The control does not resolve to documented requirements.','Link the control to its exact suitability requirement IDs.',14); need(control.capability==='OPERABLE',`${path}/capability`,'CONTROL_CAPABILITY_UNRESOLVED','The control is not confirmed operable.','Document its account-specific capability and evidence.',14); proof(control.capability_source_ref,'CONTROL_CAPABILITY',`${path}/capability_source_ref`,14); if(r.mode==='EXISTING_CAMPAIGN_REVIEW'){ const receipt=control.receipt;proof(receipt.source_ref,'CONTROL_APPLICATION_RECEIPT',`${path}/receipt/source_ref`,15); need(receipt.application_state==='APPLIED',`${path}/receipt/application_state`,'CONTROL_NOT_APPLIED','An observed source does not establish that the control was applied.','Supply an affirmative APPLIED receipt; a negative, pending or unknown application cannot pass.',15); need(receipt.configuration_ref===control.configuration_ref,`${path}/receipt/configuration_ref`,'CONTROL_CONFIGURATION_CHANGED','Applied receipt does not match the claimed configuration.','Supply a receipt for the exact current configuration.',15); for(const key of ['applied_at','reviewed_at'])validPast(receipt[key],`${path}/receipt/${key}`,15); need(utc(receipt.effective_from)&&utc(receipt.effective_until)&&utc(e.on_linkedin.window.delivery_start)&&utc(e.on_linkedin.window.delivery_end)&&receipt.effective_from<=e.on_linkedin.window.delivery_start&&receipt.effective_until>=e.on_linkedin.window.delivery_end&&utc(receipt.applied_at)&&receipt.applied_at<=receipt.effective_from,`${path}/receipt/effective_from`,'CONTROL_PERIOD_UNPROVEN','The applied receipt does not cover the reviewed delivery period.','Preserve the old period; apply controls and start a new evidenced review period.',15); need(utc(receipt.next_review_at)&&receipt.next_review_at>asOf,`${path}/receipt/next_review_at`,'CONTROL_REVIEW_DUE','The control review is missing or due.','Review the control and set its next review cutoff.',15); need(utc(receipt.effective_until)&&receipt.effective_until>asOf&&utc(receipt.next_review_at)&&receipt.next_review_at<=receipt.effective_until,`${path}/receipt/effective_until`,'CONTROL_NO_LONGER_EFFECTIVE','The control is expired or will expire before its next review.','Verify the active control period and review it before expiry.',15); if(utc(receipt.applied_at)&&utc(receipt.reviewed_at))need(receipt.reviewed_at>=receipt.applied_at,`${path}/receipt/reviewed_at`,'CONTROL_REVIEW_BEFORE_APPLICATION','The control review predates application.','Supply the actual post-application review date.',15); } } for(const req of r.external_requests){ need(known(req.field)&&req.field.startsWith('/')&&req.request_id===requestId(req.field,req.origin),'/external_requests','EXTERNAL_REQUEST_ID_INVALID','An external/native request field-ID pair is not canonical.','Use the exact mechanical field-ID rule; preserve supplied context.',16); for(const key of ['origin','subject','owning_system','reason','action','completion_observation','blocking_scope','resolution_state'])txt(req[key],`/external_requests/${esc(req.request_id??'unassigned')}/${key}`,16); if(req.resolution_state==='RESOLVED')need(evidenceRef(req.resolution_ref),`/external_requests/${esc(req.request_id)}/resolution_ref`,'EXTERNAL_RESOLUTION_UNPROVEN','External request claims resolution without a receipt.','Supply its reviewed resolution reference or leave it open.',16); } const attribution=(a,path)=>{txt(a.model,path+'/model',20);for(const key of ['click_days','view_days'])need(nat(a[key]),path+'/'+key,'ATTRIBUTION_INVALID','Attribution windows need explicit nonnegative integer days.','Supply the exact attribution settings.',20);}; const ruleCheck=(rules,path,pre,outcomeCutoff)=>{ const start=findings.size; for(const key of ['rule_id','owner','verbatim','failure_action','reconsideration_condition','collection_schedule','stop_owner','stop_collection_method','stop_action'])txt(rules[key],path+'/'+key,30,rules.owner); validPast(rules.confirmed_at,path+'/confirmed_at',30); need(rules.confirmed_fingerprint===ruleFingerprint(rules,c),path+'/confirmed_fingerprint','BUYER_RULE_CONFIRMATION_STALE','The supplied confirmation does not bind the current campaign and rule definition.','Have the named buyer review the current rule and campaign scope, then record their confirmation fingerprint.',30,rules.owner); need(nat(rules.minimum_join_coverage_bp)&&rules.minimum_join_coverage_bp<=10000,path+'/minimum_join_coverage_bp','COVERAGE_RULE_INVALID','A buyer-owned coverage threshold between 0 and 10000 basis points is required.','Supply the coverage rule without inventing a benchmark.',30); need(positive(rules.minimum_joined_per_cohort),path+'/minimum_joined_per_cohort','MATURITY_RULE_INVALID','A positive minimum joined sample per cohort is required.','Supply the buyer-owned minimum sample.',30); for(const key of ['observe_until','review_cutoff','next_review_at'])date(rules[key],path+'/'+key,30); if(utc(rules.observe_until)&&utc(outcomeCutoff))need(rules.observe_until>=outcomeCutoff,path+'/observe_until','MATURITY_BEFORE_OUTCOMES','Maturity predates the declared outcome cutoff.','Set an observation rule that includes the outcome window.',30); if(utc(rules.review_cutoff)&&utc(rules.observe_until))need(rules.review_cutoff>=rules.observe_until,path+'/review_cutoff','REVIEW_BEFORE_MATURITY','Review cutoff precedes maturity.','Set a fixed review cutoff on or after maturity.',30); need(utc(rules.next_review_at)&&rules.next_review_at>asOf,path+'/next_review_at','NEXT_REVIEW_REQUIRED','Next review is missing or due.','Set the next fixed review date.',30); need(rules.success.length>0,path+'/success','SUCCESS_RULE_MISSING','An executable buyer-owned success rule is absent.','Supply metric, cohort, operator and threshold predicates.',30); const allowed=pre?['LINKEDIN_ONLY','MIXED_PLACEMENT']:['ON_LINKEDIN','AUDIENCE_NETWORK']; for(const pred of rules.success)need(allowed.includes(pred.cohort)&&known(pred.metric)&&known(pred.operator)&&nat(pred.threshold)&&(pred.metric.endsWith('_BP')?pred.threshold<=10000:true),path+'/success','SUCCESS_RULE_INVALID','A predicate has an unsupported scope, metric, operator or threshold.','Use the declared metric registry and this mode’s cohort identities.',30); need(rules.success.some(x=>x.cohort===(pre?'MIXED_PLACEMENT':'AUDIENCE_NETWORK')&&/^(QUALIFIED|ACCEPTED)_/.test(x.metric||'')),path+'/success','CRM_SUCCESS_RULE_REQUIRED','CPC, CTR or the baseline cohort alone cannot establish Audience Network quality.','Supply an accepted or qualified outcome predicate for the mixed arm or Audience Network cohort.',30); need(rules.stop_conditions.length>0&&rules.stop_conditions.every(x=>known(x.metric)&&known(x.operator)&&nat(x.threshold)&&(x.metric==='SPEND_MINOR'?positive(x.threshold):x.operator==='EQ'&&[0,1].includes(x.threshold))),path+'/stop_conditions','STOP_RULE_INVALID','A typed executable early stop rule is required.','Supply suitability/source/spend stop conditions and thresholds.',31); return findings.size===start; }; const planCheck=(plan,path)=>{ const start=findings.size; if(!known(plan.plan_id)&&!known(plan.hypothesis)&&!known(plan.linkedin_only.arm_id)&&!known(plan.mixed_placement.arm_id))return add(path,'PLAN_REQUIRED','The bounded test plan has not been supplied.','Supply the named arms, shared settings, collection, budget and time bounds, controls, buyer-owned rules and review cutoff.',20,plan.owner); for(const key of ['plan_id','owner','hypothesis','crm_arm_identity_method','deduplication_method','planned_application_check'])txt(plan[key],path+'/'+key,20,plan.owner); need(plan.crm_scope==='CAMPAIGN_ARM',path+'/crm_scope','PLAN_CRM_SCOPE_INVALID','Pre-test CRM measurement must retain campaign-arm scope.','Use CAMPAIGN_ARM; do not promise placement CRM without a join.',20); for(const [key,expected,on] of [['linkedin_only','LinkedIn-only',false],['mixed_placement','Mixed placement',true]]){ const arm=plan[key];txt(arm.arm_id,`${path}/${key}/arm_id`,20);txt(arm.campaign_ref,`${path}/${key}/campaign_ref`,20); need(arm.label===expected&&arm.audience_network_enabled===on,`${path}/${key}/label`,'ARM_LABEL_INVALID',`This arm must be ${expected} with Audience Network ${on?'enabled':'disabled'}.`,`Use exact label ${expected}; never Audience Network-only.`,20); need(positive(arm.budget_ceiling_minor),`${path}/${key}/budget_ceiling_minor`,'BUDGET_BOUND_REQUIRED','Each selected arm needs a positive fixed budget ceiling.','Supply a positive currency-minor-unit ceiling.',20); } need(plan.linkedin_only.arm_id!==plan.mixed_placement.arm_id&&plan.linkedin_only.campaign_ref!==plan.mixed_placement.campaign_ref,path+'/mixed_placement/campaign_ref','ARM_IDENTITY_CONFLICT','The two arms share an identity.','Assign distinct arm and campaign identities.',20); need(positive(plan.total_budget_ceiling_minor)&&nat(plan.linkedin_only.budget_ceiling_minor)&&nat(plan.mixed_placement.budget_ceiling_minor)&&plan.linkedin_only.budget_ceiling_minor+plan.mixed_placement.budget_ceiling_minor<=plan.total_budget_ceiling_minor,path+'/total_budget_ceiling_minor','BUDGET_BOUND_REQUIRED','Total budget is absent or does not cover the arm ceilings.','Supply a positive reconciled total budget ceiling.',20); need(plan.currency===c.currency,path+'/currency','CURRENCY_MISMATCH','Plan currency differs from campaign currency.','Use the same currency for every budget.',20); for(const [pk,ck] of [['shared_audience_ref','audience_ref'],['shared_offer_ref','offer_ref'],['shared_creative_ref','creative_ref'],['shared_destination_refs','destination_refs'],['shared_conversion_definition','conversion_definition']])need(same(plan[pk],c[ck]),path+'/'+pk,'PLAN_SCOPE_MISMATCH',`${pk} differs from the campaign scope.`,`Record the shared ${ck} and document material differences.`,20); need(list(plan.differences)&&list(plan.comparison_limitations),path+'/differences','COMPARISON_LIMITATIONS_REQUIRED','Arm differences or comparison limits are not documented.','Name all differences and the limit of campaign-arm attribution.',20); attribution(plan.attribution,path+'/attribution'); for(const key of ['delivery_start','delivery_end','outcome_cutoff'])date(plan[key],path+'/'+key,20); need(utc(plan.delivery_start)&&utc(plan.delivery_end)&&utc(plan.outcome_cutoff)&&plan.delivery_start>=asOf&&plan.delivery_end>plan.delivery_start&&plan.outcome_cutoff>=plan.delivery_end,path+'/delivery_end','TIME_BOUND_INVALID','Both a future fixed start/end and an ordered outcome cutoff are required.','Supply a bounded future test schedule; stop at the first time or spend limit.',20); for(const kind of ['PLATFORM_ON_OFF_EXPORT','CRM_EXPORT','CONTROL_APPLICATION_RECEIPT'])need(plan.collection.some(x=>x.source_kind===kind&&['method','owner','schedule','feasibility_basis'].every(k=>known(x[k]))),path+'/collection/'+kind,'COLLECTION_METHOD_REQUIRED',`Collection for ${kind} is missing or unproven.`,`Name the method, owner, schedule and feasibility basis for ${kind}.`,20); need(plan.collection.every(x=>known(x.source_kind)&&['method','owner','schedule','feasibility_basis'].every(k=>known(x[k])))&&new Set(plan.collection.map(x=>x.source_kind)).size===plan.collection.length,path+'/collection','COLLECTION_MEMBER_INVALID','A supplied collection row is incomplete or duplicates a source kind.','Complete each supplied source-kind row and keep one collection contract per kind.',20); ruleCheck(plan.rules,path+'/rules',true,plan.outcome_cutoff); return findings.size===start; }; if(r.mode==='PRE_TEST_PLAN'){ planCheck(r.pre_test,'/pre_test'); const pendingExternal=r.external_requests.some(x=>x.resolution_state==='OPEN'&&['ALL',r.mode].includes(x.blocking_scope)); if(findings.size||pendingExternal){const f=[...findings.values()].sort(findingOrder)[0];return finish('INSUFFICIENT_EVIDENCE',f?.reason_code||'EXTERNAL_REQUEST_OPEN',f?.reason||'An external/native request remains open.');} return finish('BOUNDED_TEST','PRE_TEST_READY','The first-test plan has exact arms, collection, budget and time bounds, controls and buyer-owned review rules.',{publisher_control_state:'PROPOSED_WITH_APPLICATION_CHECK',placement_evidence_state:'PLANNED_CAMPAIGN_ARM_COLLECTION',bounded_test_kind:'PRE_TEST',observe_until:r.pre_test.rules.observe_until,review_cutoff:r.pre_test.rules.review_cutoff,next_review_at:r.pre_test.rules.next_review_at,test_plan:clone(r.pre_test),next_action:`Prepare LinkedIn-only and Mixed placement; verify applied controls before spend. Stop at the first budget/time bound and review at ${r.pre_test.rules.review_cutoff}.`}); } const evidenceStart=findings.size; for(const [key,placement] of [['on_linkedin','ON_LINKEDIN'],['audience_network','AUDIENCE_NETWORK']]){ const co=e[key],path='/existing/'+key; txt(co.cohort_id,path+'/cohort_id',21); need(co.placement===placement,path+'/placement','PLACEMENT_IDENTITY_CONFLICT','Placement label conflicts with its cohort.','Use the correct platform placement identity.',21); for(const field of ['account_ref','campaign_ref','audience_ref','currency','counting_unit'])need(co[field]===c[field],path+'/'+field,'COHORT_SCOPE_MISMATCH',`${field} differs from campaign scope.`,`Collect ${placement} for the exact campaign scope.`,21); need(list(co.ad_set_refs)&&sameSet(co.ad_set_refs,c.ad_set_refs),path+'/ad_set_refs','COHORT_SCOPE_MISMATCH','Cohort ad sets differ from campaign scope.','Use the exact reviewed ad sets.',21); txt(co.population_ref,path+'/population_ref',21);need(co.denominator_definition==='JOINED_UNIQUE_RECORDS',path+'/denominator_definition','DENOMINATOR_CONFLICT','CRM rates need the declared joined-unique-record denominator.','Use consistent denominator definitions; numeric counts may differ.',21); for(const field of Object.keys(co.window))date(co.window[field],path+'/window/'+field,21); const w=co.window;need(utc(w.delivery_start)&&utc(w.delivery_end)&&utc(w.outcome_cutoff)&&utc(w.collected_through)&&w.delivery_start=w.delivery_end&&w.collected_through<=w.outcome_cutoff&&w.collected_through<=asOf,path+'/window','WINDOW_INVALID','Delivery, collection and outcome windows are not ordered or include future observations.','Supply the exact ordered windows; future outcomes remain pending.',21); attribution(co.attribution,path+'/attribution'); for(const field of ['spend_minor','impressions','clicks','eligible_records','accepted_records','qualified_records'])need(nat(co[field]),path+'/'+field,'METRIC_UNKNOWN_OR_INVALID',`${field} is missing or invalid.`,`Supply observed nonnegative ${field}; unknown is not zero.`,22,c.measurement_owner); for(const field of ['landing_page_clicks','platform_conversions'])need(co[field]===null||nat(co[field]),path+'/'+field,'METRIC_INVALID',`${field} is invalid.`,`Supply the reported value or null when unavailable.`,22); } need(e.on_linkedin.cohort_id!==e.audience_network.cohort_id,'/existing/audience_network/cohort_id','COHORT_IDENTITY_CONFLICT','The two placement cohorts share an ID.','Assign distinct stable cohort IDs.',21); for(const field of ['account_ref','campaign_ref','ad_set_refs','audience_ref','window','attribution','currency','counting_unit','population_ref','denominator_definition'])need(field==='ad_set_refs'?sameSet(e.on_linkedin[field],e.audience_network[field]):same(e.on_linkedin[field],e.audience_network[field]),'/existing/comparability/'+field,'COHORTS_INCOMPARABLE',`On LinkedIn and Audience Network differ in ${field}.`,`Recollect both cohorts with the same ${field}; preserve the originals.`,21); const platformOK=proof(e.platform_source_ref,'PLATFORM_ON_OFF_EXPORT','/existing/platform_source_ref',23,true); const crmOK=proof(e.crm_source_ref,'CRM_EXPORT','/existing/crm_source_ref',24,true); const j=e.join; for(const field of ['placement_carrier_field','method_or_key','cardinality','eligible_population_ref','deduplication_method','audited_by','limitations'])txt(j[field],'/existing/join/'+field,25,c.measurement_owner); validPast(j.audited_at,'/existing/join/audited_at',25); proof(j.placement_source_ref,'PLACEMENT_TO_LEAD_EVENT_EXPORT','/existing/join/placement_source_ref',25,true); proof(j.crm_source_ref,'CRM_EXPORT','/existing/join/crm_source_ref',25,true); proof(j.audit_source_ref,'JOIN_AUDIT','/existing/join/audit_source_ref',25,true); proof(j.deduplication_evidence_ref,'JOIN_AUDIT','/existing/join/deduplication_evidence_ref',25,true); need(j.crm_source_ref===e.crm_source_ref,'/existing/join/crm_source_ref','JOIN_CRM_MISMATCH','The join and outcome sources name different CRM exports.','Join the exact CRM export used for the outcomes.',25); need(sources.get(j.placement_source_ref)?.carried_dimensions.includes(j.placement_carrier_field),'/existing/join/placement_carrier_field','PLACEMENT_CARRIER_MISSING','The lead/event source does not carry the declared placement field.','Supply a placement-bearing lead/event source; aggregate On/Off data is insufficient.',25); need(j.eligible_population_ref===e.on_linkedin.population_ref,'/existing/join/eligible_population_ref','JOIN_POPULATION_MISMATCH','Join population differs from the reviewed cohort.','Audit the same eligible population.',25); for(const key of ['on_linkedin','audience_network']){ const counts=j[key],co=e[key],path='/existing/join/'+key; for(const field of Object.keys(counts))need(nat(counts[field]),path+'/'+field,'JOIN_COUNT_UNKNOWN',`Join ${field} is missing or invalid.`,`Supply the audited ${field} count.`,25); need(positive(counts.eligible)&&positive(counts.joined)&&counts.eligible===co.eligible_records&&counts.joined+counts.unmatched+counts.ambiguous===counts.eligible&&counts.ambiguous===0&&nat(co.accepted_records)&&nat(co.qualified_records)&&co.qualified_records<=co.accepted_records&&co.accepted_records<=counts.joined,path,'JOIN_COUNTS_CONFLICT','Join counts, unique assignment or nested outcome counts do not reconcile.','Reconcile eligible = joined + unmatched + ambiguous; resolve ambiguity and retain unmatched records without allocation.',25); } const whollyMissingJoin=!known(j.placement_source_ref)&&!known(j.method_or_key)&&Object.values(j.on_linkedin).every(x=>x===null)&&Object.values(j.audience_network).every(x=>x===null); if(whollyMissingJoin){for(const [id,finding] of findings)if(finding.field.startsWith('/existing/join'))findings.delete(id);add('/existing/join','PLACEMENT_JOIN_REQUIRED','Campaign CRM and On/Off totals do not establish placement-specific CRM outcomes.','Supply the placement-to-lead source, join method/key, coverage counts and deduplication audit, or prepare a prospective LinkedIn-only versus Mixed placement plan.',24,c.measurement_owner);} const dataOK=findings.size===evidenceStart&&platformOK&&crmOK&&[c.accepted_definition,c.qualified_definition,c.counting_unit].every(known); ruleCheck(e.rules,'/existing/rules',false,e.on_linkedin.window.outcome_cutoff); if(!whollyMissingJoin)for(const key of ['on_linkedin','audience_network'])need(nat(e.rules.minimum_join_coverage_bp)&&positive(j[key].eligible)&&nat(j[key].joined)&&BigInt(j[key].joined)*10000n>=BigInt(e.rules.minimum_join_coverage_bp)*BigInt(j[key].eligible),'/existing/join/'+key+'/coverage','JOIN_COVERAGE_BELOW_RULE','Join coverage is missing or below the buyer-owned threshold.','Collect or reconcile the exact missing join coverage; do not allocate unmatched records.',26); const stop=e.stop_observation; proof(stop.source_ref,'STOP_CHECK','/existing/stop_observation/source_ref',29); need(typeof stop.suitability_breach==='boolean'&&typeof stop.source_failure==='boolean'&&nat(stop.spend_minor),'/existing/stop_observation','STOP_OBSERVATION_MISSING','The current stop observations are incomplete.','Collect suitability/source/spend observations with the dated source.',29); const stopVals={SUITABILITY_BREACH:stop.suitability_breach===null?null:Number(stop.suitability_breach),SOURCE_FAILURE:stop.source_failure===null?null:Number(stop.source_failure),SPEND_MINOR:stop.spend_minor}; const triggered=e.rules.stop_conditions.some(x=>nat(stopVals[x.metric])&&nat(x.threshold)&&compare(stopVals[x.metric],1,x.operator,x.threshold)); if(triggered)add('/existing/stop_observation','STOP_TRIGGERED','An early stop condition is triggered.','Pause further delivery, preserve evidence and resolve the stop before any continuation.',29,e.rules.stop_owner); const metrics={}; for(const key of ['on_linkedin','audience_network']){ const co=e[key],jc=j[key];metrics[key]={platform:platformOK?{spend_minor:co.spend_minor,impressions:co.impressions,clicks:co.clicks,landing_page_clicks:co.landing_page_clicks,platform_conversions:co.platform_conversions,cpc_minor:fraction(co.spend_minor,co.clicks),ctr_bp:fraction(co.clicks,co.impressions,10000)}:null,crm:dataOK?{counting_unit:co.counting_unit,population_ref:co.population_ref,denominator_definition:co.denominator_definition,eligible:jc.eligible,joined:jc.joined,unmatched:jc.unmatched,ambiguous:jc.ambiguous,accepted:co.accepted_records,qualified:co.qualified_records,coverage_bp:fraction(jc.joined,jc.eligible,10000),accepted_rate_bp:fraction(co.accepted_records,jc.joined,10000),qualified_rate_bp:fraction(co.qualified_records,jc.joined,10000)}:null}; } const extra={metrics,placement_crm_state:dataOK?'AVAILABLE':'UNKNOWN',placement_evidence_state:platformOK?'SUPPLIED_SCOPED_ON_OFF_REPORT':'UNVERIFIED',publisher_control_state:[...findings.values()].some(x=>x.field.startsWith('/publisher')||x.field.startsWith('/controls'))?'UNVERIFIED':'SUPPLIED_APPLIED_RECEIPTS',observe_until:e.rules.observe_until,review_cutoff:e.rules.review_cutoff,next_review_at:e.rules.next_review_at,stop_result:triggered?'TRIGGERED':'CLEAR'}; const pendingExternal=r.external_requests.some(x=>x.resolution_state==='OPEN'&&['ALL',r.mode].includes(x.blocking_scope)); if(findings.size||pendingExternal){const f=[...findings.values()].sort(findingOrder)[0];return finish('INSUFFICIENT_EVIDENCE',f?.reason_code||'EXTERNAL_REQUEST_OPEN',f?.reason||'An external/native request remains open.',extra);} if(asOfj[key].joined{ const key=pred.cohort==='ON_LINKEDIN'?'on_linkedin':'audience_network',co=e[key],jc=j[key]; const pairs={QUALIFIED_RATE_BP:[co.qualified_records*10000,jc.joined],ACCEPTED_RATE_BP:[co.accepted_records*10000,jc.joined],QUALIFIED_COUNT:[co.qualified_records,1],ACCEPTED_COUNT:[co.accepted_records,1],CPC_MINOR:[co.spend_minor,co.clicks],CTR_BP:[co.clicks*10000,co.impressions]}; const pair=pairs[pred.metric];return pair&&nat(pair[0])&&positive(pair[1])?compare(pair[0],pair[1],pred.operator,pred.threshold):null; }); if(predicateResults.some(x=>x===null)){add('/existing/rules/success','RULE_NOT_EXECUTABLE','A rule metric has an unavailable or zero denominator.','Repair the rule or collect its exact supported denominator.',33);return finish('INSUFFICIENT_EVIDENCE','RULE_NOT_EXECUTABLE','The buyer rule cannot be executed.',{...extra,maturity_result:'MATURE'});} const pass=predicateResults.every(Boolean), matureExtra={...extra,maturity_result:'MATURE',rule_result:pass?'TRUE':'FALSE',predicate_results:predicateResults}; if(!pass&&e.rules.failure_action==='DISABLE')return finish('KEEP_DISABLED','MATURE_RULE_FAILED_DISABLE','Complete mature evidence fails the buyer-owned rule whose failed branch says disable.',{...matureExtra,controlling_evidence_refs:[e.platform_source_ref,e.crm_source_ref,j.audit_source_ref],next_action:`Keep Audience Network disabled. Reconsider only when: ${e.rules.reconsideration_condition}`}); if(!pass&&e.rules.failure_action==='REDESIGN'){ if(!planCheck(r.replacement_pre_test,'/replacement_pre_test'))return finish('INSUFFICIENT_EVIDENCE','REPLACEMENT_PLAN_REQUIRED','The mature failed review requires a complete bounded replacement plan.',matureExtra); return finish('BOUNDED_TEST','REPLACEMENT_PLAN_READY','Preserve the failed review; the complete replacement plan defines the next bounded test.',{...matureExtra,bounded_test_kind:'REPLACEMENT',test_plan:clone(r.replacement_pre_test),failed_review_fingerprint:sha256(canonical(e)),observe_until:r.replacement_pre_test.rules.observe_until,review_cutoff:r.replacement_pre_test.rules.review_cutoff,next_review_at:r.replacement_pre_test.rules.next_review_at,next_action:`Preserve the failed review. Run replacement ${r.replacement_pre_test.plan_id} within its budget and time limits; review at ${r.replacement_pre_test.rules.review_cutoff}.`}); } if(pass)return finish('CONTINUE_WITH_CONTROLS','MATURE_RULE_PASSED','Mature comparable placement-joined CRM evidence satisfies the buyer-owned rule with current documented controls.',{...matureExtra,next_action:`Continue within the recorded campaign scope and controls. Review again at ${e.rules.next_review_at}; publisher/control review dates still apply.`}); add('/existing/rules','RULE_NOT_EXECUTABLE','The rule has no executable result.','Complete the success and failed-action branches.',33); return finish('INSUFFICIENT_EVIDENCE','RULE_NOT_EXECUTABLE','No implied outcome is permitted.',matureExtra); } export function envelope(record,options={}){const evaluation=evaluate(record,options);return {format:'maestro.lan.export.v1',contract_id:contract.contract_id,contract_version:ENGINE_VERSION,input:clone(record),payload_sha256:sha256(canonical(record)),evaluation};} export function importRecord(value,options={}) { let parsed=value; if(typeof value==='string'){ if(value.length>4000000)throw new Error('IMPORT_TOO_LARGE'); const fences=[...value.matchAll(/```json\s*\n([\s\S]*?)\n```/g)]; if(fences.length){if(fences.length!==1)throw new Error('AMBIGUOUS_JSON_FENCES');parsed=JSON.parse(fences[0][1]);}else parsed=JSON.parse(value); } let input=parsed,integrity='SOURCE_RECALCULATED'; if(parsed?.format){ const keys=['format','contract_id','contract_version','input','payload_sha256','evaluation']; if(Object.keys(parsed).length!==keys.length||!keys.every(k=>Object.hasOwn(parsed,k))||parsed.format!=='maestro.lan.export.v1'||parsed.contract_id!==contract.contract_id||parsed.contract_version!==ENGINE_VERSION)throw new Error('INVALID_ENVELOPE'); input=parsed.input;assertShape(input); if(parsed.payload_sha256!==sha256(canonical(input)))throw new Error('HASH_MISMATCH'); // An envelope must carry the exact historical calculation, then gets evaluated afresh. if(!parsed.evaluation||!utc(parsed.evaluation.evaluated_as_of)||!same(parsed.evaluation,evaluate(input,{asOf:parsed.evaluation.evaluated_as_of})))throw new Error('EVALUATION_RECEIPT_MISMATCH'); integrity='ENVELOPE_INTEGRITY_VERIFIED'; } else if(parsed?.input){ // Exact engine results are a supported prompt transport; derived values remain historical. input=parsed.input;assertShape(input); if(!utc(parsed.evaluated_as_of)||!same(parsed,evaluate(input,{asOf:parsed.evaluated_as_of})))throw new Error('EVALUATION_RECEIPT_MISMATCH'); integrity='EVALUATION_REPLAY_VERIFIED'; } assertShape(input);const evaluation=evaluate(input,options); return {integrity,input:clone(input),evaluation}; } export function importInto(current,value,options={}){try{return {accepted:true,...importRecord(value,options)}}catch(error){return {accepted:false,integrity:'IMPORT_REJECTED',error:String(error.message),input:clone(current),evaluation:evaluate(current,options)};}} export function flatten(value,path=''){ if(value!==null&&typeof value==='object'){ const entries=Object.entries(value);if(!entries.length)return [[path,Array.isArray(value)?'No entries':'No supplied members']]; return entries.flatMap(([k,v])=>flatten(v,path+'/'+esc(k))); } return [[path,value===null?'Unknown':typeof value==='boolean'?(value?'Yes':'No'):String(value)]]; } const md=x=>String(x).replace(/\|/g,'\\|').replace(/\r?\n/g,'
'); export function toMarkdown(result){ const ev=result.format?result.evaluation:result,input=ev.input; const lines=['# LinkedIn Audience Network decision record','',`**${ev.decision}** — ${ev.reason}`,'',`Next action: ${ev.next_action}`,'',`Placement CRM: ${ev.placement_crm_state}. Publisher controls: ${ev.publisher_control_state}.`,'',ev.provenance_summary,'',ev.claim_boundary]; for(const [heading,data] of [['Decision and evidence',{...ev,input:undefined,requests:undefined}],['Campaign',input.campaign],['Publisher review',input.publisher],['Suitability',input.suitability],['Controls',input.controls],['Pre-test plan',input.pre_test],['Existing campaign review',input.existing],['Replacement plan',input.replacement_pre_test],['Sources',input.sources],['External requests',input.external_requests],['History',input.history]]){ lines.push('',`## ${heading}`,'','| Field | Value |','| --- | --- |'); for(const [path,v] of flatten(data).filter(([,v])=>v!=='undefined'))lines.push(`| ${md(label(path))} | ${md(v)} |`); } lines.push('','## Open requests',''); if(!ev.requests.length)lines.push('None.'); for(const request of ev.requests)lines.push(`- ${request.request_id} — ${request.owner||'Owner assignment required'}: ${request.reason} ${request.action} Completion: ${request.completion_observation}`); lines.push('','## Machine-readable record','','```json',JSON.stringify(envelope(input,{asOf:ev.evaluated_as_of}),null,2),'```','');return lines.join('\n'); } export function toCSV(result){const ev=result.format?result.evaluation:result;const handoff={decision:ev.decision,reason_code:ev.reason_code,reason:ev.reason,evaluated_as_of:ev.evaluated_as_of,input_fingerprint:ev.input_fingerprint,placement_crm_state:ev.placement_crm_state,publisher_control_state:ev.publisher_control_state,placement_evidence_state:ev.placement_evidence_state,rule_result:ev.rule_result,maturity_result:ev.maturity_result,bounded_test_kind:ev.bounded_test_kind,observe_until:ev.observe_until,review_cutoff:ev.review_cutoff,next_review_at:ev.next_review_at,claim_boundary:ev.claim_boundary,provenance_summary:ev.provenance_summary,next_action:ev.next_action,stop_result:ev.stop_result,predicate_results:ev.predicate_results,requests:ev.requests,metrics:ev.metrics};const rows=[['record_id','revision','field','value_state','value'],...flatten({input:ev.input,evaluation:handoff}).map(([field,value])=>[ev.record_id,ev.input.revision,field,value==='Unknown'?'UNKNOWN':'SUPPLIED_OR_DERIVED',value])];const cell=x=>'"'+String(x).replaceAll('"','""')+'"';return rows.map(row=>row.map(cell).join(',')).join('\r\n')+'\r\n';} ``` SUPPLIED RECORD {{PASTE_JSON_HERE}}