{
  "name": "HarvestLab Contact CRM changes - review only",
  "nodes": [
    {
      "id": "5a43f571-30f4-50d9-b98d-c25d6d229bb6",
      "name": "Manual review",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        200
      ],
      "parameters": {}
    },
    {
      "id": "237ebed4-f7e5-5a68-b5ae-52ad0d6d161d",
      "name": "Configure existing run",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Edit only this config object. Never place credentials here.\nconst config = {\n  \"runId\": \"REPLACE_WITH_SUCCEEDED_RUN_ID\",\n  \"expectedActorId\": \"bHzVpEmytvDNJk48m\",\n  \"maxRows\": 1000,\n  \"pageSize\": 100,\n  \"baselineReference\": \"initial-empty\",\n  \"previousSnapshot\": {\n    \"merge_policy\": \"upsert_by_key_preserve_existing_on_empty\",\n    \"companies\": [],\n    \"contacts\": []\n  },\n  \"contactReviewMode\": \"single_run\",\n  \"expectedContactInput\": null,\n  \"retryRunId\": null,\n  \"contactRefreshWindow\": null\n};\n/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\n/* Review one completed retry against its exact checked Contact pilot cohort. */\nconst CONTACT_RETRY_COHORT_SITES = 25;\nconst CONTACT_RETRY_SOURCE_TYPES = new Set(['contact_data','partial_result','fetch_failed']);\n\nfunction contactRefreshBounds(window) {\n  if (!object(window) || ![window.startDate,window.endDate].every(day =>\n      typeof day === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(day))) {\n    fail('Set an explicit UTC start and end date for the Contact refresh.');\n  }\n  const start = sourceTime(window.startDate+'T00:00:00Z','Contact refresh');\n  const end = sourceTime(window.endDate+'T23:59:59.999999Z','Contact refresh');\n  if (end < start) fail('Contact refresh end date precedes its start date.');\n  return {start,end};\n}\n\nfunction validateContactRetryConfig(config) {\n  validateContactReviewConfig(config);\n  if (config.retryRunId == null && config.contactRefreshWindow == null) return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || !validId(config.retryRunId) || config.retryRunId === config.runId) {\n    fail('Set one distinct completed retry run ID in fixed_cohort mode.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!scope.require_mx || scope.urls.length !== CONTACT_RETRY_COHORT_SITES) {\n    fail('The paired Contact review requires the checked-only 25-site cohort.');\n  }\n  contactRefreshBounds(config.contactRefreshWindow);\n  return config;\n}\n\nfunction checkContactRetryRunPair(original,retry,config) {\n  if (!object(original) || !object(retry) || !validId(config.retryRunId) || config.retryRunId === config.runId ||\n      original.runId !== config.runId || retry.runId !== config.retryRunId ||\n      original.actorId !== CONTACT_ACTOR_ID || retry.actorId !== CONTACT_ACTOR_ID ||\n      ![original.datasetId,retry.datasetId,original.storeId,retry.storeId].every(validId) ||\n      original.datasetId === retry.datasetId || original.storeId === retry.storeId) {\n    fail('Original and retry Contact run or default storage identities conflict.');\n  }\n  const {start,end} = contactRefreshBounds(config.contactRefreshWindow);\n  const [originalStart,originalEnd,retryStart,retryEnd] = [original.startedAt,original.finishedAt,retry.startedAt,retry.finishedAt]\n    .map(value => sourceTime(value,'Contact run'));\n  if (start > originalStart || originalStart > originalEnd || originalEnd > retryStart || retryStart > retryEnd || retryEnd > end) {\n    fail('Contact runs must finish in order within the same UTC refresh window.');\n  }\n}\n\nfunction validateContactRetryRun(retryResponse,originalResponse,config) {\n  validateContactRetryConfig(config);\n  const original = {...validateRun(originalResponse,config),\n    startedAt:originalResponse.data.startedAt,finishedAt:originalResponse.data.finishedAt};\n  const retry = {...validateRun(retryResponse,{...config,runId:config.retryRunId}),\n    startedAt:retryResponse.data.startedAt,finishedAt:retryResponse.data.finishedAt};\n  checkContactRetryRunPair(original,retry,config);\n  return retry;\n}\n\nfunction checkContactRetryPayload(payload,manifest,scope,config,label) {\n  const validated = validateSnapshot(payload,config.maxRows,true);\n  if (validated.companies.length !== manifest.exported_companies || validated.contacts.length !== manifest.exported_contacts) {\n    fail(label+' CRM payload does not match its completion manifest.');\n  }\n  return checkContactCohortRows(validated,scope,label+' CRM export',{native:true});\n}\n\nfunction checkContactRetryScope(retry,original,observed) {\n  if (!object(retry) || !Array.isArray(retry.planned_company_keys)) fail('Retry Contact scope is missing.');\n  const selected = new Set(retry.planned_company_keys);\n  if (!selected.size || selected.size !== retry.planned_company_keys.length ||\n      retry.planned_company_keys.some(key => observed.has(key) || !original.planned_company_keys.includes(key))) {\n    fail('Retry must target distinct companies absent from the original Contact export.');\n  }\n  const domains = original.planned_company_keys.filter(key => selected.has(key));\n  const urls = original.urls.filter((_,index) => selected.has(original.planned_company_keys[index]));\n  const expected = {...original,urls,planned_company_keys:domains,max_websites:urls.length,\n    max_mx_checks:Math.min(original.max_mx_checks,urls.length)};\n  if (stable(retry) !== stable(expected)) fail('Retry saved INPUT differs from the permitted Contact URLs, order or settings.');\n}\n\nfunction validateContactRetryInput(rawRetryInput,originalUpserts,originalManifest,scope,config) {\n  validateContactRetryConfig(config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(scope) || stable(scope) !== stable(expected)) fail('Original Contact scope differs from the pinned cohort.');\n  validateContactRunManifest(originalManifest,config,scope);\n  const observed = checkContactRetryPayload(originalUpserts,originalManifest,scope,config,'Original');\n  const retry = readContactFixedInput(rawRetryInput,'Retry');\n  checkContactRetryScope(retry,scope,observed);\n  return retry;\n}\n\nfunction validateContactRetryManifest(manifest,config,scope) {\n  if (!object(scope) || !Array.isArray(scope.urls) || !scope.urls.length || scope.require_mx !== true) {\n    fail('Verified checked-only Contact retry scope is missing.');\n  }\n  if (manifest?.exported_companies === 0) {\n    const files = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n    if (manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false ||\n        manifest.exported_contacts !== 0 || !Number.isInteger(manifest.source_rows) || manifest.source_rows < 0 ||\n        manifest.persisted_site_rows !== manifest.source_rows || manifest.source_rows > config.maxRows ||\n        !Array.isArray(manifest.files) || manifest.files.length !== files.length || !files.every(name => manifest.files.includes(name))) {\n      fail('Empty Contact retry must have a complete native manifest.');\n    }\n  } else {\n    validateManifest(manifest,config.maxRows);\n  }\n  if (manifest.require_mx !== true || manifest.requested_sites !== scope.urls.length || manifest.source_rows > scope.urls.length) {\n    fail('Contact retry manifest does not match its verified scope.');\n  }\n  return manifest;\n}\n\nfunction contactRetryDataset(pages,scope,run,config) {\n  const rows = datasetRows(pages,config);\n  const start = sourceTime(run.startedAt,'Contact run'), end = sourceTime(run.finishedAt,'Contact run');\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  for (const row of rows) {\n    if (!CONTACT_RETRY_SOURCE_TYPES.has(row?.result_type)) continue;\n    const observed = sourceTime(row.scraped_at,'Contact dataset');\n    // Native rows timestamped to the second can fall in the run's opening second.\n    const earliest = /T\\d{2}:\\d{2}:\\d{2}(?:Z|[+-])/.test(row.scraped_at) ? start - (start % 1_000_000n) : start;\n    if (planned.get(contactCompanyKey(row.domain)) !== row.url || typeof row.url !== 'string' ||\n        observed < earliest || observed > end) {\n      fail('Contact dataset contains a source row outside its run scope or time range.');\n    }\n  }\n  return rows;\n}\n\nfunction reviewContactWithRetry({config,originalRun,retryRun,originalScope,retryScope,originalManifest,retryManifest,\n    originalUpserts,retryUpserts,originalPages,retryPages}) {\n  validateContactRetryConfig(config);\n  checkContactRetryRunPair(originalRun,retryRun,config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(originalScope) || stable(originalScope) !== stable(expected)) {\n    fail('Original Contact scope differs from the pinned cohort.');\n  }\n  validateContactRunManifest(originalManifest,config,originalScope);\n  const observedOriginal = checkContactRetryPayload(originalUpserts,originalManifest,originalScope,config,'Original');\n  checkContactRetryScope(retryScope,originalScope,observedOriginal);\n  validateContactRetryManifest(retryManifest,config,retryScope);\n  const observedRetry = checkContactRetryPayload(retryUpserts,retryManifest,retryScope,config,'Retry');\n  const originalRows = contactRetryDataset(originalPages,originalScope,originalRun,config);\n  const retryRows = contactRetryDataset(retryPages,retryScope,retryRun,config);\n  if (originalRows.length + retryRows.length > config.maxRows) fail('Combined Contact dataset exceeds maxRows.');\n  const observations = verifyContactCrmDatasetCompanions([originalUpserts,retryUpserts],[\n    {manifest:originalManifest,dataset:originalRows},{manifest:retryManifest,dataset:retryRows},\n  ]);\n  const selected = [...originalUpserts.contacts,...retryUpserts.contacts];\n  const held = new Set();\n  for (const contact of selected) {\n    const sources = observations.get(contact.contact_key);\n    if (new Set(sources?.map(source => contactCompanyKey(source.companyKey))).size > 1) held.add(contact.contact_key);\n  }\n  const contacts = selected.filter(contact => !held.has(contact.contact_key));\n  const companies = [...originalUpserts.companies,...retryUpserts.companies];\n  const rows = originalManifest.source_rows + retryManifest.source_rows;\n  // Each real manifest has already been verified. This count record is internal to the merge.\n  const merged = crmHandoff({...originalUpserts,companies,contacts},{...originalManifest,\n    exported_companies:companies.length,exported_contacts:contacts.length,persisted_site_rows:rows,source_rows:rows},config,originalRun);\n  const planned = originalScope.planned_company_keys;\n  const observed = new Set([...observedOriginal,...observedRetry]);\n  const absent = planned.filter(key => !observed.has(key));\n  const qualified = new Set(contacts.filter(contact => contact.company_key).map(contact => contactCompanyKey(contact.company_key)));\n  merged.candidate_baseline.contact_scope = originalScope;\n  merged.handoff_id += ':'+retryRun.runId;\n  merged.source_retry_run_id = retryRun.runId;\n  merged.acknowledgement_binding.required = [\n    'source_run_id','source_retry_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload',\n  ];\n  merged.contact_refresh_window = {startDate:config.contactRefreshWindow.startDate,endDate:config.contactRefreshWindow.endDate};\n  merged.review_issues.push(...[...held].sort().map(record_key => ({\n    record_type:'contacts',record_key,reason:'cross_run_ambiguous_company_association',\n  })));\n  merged.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete',planned_company_count:planned.length,\n    observed_company_count:observed.size,absent_company_count:absent.length,\n    planned_company_keys:planned,observed_company_keys:planned.filter(key => observed.has(key)),absent_company_keys:absent,\n    original_observed_company_count:observedOriginal.size,retry_observed_company_count:observedRetry.size,\n    current_mx_qualified_company_count:qualified.size,held_contact_count:held.size,\n    original_post_crawl_interruption:Object.hasOwn(originalManifest,'post_crawl_interruption'),\n    retry_post_crawl_interruption:Object.hasOwn(retryManifest,'post_crawl_interruption'),\n  };\n  return merged;\n}\n\nreturn [{json:validateContactRetryConfig(config)}];"
      }
    },
    {
      "id": "54286c80-1bc0-555a-ac0b-2a474c04473c",
      "name": "Read existing run",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        200
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/actor-runs/' + $json.runId }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "9fb80a9f-7e40-537b-baf7-844597c1946f",
      "name": "Verify succeeded run",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\nreturn [{json:validateRun($input.first().json,$('Configure existing run').first().json)}];"
      }
    },
    {
      "id": "e4f5a99c-c341-5401-ab3d-c5bf3b9a3e3f",
      "name": "Pinned Contact cohort?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        880,
        200
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "leftValue": "={{ $('Configure existing run').first().json.contactReviewMode ?? 'single_run' }}",
              "rightValue": "fixed_cohort",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "87ef5534-f7bc-5e94-bb87-d12d825fd912",
      "name": "Read saved Contact input",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        200
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $json.storeId + '/records/INPUT' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "6fe72b1c-5405-51a6-b85d-cfc5579f949b",
      "name": "Verify Contact cohort",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\nconst config = $('Configure existing run').first().json;\nreturn [{json:validateContactRunScope(config,$input.first().json)}];"
      }
    },
    {
      "id": "90b048ce-2181-536e-85f8-1babfac65806",
      "name": "Read CRM manifest",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1540,
        200
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $('Verify succeeded run').first().json.storeId + '/records/CRM-EXPORT' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "a8a84b17-c27d-5a00-8ceb-2945ed6338d7",
      "name": "Verify CRM manifest",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1760,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\nconst config = $('Configure existing run').first().json;\nconst scope = config.contactReviewMode === 'fixed_cohort' ? $('Verify Contact cohort').first().json : null;\nreturn [{json:validateContactRunManifest($input.first().json,config,scope)}];"
      }
    },
    {
      "id": "0a9b0478-71d8-52e6-920a-bf3d0093f9d7",
      "name": "Read native CRM upserts",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1980,
        200
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $('Verify succeeded run').first().json.storeId + '/records/CRM-upserts.json' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "a964954d-61e4-560e-9c61-4bb6d5231d8a",
      "name": "Review a Contact retry?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2200,
        200
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "leftValue": "={{ $('Configure existing run').first().json.retryRunId != null }}",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "5eda3e87-f67d-5d89-b9bc-c9cda37d621a",
      "name": "Review CRM changes",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2420,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\nconst config = $('Configure existing run').first().json;\nconst scope = config.contactReviewMode === 'fixed_cohort' ? $('Verify Contact cohort').first().json : null;\nreturn [{json:reviewContactRun($input.first().json,$('Verify CRM manifest').first().json,config,$('Verify succeeded run').first().json,scope)}];"
      }
    },
    {
      "id": "3c792a40-9faf-57c7-a22d-af05f0bf2731",
      "name": "Read retry run",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2420,
        380
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/actor-runs/' + $('Configure existing run').first().json.retryRunId }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "a5bf94eb-536a-5fa4-9e28-cc84a07f3320",
      "name": "Verify retry run",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2640,
        380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\n/* Review one completed retry against its exact checked Contact pilot cohort. */\nconst CONTACT_RETRY_COHORT_SITES = 25;\nconst CONTACT_RETRY_SOURCE_TYPES = new Set(['contact_data','partial_result','fetch_failed']);\n\nfunction contactRefreshBounds(window) {\n  if (!object(window) || ![window.startDate,window.endDate].every(day =>\n      typeof day === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(day))) {\n    fail('Set an explicit UTC start and end date for the Contact refresh.');\n  }\n  const start = sourceTime(window.startDate+'T00:00:00Z','Contact refresh');\n  const end = sourceTime(window.endDate+'T23:59:59.999999Z','Contact refresh');\n  if (end < start) fail('Contact refresh end date precedes its start date.');\n  return {start,end};\n}\n\nfunction validateContactRetryConfig(config) {\n  validateContactReviewConfig(config);\n  if (config.retryRunId == null && config.contactRefreshWindow == null) return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || !validId(config.retryRunId) || config.retryRunId === config.runId) {\n    fail('Set one distinct completed retry run ID in fixed_cohort mode.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!scope.require_mx || scope.urls.length !== CONTACT_RETRY_COHORT_SITES) {\n    fail('The paired Contact review requires the checked-only 25-site cohort.');\n  }\n  contactRefreshBounds(config.contactRefreshWindow);\n  return config;\n}\n\nfunction checkContactRetryRunPair(original,retry,config) {\n  if (!object(original) || !object(retry) || !validId(config.retryRunId) || config.retryRunId === config.runId ||\n      original.runId !== config.runId || retry.runId !== config.retryRunId ||\n      original.actorId !== CONTACT_ACTOR_ID || retry.actorId !== CONTACT_ACTOR_ID ||\n      ![original.datasetId,retry.datasetId,original.storeId,retry.storeId].every(validId) ||\n      original.datasetId === retry.datasetId || original.storeId === retry.storeId) {\n    fail('Original and retry Contact run or default storage identities conflict.');\n  }\n  const {start,end} = contactRefreshBounds(config.contactRefreshWindow);\n  const [originalStart,originalEnd,retryStart,retryEnd] = [original.startedAt,original.finishedAt,retry.startedAt,retry.finishedAt]\n    .map(value => sourceTime(value,'Contact run'));\n  if (start > originalStart || originalStart > originalEnd || originalEnd > retryStart || retryStart > retryEnd || retryEnd > end) {\n    fail('Contact runs must finish in order within the same UTC refresh window.');\n  }\n}\n\nfunction validateContactRetryRun(retryResponse,originalResponse,config) {\n  validateContactRetryConfig(config);\n  const original = {...validateRun(originalResponse,config),\n    startedAt:originalResponse.data.startedAt,finishedAt:originalResponse.data.finishedAt};\n  const retry = {...validateRun(retryResponse,{...config,runId:config.retryRunId}),\n    startedAt:retryResponse.data.startedAt,finishedAt:retryResponse.data.finishedAt};\n  checkContactRetryRunPair(original,retry,config);\n  return retry;\n}\n\nfunction checkContactRetryPayload(payload,manifest,scope,config,label) {\n  const validated = validateSnapshot(payload,config.maxRows,true);\n  if (validated.companies.length !== manifest.exported_companies || validated.contacts.length !== manifest.exported_contacts) {\n    fail(label+' CRM payload does not match its completion manifest.');\n  }\n  return checkContactCohortRows(validated,scope,label+' CRM export',{native:true});\n}\n\nfunction checkContactRetryScope(retry,original,observed) {\n  if (!object(retry) || !Array.isArray(retry.planned_company_keys)) fail('Retry Contact scope is missing.');\n  const selected = new Set(retry.planned_company_keys);\n  if (!selected.size || selected.size !== retry.planned_company_keys.length ||\n      retry.planned_company_keys.some(key => observed.has(key) || !original.planned_company_keys.includes(key))) {\n    fail('Retry must target distinct companies absent from the original Contact export.');\n  }\n  const domains = original.planned_company_keys.filter(key => selected.has(key));\n  const urls = original.urls.filter((_,index) => selected.has(original.planned_company_keys[index]));\n  const expected = {...original,urls,planned_company_keys:domains,max_websites:urls.length,\n    max_mx_checks:Math.min(original.max_mx_checks,urls.length)};\n  if (stable(retry) !== stable(expected)) fail('Retry saved INPUT differs from the permitted Contact URLs, order or settings.');\n}\n\nfunction validateContactRetryInput(rawRetryInput,originalUpserts,originalManifest,scope,config) {\n  validateContactRetryConfig(config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(scope) || stable(scope) !== stable(expected)) fail('Original Contact scope differs from the pinned cohort.');\n  validateContactRunManifest(originalManifest,config,scope);\n  const observed = checkContactRetryPayload(originalUpserts,originalManifest,scope,config,'Original');\n  const retry = readContactFixedInput(rawRetryInput,'Retry');\n  checkContactRetryScope(retry,scope,observed);\n  return retry;\n}\n\nfunction validateContactRetryManifest(manifest,config,scope) {\n  if (!object(scope) || !Array.isArray(scope.urls) || !scope.urls.length || scope.require_mx !== true) {\n    fail('Verified checked-only Contact retry scope is missing.');\n  }\n  if (manifest?.exported_companies === 0) {\n    const files = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n    if (manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false ||\n        manifest.exported_contacts !== 0 || !Number.isInteger(manifest.source_rows) || manifest.source_rows < 0 ||\n        manifest.persisted_site_rows !== manifest.source_rows || manifest.source_rows > config.maxRows ||\n        !Array.isArray(manifest.files) || manifest.files.length !== files.length || !files.every(name => manifest.files.includes(name))) {\n      fail('Empty Contact retry must have a complete native manifest.');\n    }\n  } else {\n    validateManifest(manifest,config.maxRows);\n  }\n  if (manifest.require_mx !== true || manifest.requested_sites !== scope.urls.length || manifest.source_rows > scope.urls.length) {\n    fail('Contact retry manifest does not match its verified scope.');\n  }\n  return manifest;\n}\n\nfunction contactRetryDataset(pages,scope,run,config) {\n  const rows = datasetRows(pages,config);\n  const start = sourceTime(run.startedAt,'Contact run'), end = sourceTime(run.finishedAt,'Contact run');\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  for (const row of rows) {\n    if (!CONTACT_RETRY_SOURCE_TYPES.has(row?.result_type)) continue;\n    const observed = sourceTime(row.scraped_at,'Contact dataset');\n    // Native rows timestamped to the second can fall in the run's opening second.\n    const earliest = /T\\d{2}:\\d{2}:\\d{2}(?:Z|[+-])/.test(row.scraped_at) ? start - (start % 1_000_000n) : start;\n    if (planned.get(contactCompanyKey(row.domain)) !== row.url || typeof row.url !== 'string' ||\n        observed < earliest || observed > end) {\n      fail('Contact dataset contains a source row outside its run scope or time range.');\n    }\n  }\n  return rows;\n}\n\nfunction reviewContactWithRetry({config,originalRun,retryRun,originalScope,retryScope,originalManifest,retryManifest,\n    originalUpserts,retryUpserts,originalPages,retryPages}) {\n  validateContactRetryConfig(config);\n  checkContactRetryRunPair(originalRun,retryRun,config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(originalScope) || stable(originalScope) !== stable(expected)) {\n    fail('Original Contact scope differs from the pinned cohort.');\n  }\n  validateContactRunManifest(originalManifest,config,originalScope);\n  const observedOriginal = checkContactRetryPayload(originalUpserts,originalManifest,originalScope,config,'Original');\n  checkContactRetryScope(retryScope,originalScope,observedOriginal);\n  validateContactRetryManifest(retryManifest,config,retryScope);\n  const observedRetry = checkContactRetryPayload(retryUpserts,retryManifest,retryScope,config,'Retry');\n  const originalRows = contactRetryDataset(originalPages,originalScope,originalRun,config);\n  const retryRows = contactRetryDataset(retryPages,retryScope,retryRun,config);\n  if (originalRows.length + retryRows.length > config.maxRows) fail('Combined Contact dataset exceeds maxRows.');\n  const observations = verifyContactCrmDatasetCompanions([originalUpserts,retryUpserts],[\n    {manifest:originalManifest,dataset:originalRows},{manifest:retryManifest,dataset:retryRows},\n  ]);\n  const selected = [...originalUpserts.contacts,...retryUpserts.contacts];\n  const held = new Set();\n  for (const contact of selected) {\n    const sources = observations.get(contact.contact_key);\n    if (new Set(sources?.map(source => contactCompanyKey(source.companyKey))).size > 1) held.add(contact.contact_key);\n  }\n  const contacts = selected.filter(contact => !held.has(contact.contact_key));\n  const companies = [...originalUpserts.companies,...retryUpserts.companies];\n  const rows = originalManifest.source_rows + retryManifest.source_rows;\n  // Each real manifest has already been verified. This count record is internal to the merge.\n  const merged = crmHandoff({...originalUpserts,companies,contacts},{...originalManifest,\n    exported_companies:companies.length,exported_contacts:contacts.length,persisted_site_rows:rows,source_rows:rows},config,originalRun);\n  const planned = originalScope.planned_company_keys;\n  const observed = new Set([...observedOriginal,...observedRetry]);\n  const absent = planned.filter(key => !observed.has(key));\n  const qualified = new Set(contacts.filter(contact => contact.company_key).map(contact => contactCompanyKey(contact.company_key)));\n  merged.candidate_baseline.contact_scope = originalScope;\n  merged.handoff_id += ':'+retryRun.runId;\n  merged.source_retry_run_id = retryRun.runId;\n  merged.acknowledgement_binding.required = [\n    'source_run_id','source_retry_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload',\n  ];\n  merged.contact_refresh_window = {startDate:config.contactRefreshWindow.startDate,endDate:config.contactRefreshWindow.endDate};\n  merged.review_issues.push(...[...held].sort().map(record_key => ({\n    record_type:'contacts',record_key,reason:'cross_run_ambiguous_company_association',\n  })));\n  merged.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete',planned_company_count:planned.length,\n    observed_company_count:observed.size,absent_company_count:absent.length,\n    planned_company_keys:planned,observed_company_keys:planned.filter(key => observed.has(key)),absent_company_keys:absent,\n    original_observed_company_count:observedOriginal.size,retry_observed_company_count:observedRetry.size,\n    current_mx_qualified_company_count:qualified.size,held_contact_count:held.size,\n    original_post_crawl_interruption:Object.hasOwn(originalManifest,'post_crawl_interruption'),\n    retry_post_crawl_interruption:Object.hasOwn(retryManifest,'post_crawl_interruption'),\n  };\n  return merged;\n}\n\nconst config = $('Configure existing run').first().json;\nreturn [{json:validateContactRetryRun($input.first().json,$('Read existing run').first().json,config)}];"
      }
    },
    {
      "id": "035d2e20-2d0a-510e-bd6f-5dc59544375e",
      "name": "Read saved retry input",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2860,
        380
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $json.storeId + '/records/INPUT' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "8324068b-78c7-538c-8610-137b4eeb1945",
      "name": "Verify retry scope",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3080,
        380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\n/* Review one completed retry against its exact checked Contact pilot cohort. */\nconst CONTACT_RETRY_COHORT_SITES = 25;\nconst CONTACT_RETRY_SOURCE_TYPES = new Set(['contact_data','partial_result','fetch_failed']);\n\nfunction contactRefreshBounds(window) {\n  if (!object(window) || ![window.startDate,window.endDate].every(day =>\n      typeof day === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(day))) {\n    fail('Set an explicit UTC start and end date for the Contact refresh.');\n  }\n  const start = sourceTime(window.startDate+'T00:00:00Z','Contact refresh');\n  const end = sourceTime(window.endDate+'T23:59:59.999999Z','Contact refresh');\n  if (end < start) fail('Contact refresh end date precedes its start date.');\n  return {start,end};\n}\n\nfunction validateContactRetryConfig(config) {\n  validateContactReviewConfig(config);\n  if (config.retryRunId == null && config.contactRefreshWindow == null) return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || !validId(config.retryRunId) || config.retryRunId === config.runId) {\n    fail('Set one distinct completed retry run ID in fixed_cohort mode.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!scope.require_mx || scope.urls.length !== CONTACT_RETRY_COHORT_SITES) {\n    fail('The paired Contact review requires the checked-only 25-site cohort.');\n  }\n  contactRefreshBounds(config.contactRefreshWindow);\n  return config;\n}\n\nfunction checkContactRetryRunPair(original,retry,config) {\n  if (!object(original) || !object(retry) || !validId(config.retryRunId) || config.retryRunId === config.runId ||\n      original.runId !== config.runId || retry.runId !== config.retryRunId ||\n      original.actorId !== CONTACT_ACTOR_ID || retry.actorId !== CONTACT_ACTOR_ID ||\n      ![original.datasetId,retry.datasetId,original.storeId,retry.storeId].every(validId) ||\n      original.datasetId === retry.datasetId || original.storeId === retry.storeId) {\n    fail('Original and retry Contact run or default storage identities conflict.');\n  }\n  const {start,end} = contactRefreshBounds(config.contactRefreshWindow);\n  const [originalStart,originalEnd,retryStart,retryEnd] = [original.startedAt,original.finishedAt,retry.startedAt,retry.finishedAt]\n    .map(value => sourceTime(value,'Contact run'));\n  if (start > originalStart || originalStart > originalEnd || originalEnd > retryStart || retryStart > retryEnd || retryEnd > end) {\n    fail('Contact runs must finish in order within the same UTC refresh window.');\n  }\n}\n\nfunction validateContactRetryRun(retryResponse,originalResponse,config) {\n  validateContactRetryConfig(config);\n  const original = {...validateRun(originalResponse,config),\n    startedAt:originalResponse.data.startedAt,finishedAt:originalResponse.data.finishedAt};\n  const retry = {...validateRun(retryResponse,{...config,runId:config.retryRunId}),\n    startedAt:retryResponse.data.startedAt,finishedAt:retryResponse.data.finishedAt};\n  checkContactRetryRunPair(original,retry,config);\n  return retry;\n}\n\nfunction checkContactRetryPayload(payload,manifest,scope,config,label) {\n  const validated = validateSnapshot(payload,config.maxRows,true);\n  if (validated.companies.length !== manifest.exported_companies || validated.contacts.length !== manifest.exported_contacts) {\n    fail(label+' CRM payload does not match its completion manifest.');\n  }\n  return checkContactCohortRows(validated,scope,label+' CRM export',{native:true});\n}\n\nfunction checkContactRetryScope(retry,original,observed) {\n  if (!object(retry) || !Array.isArray(retry.planned_company_keys)) fail('Retry Contact scope is missing.');\n  const selected = new Set(retry.planned_company_keys);\n  if (!selected.size || selected.size !== retry.planned_company_keys.length ||\n      retry.planned_company_keys.some(key => observed.has(key) || !original.planned_company_keys.includes(key))) {\n    fail('Retry must target distinct companies absent from the original Contact export.');\n  }\n  const domains = original.planned_company_keys.filter(key => selected.has(key));\n  const urls = original.urls.filter((_,index) => selected.has(original.planned_company_keys[index]));\n  const expected = {...original,urls,planned_company_keys:domains,max_websites:urls.length,\n    max_mx_checks:Math.min(original.max_mx_checks,urls.length)};\n  if (stable(retry) !== stable(expected)) fail('Retry saved INPUT differs from the permitted Contact URLs, order or settings.');\n}\n\nfunction validateContactRetryInput(rawRetryInput,originalUpserts,originalManifest,scope,config) {\n  validateContactRetryConfig(config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(scope) || stable(scope) !== stable(expected)) fail('Original Contact scope differs from the pinned cohort.');\n  validateContactRunManifest(originalManifest,config,scope);\n  const observed = checkContactRetryPayload(originalUpserts,originalManifest,scope,config,'Original');\n  const retry = readContactFixedInput(rawRetryInput,'Retry');\n  checkContactRetryScope(retry,scope,observed);\n  return retry;\n}\n\nfunction validateContactRetryManifest(manifest,config,scope) {\n  if (!object(scope) || !Array.isArray(scope.urls) || !scope.urls.length || scope.require_mx !== true) {\n    fail('Verified checked-only Contact retry scope is missing.');\n  }\n  if (manifest?.exported_companies === 0) {\n    const files = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n    if (manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false ||\n        manifest.exported_contacts !== 0 || !Number.isInteger(manifest.source_rows) || manifest.source_rows < 0 ||\n        manifest.persisted_site_rows !== manifest.source_rows || manifest.source_rows > config.maxRows ||\n        !Array.isArray(manifest.files) || manifest.files.length !== files.length || !files.every(name => manifest.files.includes(name))) {\n      fail('Empty Contact retry must have a complete native manifest.');\n    }\n  } else {\n    validateManifest(manifest,config.maxRows);\n  }\n  if (manifest.require_mx !== true || manifest.requested_sites !== scope.urls.length || manifest.source_rows > scope.urls.length) {\n    fail('Contact retry manifest does not match its verified scope.');\n  }\n  return manifest;\n}\n\nfunction contactRetryDataset(pages,scope,run,config) {\n  const rows = datasetRows(pages,config);\n  const start = sourceTime(run.startedAt,'Contact run'), end = sourceTime(run.finishedAt,'Contact run');\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  for (const row of rows) {\n    if (!CONTACT_RETRY_SOURCE_TYPES.has(row?.result_type)) continue;\n    const observed = sourceTime(row.scraped_at,'Contact dataset');\n    // Native rows timestamped to the second can fall in the run's opening second.\n    const earliest = /T\\d{2}:\\d{2}:\\d{2}(?:Z|[+-])/.test(row.scraped_at) ? start - (start % 1_000_000n) : start;\n    if (planned.get(contactCompanyKey(row.domain)) !== row.url || typeof row.url !== 'string' ||\n        observed < earliest || observed > end) {\n      fail('Contact dataset contains a source row outside its run scope or time range.');\n    }\n  }\n  return rows;\n}\n\nfunction reviewContactWithRetry({config,originalRun,retryRun,originalScope,retryScope,originalManifest,retryManifest,\n    originalUpserts,retryUpserts,originalPages,retryPages}) {\n  validateContactRetryConfig(config);\n  checkContactRetryRunPair(originalRun,retryRun,config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(originalScope) || stable(originalScope) !== stable(expected)) {\n    fail('Original Contact scope differs from the pinned cohort.');\n  }\n  validateContactRunManifest(originalManifest,config,originalScope);\n  const observedOriginal = checkContactRetryPayload(originalUpserts,originalManifest,originalScope,config,'Original');\n  checkContactRetryScope(retryScope,originalScope,observedOriginal);\n  validateContactRetryManifest(retryManifest,config,retryScope);\n  const observedRetry = checkContactRetryPayload(retryUpserts,retryManifest,retryScope,config,'Retry');\n  const originalRows = contactRetryDataset(originalPages,originalScope,originalRun,config);\n  const retryRows = contactRetryDataset(retryPages,retryScope,retryRun,config);\n  if (originalRows.length + retryRows.length > config.maxRows) fail('Combined Contact dataset exceeds maxRows.');\n  const observations = verifyContactCrmDatasetCompanions([originalUpserts,retryUpserts],[\n    {manifest:originalManifest,dataset:originalRows},{manifest:retryManifest,dataset:retryRows},\n  ]);\n  const selected = [...originalUpserts.contacts,...retryUpserts.contacts];\n  const held = new Set();\n  for (const contact of selected) {\n    const sources = observations.get(contact.contact_key);\n    if (new Set(sources?.map(source => contactCompanyKey(source.companyKey))).size > 1) held.add(contact.contact_key);\n  }\n  const contacts = selected.filter(contact => !held.has(contact.contact_key));\n  const companies = [...originalUpserts.companies,...retryUpserts.companies];\n  const rows = originalManifest.source_rows + retryManifest.source_rows;\n  // Each real manifest has already been verified. This count record is internal to the merge.\n  const merged = crmHandoff({...originalUpserts,companies,contacts},{...originalManifest,\n    exported_companies:companies.length,exported_contacts:contacts.length,persisted_site_rows:rows,source_rows:rows},config,originalRun);\n  const planned = originalScope.planned_company_keys;\n  const observed = new Set([...observedOriginal,...observedRetry]);\n  const absent = planned.filter(key => !observed.has(key));\n  const qualified = new Set(contacts.filter(contact => contact.company_key).map(contact => contactCompanyKey(contact.company_key)));\n  merged.candidate_baseline.contact_scope = originalScope;\n  merged.handoff_id += ':'+retryRun.runId;\n  merged.source_retry_run_id = retryRun.runId;\n  merged.acknowledgement_binding.required = [\n    'source_run_id','source_retry_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload',\n  ];\n  merged.contact_refresh_window = {startDate:config.contactRefreshWindow.startDate,endDate:config.contactRefreshWindow.endDate};\n  merged.review_issues.push(...[...held].sort().map(record_key => ({\n    record_type:'contacts',record_key,reason:'cross_run_ambiguous_company_association',\n  })));\n  merged.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete',planned_company_count:planned.length,\n    observed_company_count:observed.size,absent_company_count:absent.length,\n    planned_company_keys:planned,observed_company_keys:planned.filter(key => observed.has(key)),absent_company_keys:absent,\n    original_observed_company_count:observedOriginal.size,retry_observed_company_count:observedRetry.size,\n    current_mx_qualified_company_count:qualified.size,held_contact_count:held.size,\n    original_post_crawl_interruption:Object.hasOwn(originalManifest,'post_crawl_interruption'),\n    retry_post_crawl_interruption:Object.hasOwn(retryManifest,'post_crawl_interruption'),\n  };\n  return merged;\n}\n\nconst config = $('Configure existing run').first().json;\nreturn [{json:validateContactRetryInput($input.first().json,$('Read native CRM upserts').first().json,$('Verify CRM manifest').first().json,$('Verify Contact cohort').first().json,config)}];"
      }
    },
    {
      "id": "56dcb176-07d7-5dfa-affc-7ed841a91c6c",
      "name": "Read retry CRM manifest",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3300,
        380
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $('Verify retry run').first().json.storeId + '/records/CRM-EXPORT' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "acfd0562-72e6-5da8-9b71-9f20f74988f2",
      "name": "Verify retry CRM manifest",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3520,
        380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\n/* Review one completed retry against its exact checked Contact pilot cohort. */\nconst CONTACT_RETRY_COHORT_SITES = 25;\nconst CONTACT_RETRY_SOURCE_TYPES = new Set(['contact_data','partial_result','fetch_failed']);\n\nfunction contactRefreshBounds(window) {\n  if (!object(window) || ![window.startDate,window.endDate].every(day =>\n      typeof day === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(day))) {\n    fail('Set an explicit UTC start and end date for the Contact refresh.');\n  }\n  const start = sourceTime(window.startDate+'T00:00:00Z','Contact refresh');\n  const end = sourceTime(window.endDate+'T23:59:59.999999Z','Contact refresh');\n  if (end < start) fail('Contact refresh end date precedes its start date.');\n  return {start,end};\n}\n\nfunction validateContactRetryConfig(config) {\n  validateContactReviewConfig(config);\n  if (config.retryRunId == null && config.contactRefreshWindow == null) return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || !validId(config.retryRunId) || config.retryRunId === config.runId) {\n    fail('Set one distinct completed retry run ID in fixed_cohort mode.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!scope.require_mx || scope.urls.length !== CONTACT_RETRY_COHORT_SITES) {\n    fail('The paired Contact review requires the checked-only 25-site cohort.');\n  }\n  contactRefreshBounds(config.contactRefreshWindow);\n  return config;\n}\n\nfunction checkContactRetryRunPair(original,retry,config) {\n  if (!object(original) || !object(retry) || !validId(config.retryRunId) || config.retryRunId === config.runId ||\n      original.runId !== config.runId || retry.runId !== config.retryRunId ||\n      original.actorId !== CONTACT_ACTOR_ID || retry.actorId !== CONTACT_ACTOR_ID ||\n      ![original.datasetId,retry.datasetId,original.storeId,retry.storeId].every(validId) ||\n      original.datasetId === retry.datasetId || original.storeId === retry.storeId) {\n    fail('Original and retry Contact run or default storage identities conflict.');\n  }\n  const {start,end} = contactRefreshBounds(config.contactRefreshWindow);\n  const [originalStart,originalEnd,retryStart,retryEnd] = [original.startedAt,original.finishedAt,retry.startedAt,retry.finishedAt]\n    .map(value => sourceTime(value,'Contact run'));\n  if (start > originalStart || originalStart > originalEnd || originalEnd > retryStart || retryStart > retryEnd || retryEnd > end) {\n    fail('Contact runs must finish in order within the same UTC refresh window.');\n  }\n}\n\nfunction validateContactRetryRun(retryResponse,originalResponse,config) {\n  validateContactRetryConfig(config);\n  const original = {...validateRun(originalResponse,config),\n    startedAt:originalResponse.data.startedAt,finishedAt:originalResponse.data.finishedAt};\n  const retry = {...validateRun(retryResponse,{...config,runId:config.retryRunId}),\n    startedAt:retryResponse.data.startedAt,finishedAt:retryResponse.data.finishedAt};\n  checkContactRetryRunPair(original,retry,config);\n  return retry;\n}\n\nfunction checkContactRetryPayload(payload,manifest,scope,config,label) {\n  const validated = validateSnapshot(payload,config.maxRows,true);\n  if (validated.companies.length !== manifest.exported_companies || validated.contacts.length !== manifest.exported_contacts) {\n    fail(label+' CRM payload does not match its completion manifest.');\n  }\n  return checkContactCohortRows(validated,scope,label+' CRM export',{native:true});\n}\n\nfunction checkContactRetryScope(retry,original,observed) {\n  if (!object(retry) || !Array.isArray(retry.planned_company_keys)) fail('Retry Contact scope is missing.');\n  const selected = new Set(retry.planned_company_keys);\n  if (!selected.size || selected.size !== retry.planned_company_keys.length ||\n      retry.planned_company_keys.some(key => observed.has(key) || !original.planned_company_keys.includes(key))) {\n    fail('Retry must target distinct companies absent from the original Contact export.');\n  }\n  const domains = original.planned_company_keys.filter(key => selected.has(key));\n  const urls = original.urls.filter((_,index) => selected.has(original.planned_company_keys[index]));\n  const expected = {...original,urls,planned_company_keys:domains,max_websites:urls.length,\n    max_mx_checks:Math.min(original.max_mx_checks,urls.length)};\n  if (stable(retry) !== stable(expected)) fail('Retry saved INPUT differs from the permitted Contact URLs, order or settings.');\n}\n\nfunction validateContactRetryInput(rawRetryInput,originalUpserts,originalManifest,scope,config) {\n  validateContactRetryConfig(config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(scope) || stable(scope) !== stable(expected)) fail('Original Contact scope differs from the pinned cohort.');\n  validateContactRunManifest(originalManifest,config,scope);\n  const observed = checkContactRetryPayload(originalUpserts,originalManifest,scope,config,'Original');\n  const retry = readContactFixedInput(rawRetryInput,'Retry');\n  checkContactRetryScope(retry,scope,observed);\n  return retry;\n}\n\nfunction validateContactRetryManifest(manifest,config,scope) {\n  if (!object(scope) || !Array.isArray(scope.urls) || !scope.urls.length || scope.require_mx !== true) {\n    fail('Verified checked-only Contact retry scope is missing.');\n  }\n  if (manifest?.exported_companies === 0) {\n    const files = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n    if (manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false ||\n        manifest.exported_contacts !== 0 || !Number.isInteger(manifest.source_rows) || manifest.source_rows < 0 ||\n        manifest.persisted_site_rows !== manifest.source_rows || manifest.source_rows > config.maxRows ||\n        !Array.isArray(manifest.files) || manifest.files.length !== files.length || !files.every(name => manifest.files.includes(name))) {\n      fail('Empty Contact retry must have a complete native manifest.');\n    }\n  } else {\n    validateManifest(manifest,config.maxRows);\n  }\n  if (manifest.require_mx !== true || manifest.requested_sites !== scope.urls.length || manifest.source_rows > scope.urls.length) {\n    fail('Contact retry manifest does not match its verified scope.');\n  }\n  return manifest;\n}\n\nfunction contactRetryDataset(pages,scope,run,config) {\n  const rows = datasetRows(pages,config);\n  const start = sourceTime(run.startedAt,'Contact run'), end = sourceTime(run.finishedAt,'Contact run');\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  for (const row of rows) {\n    if (!CONTACT_RETRY_SOURCE_TYPES.has(row?.result_type)) continue;\n    const observed = sourceTime(row.scraped_at,'Contact dataset');\n    // Native rows timestamped to the second can fall in the run's opening second.\n    const earliest = /T\\d{2}:\\d{2}:\\d{2}(?:Z|[+-])/.test(row.scraped_at) ? start - (start % 1_000_000n) : start;\n    if (planned.get(contactCompanyKey(row.domain)) !== row.url || typeof row.url !== 'string' ||\n        observed < earliest || observed > end) {\n      fail('Contact dataset contains a source row outside its run scope or time range.');\n    }\n  }\n  return rows;\n}\n\nfunction reviewContactWithRetry({config,originalRun,retryRun,originalScope,retryScope,originalManifest,retryManifest,\n    originalUpserts,retryUpserts,originalPages,retryPages}) {\n  validateContactRetryConfig(config);\n  checkContactRetryRunPair(originalRun,retryRun,config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(originalScope) || stable(originalScope) !== stable(expected)) {\n    fail('Original Contact scope differs from the pinned cohort.');\n  }\n  validateContactRunManifest(originalManifest,config,originalScope);\n  const observedOriginal = checkContactRetryPayload(originalUpserts,originalManifest,originalScope,config,'Original');\n  checkContactRetryScope(retryScope,originalScope,observedOriginal);\n  validateContactRetryManifest(retryManifest,config,retryScope);\n  const observedRetry = checkContactRetryPayload(retryUpserts,retryManifest,retryScope,config,'Retry');\n  const originalRows = contactRetryDataset(originalPages,originalScope,originalRun,config);\n  const retryRows = contactRetryDataset(retryPages,retryScope,retryRun,config);\n  if (originalRows.length + retryRows.length > config.maxRows) fail('Combined Contact dataset exceeds maxRows.');\n  const observations = verifyContactCrmDatasetCompanions([originalUpserts,retryUpserts],[\n    {manifest:originalManifest,dataset:originalRows},{manifest:retryManifest,dataset:retryRows},\n  ]);\n  const selected = [...originalUpserts.contacts,...retryUpserts.contacts];\n  const held = new Set();\n  for (const contact of selected) {\n    const sources = observations.get(contact.contact_key);\n    if (new Set(sources?.map(source => contactCompanyKey(source.companyKey))).size > 1) held.add(contact.contact_key);\n  }\n  const contacts = selected.filter(contact => !held.has(contact.contact_key));\n  const companies = [...originalUpserts.companies,...retryUpserts.companies];\n  const rows = originalManifest.source_rows + retryManifest.source_rows;\n  // Each real manifest has already been verified. This count record is internal to the merge.\n  const merged = crmHandoff({...originalUpserts,companies,contacts},{...originalManifest,\n    exported_companies:companies.length,exported_contacts:contacts.length,persisted_site_rows:rows,source_rows:rows},config,originalRun);\n  const planned = originalScope.planned_company_keys;\n  const observed = new Set([...observedOriginal,...observedRetry]);\n  const absent = planned.filter(key => !observed.has(key));\n  const qualified = new Set(contacts.filter(contact => contact.company_key).map(contact => contactCompanyKey(contact.company_key)));\n  merged.candidate_baseline.contact_scope = originalScope;\n  merged.handoff_id += ':'+retryRun.runId;\n  merged.source_retry_run_id = retryRun.runId;\n  merged.acknowledgement_binding.required = [\n    'source_run_id','source_retry_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload',\n  ];\n  merged.contact_refresh_window = {startDate:config.contactRefreshWindow.startDate,endDate:config.contactRefreshWindow.endDate};\n  merged.review_issues.push(...[...held].sort().map(record_key => ({\n    record_type:'contacts',record_key,reason:'cross_run_ambiguous_company_association',\n  })));\n  merged.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete',planned_company_count:planned.length,\n    observed_company_count:observed.size,absent_company_count:absent.length,\n    planned_company_keys:planned,observed_company_keys:planned.filter(key => observed.has(key)),absent_company_keys:absent,\n    original_observed_company_count:observedOriginal.size,retry_observed_company_count:observedRetry.size,\n    current_mx_qualified_company_count:qualified.size,held_contact_count:held.size,\n    original_post_crawl_interruption:Object.hasOwn(originalManifest,'post_crawl_interruption'),\n    retry_post_crawl_interruption:Object.hasOwn(retryManifest,'post_crawl_interruption'),\n  };\n  return merged;\n}\n\nconst config = $('Configure existing run').first().json;\nreturn [{json:validateContactRetryManifest($input.first().json,config,$('Verify retry scope').first().json)}];"
      }
    },
    {
      "id": "2eb72066-3f59-55c2-9517-5cd31353069d",
      "name": "Read retry CRM upserts",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3740,
        380
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/key-value-stores/' + $('Verify retry run').first().json.storeId + '/records/CRM-upserts.json' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": false
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          }
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "6fc24f61-38a8-5389-889c-643950227737",
      "name": "Read original Contact dataset pages",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3960,
        380
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/datasets/' + $('Verify succeeded run').first().json.datasetId + '/items' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": true
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "qs",
                    "name": "offset",
                    "value": "={{ $pageCount * $('Configure existing run').first().json.pageSize }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !Array.isArray($response.body) || $response.body.length < $('Configure existing run').first().json.pageSize }}",
              "limitPagesFetched": true,
              "maxRequests": "={{ Math.ceil($('Configure existing run').first().json.maxRows / $('Configure existing run').first().json.pageSize) + 1 }}",
              "requestInterval": 200
            }
          }
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "format",
              "value": "json"
            },
            {
              "name": "clean",
              "value": "false"
            },
            {
              "name": "limit",
              "value": "={{ $('Configure existing run').first().json.pageSize }}"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "e2df1e47-31a4-5be4-86e6-2808bfef276f",
      "name": "Bind original Contact dataset pages",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4180,
        380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\nconst config = $('Configure existing run').first().json;\nconst pages = $input.all().map(item => item.json);\ndatasetRows(pages,config);\nreturn [{json:{pages}}];"
      }
    },
    {
      "id": "9631c5e5-6f2a-5345-9008-f94916c26127",
      "name": "Read retry Contact dataset pages",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        4400,
        380
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://api.apify.com/v2/datasets/' + $('Verify retry run').first().json.datasetId + '/items' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json",
              "fullResponse": true
            }
          },
          "timeout": 30000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "qs",
                    "name": "offset",
                    "value": "={{ $pageCount * $('Configure existing run').first().json.pageSize }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !Array.isArray($response.body) || $response.body.length < $('Configure existing run').first().json.pageSize }}",
              "limitPagesFetched": true,
              "maxRequests": "={{ Math.ceil($('Configure existing run').first().json.maxRows / $('Configure existing run').first().json.pageSize) + 1 }}",
              "requestInterval": 200
            }
          }
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "format",
              "value": "json"
            },
            {
              "name": "clean",
              "value": "false"
            },
            {
              "name": "limit",
              "value": "={{ $('Configure existing run').first().json.pageSize }}"
            }
          ]
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "notes": "Choose a private HTTP Header Auth credential: Authorization = Bearer <Apify token>. GET only; token never goes in a URL."
    },
    {
      "id": "8fb0f3a3-07c0-51c6-8dfd-1b3365b94497",
      "name": "Review original plus retry",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4620,
        380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "/* Pure handoff contracts embedded in n8n Code nodes by build_templates.py.\n * No network, persistence, Actor invocation, destination writes or logging.\n */\nconst MERGE_POLICY = 'upsert_by_key_preserve_existing_on_empty';\nconst COMPANY_FIELDS = ['company_key','domain','company_name','website','linkedin_url','contact_page_url','phone','phone_status','tech_stack','scraped_at'];\nconst CONTACT_FIELDS = ['contact_key','company_key','email','email_status','phone','phone_status','role','source_url','scraped_at'];\nconst AMAZON_FIELDS = ['product_key','asin','marketplace','title','price','currency','availability','rating','reviews_count','url','scraped_at','seller'];\nconst AMAZON_POLICY = 'retain_last_good_per_product_key';\nconst AMAZON_CONTEXT_COUNTERS = {\n  offer_context_mismatch:'offer_context_mismatches_suppressed',\n  seller_changed:'seller_changes_suppressed',\n  seller_missing:'missing_sellers_suppressed',\n};\nconst EVIDENCE = {published_unverified:0,mx_medium_mailbox_unknown:1,mx_high_mailbox_unknown:2,smtp_deliverable:3};\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst validId = value => typeof value === 'string' && ID.test(value);\nconst MARKET = /^amazon\\.(?:com|ca|com\\.mx|com\\.br|co\\.uk|de|fr|es|it|nl|pl|se|co\\.jp|in|com\\.au|ae|sa|sg|com\\.tr)$/;\nconst text = v => typeof v === 'string' ? v.trim() : '';\nconst object = v => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst fail = message => { throw new Error(message); };\nconst meaningful = row => Object.fromEntries(Object.entries(row).filter(([k,v]) => k !== 'scraped_at' && v));\nconst stable = row => JSON.stringify(Object.entries(row).sort(([a],[b]) => a.localeCompare(b)));\nconst clean = row => Object.fromEntries(Object.entries(row).filter(([,v]) => v));\n\nfunction validateConfig(config) {\n  if (!object(config) || !validId(config.runId) || config.runId === 'REPLACE_WITH_SUCCEEDED_RUN_ID') fail('Set an exact existing succeeded run ID.');\n  if (!validId(config.expectedActorId)) fail('Invalid expected Actor ID.');\n  if (!Number.isInteger(config.maxRows) || config.maxRows < 1 || config.maxRows > 10000) fail('maxRows must be 1..10000.');\n  if (!Number.isInteger(config.pageSize) || config.pageSize < 1 || config.pageSize > 1000) fail('pageSize must be 1..1000.');\n  if (!text(config.baselineReference) || config.baselineReference.length > 128) fail('Set an explicit accepted baseline revision reference.');\n  if (config.baselineReference === 'initial-empty' && object(config.previousSnapshot) && ['companies','contacts','products'].some(kind => Array.isArray(config.previousSnapshot[kind]) && config.previousSnapshot[kind].length)) fail('A nonempty accepted baseline needs its actual revision reference.');\n  return config;\n}\n\nfunction validateRun(response, config) {\n  validateConfig(config);\n  const run = response && response.data;\n  if (!object(run) || run.id !== config.runId || run.actId !== config.expectedActorId || run.status !== 'SUCCEEDED') fail('Run identity, Actor or succeeded status does not match.');\n  if (!validId(run.defaultDatasetId) || !validId(run.defaultKeyValueStoreId)) fail('Run storage identifiers are missing.');\n  return {runId:run.id, actorId:run.actId, datasetId:run.defaultDatasetId, storeId:run.defaultKeyValueStoreId};\n}\n\nfunction validateManifest(manifest, maxRows) {\n  if (!object(manifest) || manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false) fail('CRM export is absent, partial or unsafe.');\n  for (const name of ['exported_companies','exported_contacts','persisted_site_rows','source_rows']) {\n    if (!Number.isInteger(manifest[name]) || manifest[name] < 0 || manifest[name] > maxRows) fail('CRM manifest count is invalid or exceeds maxRows.');\n  }\n  if (manifest.persisted_site_rows !== manifest.source_rows || manifest.exported_companies === 0 || manifest.exported_companies > manifest.source_rows || manifest.exported_contacts > manifest.source_rows || manifest.exported_companies + manifest.exported_contacts > maxRows) fail('CRM manifest counts are incomplete or exceed maxRows.');\n  const required = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n  if (!Array.isArray(manifest.files) || manifest.files.length !== 3 || required.some(name => !manifest.files.includes(name))) fail('CRM manifest lacks required file references.');\n  if (typeof manifest.require_mx !== 'boolean') fail('CRM manifest has no explicit verification mode.');\n  return manifest;\n}\n\nfunction validateSnapshot(payload, maxRows, native = false) {\n  if (!object(payload) || payload.merge_policy !== MERGE_POLICY || !Array.isArray(payload.companies) || !Array.isArray(payload.contacts)) fail('Invalid CRM snapshot contract.');\n  if (JSON.stringify(payload).length > 10 * 1024 * 1024 || payload.companies.length + payload.contacts.length > maxRows) fail('CRM snapshot exceeds the size or record cap.');\n  if (native && (payload.full_snapshot !== false || payload.allow_deletions !== false || payload.contact_selection !== 'one_eligible_email_per_company_source_row' || payload.association_policy !== 'preserve_existing_on_empty_review_ambiguous')) fail('Native CRM handoff policies do not match.');\n  const result = {merge_policy:MERGE_POLICY,companies:[],contacts:[]};\n  for (const [kind, fields, keyField] of [['companies',COMPANY_FIELDS,'company_key'],['contacts',CONTACT_FIELDS,'contact_key']]) {\n    const seen = new Set();\n    for (const row of payload[kind]) {\n      if (!object(row) || Object.entries(row).some(([k,v]) => !fields.includes(k) || typeof v !== 'string')) fail('Invalid CRM record fields.');\n      const key = row[keyField];\n      if (!key || seen.has(key)) fail('Duplicate or missing CRM key.');\n      seen.add(key);\n      if (kind === 'companies') {\n        if (row.domain !== key || key !== key.toLowerCase() || !key.includes('.') || /[\\s/:@]/.test(key)) fail('Invalid company identity.');\n      } else if (row.email !== key || key !== key.trim().toLowerCase() || !/^[^\\s@,;]+@[^\\s@,;]+\\.[^\\s@,;]+$/.test(key) || !Object.hasOwn(EVIDENCE,row.email_status)) fail('Invalid contact identity or evidence.');\n      if (row.phone && (!/^\\+[1-9]\\d{6,14}$/.test(row.phone) || row.phone_status !== 'format_valid_not_reachability_checked')) fail('Unqualified phone in CRM handoff.');\n      sourceTime(row.scraped_at,'CRM');\n      result[kind].push({...row});\n    }\n  }\n  if (native && result.contacts.some(row => row.company_key && !result.companies.some(company => company.company_key === row.company_key))) fail('Contact refers to a company absent from the native handoff.');\n  return result;\n}\n\nfunction crmHandoff(payload, manifest, config, run) {\n  validateConfig(config);\n  validateManifest(manifest,config.maxRows);\n  const current = validateSnapshot(payload,config.maxRows,true);\n  if (current.companies.length !== manifest.exported_companies || current.contacts.length !== manifest.exported_contacts) fail('CRM payload does not match completion manifest counts.');\n  if (manifest.require_mx && current.contacts.some(row => row.email_status === 'published_unverified')) fail('MX-required export contains an unchecked contact.');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const next = {merge_policy:MERGE_POLICY}, delta = {merge_policy:MERGE_POLICY};\n  const stats = {verification_downgrades_suppressed:0,association_conflicts_suppressed:0,\n    older_companies_suppressed:0,older_contacts_suppressed:0,same_time_company_conflicts_suppressed:0,same_time_contact_conflicts_suppressed:0};\n  const issues = [];\n  for (const [kind,keyField] of [['companies','company_key'],['contacts','contact_key']]) {\n    const saved = new Map(previous[kind].map(row => [row[keyField],{...row}]));\n    const seen = new Set(); const changes = []; let unchanged = 0;\n    for (const row of current[kind]) {\n      const key = row[keyField], old = saved.get(key) || {};\n      seen.add(key);\n      let merged = {...old,...clean(row)};\n      const weaker = kind === 'contacts' && old.email_status && EVIDENCE[row.email_status] < EVIDENCE[old.email_status];\n      const ambiguousAssociation = row.company_key === '';\n      const associationConflict = kind === 'contacts' && old.company_key &&\n        (ambiguousAssociation || (row.company_key && old.company_key !== row.company_key));\n      if (weaker) stats.verification_downgrades_suppressed += 1;\n      if (associationConflict) {\n        stats.association_conflicts_suppressed += 1;\n        if (ambiguousAssociation) {\n          issues.push({\n            record_type:kind, record_key:key, reason:'ambiguous_company_association',\n            scraped_at:row.scraped_at, accepted_scraped_at:old.scraped_at,\n          });\n        }\n      }\n      if (old[keyField]) {\n        const observedTime = sourceTime(row.scraped_at,'CRM'), acceptedTime = sourceTime(old.scraped_at,'CRM');\n        if (observedTime < acceptedTime) {\n          stats['older_'+kind+'_suppressed'] += 1;\n          issues.push({record_type:kind,record_key:key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          merged = {...old};\n        } else if (observedTime === acceptedTime) {\n          if (stable(meaningful(old)) !== stable(meaningful(merged))) {\n            stats['same_time_'+(kind === 'companies' ? 'company' : 'contact')+'_conflicts_suppressed'] += 1;\n            issues.push({record_type:kind,record_key:key,reason:'same_observation_conflict',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n          }\n          // Exact replays and equivalent timezone spellings preserve the accepted record.\n          merged = {...old};\n        } else if (weaker || associationConflict) merged = {...old};\n      }\n      saved.set(key,merged);\n      if (stable(meaningful(old)) === stable(meaningful(merged))) unchanged += 1;\n      else changes.push(clean(merged));\n    }\n    next[kind] = [...saved.values()]; delta[kind] = changes;\n    stats['unchanged_'+kind] = unchanged;\n    stats['retained_'+kind] = previous[kind].filter(row => !seen.has(row[keyField])).length;\n  }\n  validateSnapshot(next,config.maxRows);\n  return {...reviewEnvelope(run,'contact-crm',config),delta,candidate_baseline:next,stats,review_issues:issues};\n}\n\nfunction reviewEnvelope(run,workflow,config) {\n  return {workflow,handoff_id:workflow+':'+run.actorId+':'+run.runId,source_run_id:run.runId,\n    accepted_baseline_reference:config.baselineReference,\n    acknowledgement_binding:{implemented:false,required:['source_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload'],handoff_id_alone_is_insufficient:true},\n    delivery_status:'REVIEW_ONLY',destination_written:false,acknowledgement_required:true,\n    baseline_advanced:false,replace_existing_data:false,delete_missing_records:false};\n}\n\nfunction datasetRows(pages, config) {\n  if (!Array.isArray(pages) || !pages.length) fail('No dataset page response.');\n  let rows = [], expectedOffset = 0, advertisedTotal;\n  for (const page of pages) {\n    if (!object(page) || page.statusCode !== 200 || !Array.isArray(page.body)) fail('A dataset page failed or was not a JSON array.');\n    const headers = Object.fromEntries(Object.entries(page.headers || {}).map(([key,value]) => [key.toLowerCase(),value]));\n    const readInteger = key => /^\\d+$/.test(String(headers[key])) ? Number(headers[key]) : fail('Dataset pagination headers are missing or invalid.');\n    const offset = readInteger('x-apify-pagination-offset');\n    const count = readInteger('x-apify-pagination-count');\n    const total = readInteger('x-apify-pagination-total');\n    const limit = readInteger('x-apify-pagination-limit');\n    if (offset !== expectedOffset || count !== page.body.length || count > config.pageSize || limit !== config.pageSize) fail('Dataset page is missing, repeated or inconsistent.');\n    if (advertisedTotal !== undefined && advertisedTotal !== total) fail('Dataset changed during the export; retry the same completed run.');\n    advertisedTotal = total;\n    if (total > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n    rows.push(...page.body); expectedOffset += config.pageSize;\n    if (rows.length > config.maxRows) fail('Dataset exceeds maxRows; preserve the prior feed.');\n  }\n  if (rows.length !== advertisedTotal || pages.at(-1).body.length >= config.pageSize) fail('Dataset export is incomplete; preserve the prior feed.');\n  return rows;\n}\n\nfunction amazonOfferQuery(url) {\n  const withoutFragment = url.split('#',1)[0];\n  const queryStart = withoutFragment.indexOf('?');\n  const query = queryStart < 0 ? '' : withoutFragment.slice(queryStart + 1);\n  // Match the Actor's Associates-tag handling. Other query components may select an offer.\n  return query.split('&').filter(part => part && part.split('=',1)[0] !== 'tag').join('&');\n}\n\nfunction amazonSource(row,asin) {\n  const urls = ['url','product_url'].filter(key => text(row[key])).map(key => text(row[key]));\n  let market, offerQuery;\n  for (const url of urls) {\n    // Strict literal Amazon hosts: no credentials, port, host escapes or redirects.\n    const parsed = /^https?:\\/\\/([^/?#]+)([^?#]*)/i.exec(url);\n    if (!parsed) return null;\n    const host = parsed[1].toLowerCase().replace(/^www\\./,'');\n    if (!MARKET.test(host) || (market && market !== host)) return null;\n    market = host;\n    const identities = [...parsed[2].matchAll(/\\/(?:dp|gp\\/product|product)\\/([A-Z0-9]{10})(?=\\/|$)/gi)];\n    if (identities.some(match => match[1].toUpperCase() !== asin)) return null;\n    const query = amazonOfferQuery(url);\n    if (offerQuery !== undefined && offerQuery !== query) return null;\n    offerQuery = query;\n  }\n  return urls.length ? {url:urls[0],marketplace:market} : null;\n}\n\nfunction amazonProducts(rows, loadAccepted = () => new Map(), expectedOffers = null, keywordScope = null) {\n  const latest = new Map(), currencyIssues = [], scopeIssues = [];\n  let accepted, rejected = 0;\n  for (const row of rows) {\n    if (!object(row) || row.diagnostic_item || row.block_detected || row.error || row.billable_contact_found === false || ![undefined,null,'product_data','contact_data'].includes(row.result_type)) { rejected++; continue; }\n    const asin = text(row.asin).toUpperCase(), source = amazonSource(row,asin), currency = text(row.currency).toUpperCase();\n    const price = (typeof row.price === 'number' || typeof row.price === 'string') ? String(row.price).trim() : '';\n    if (!/^[A-Z0-9]{10}$/.test(asin) || !source || !text(row.title) || !/^[A-Z]{3}$/.test(currency) || !/^[+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(price) || !Number.isFinite(Number(price)) || Number(price) <= 0) { rejected++; continue; }\n    const timestamp = text(row.scraped_at);\n    let observedAt;\n    try {\n      observedAt = sourceTime(timestamp);\n    } catch {\n      rejected++;\n      continue;\n    }\n    const key = source.marketplace+':'+asin;\n    if (keywordScope && (row.search_query !== keywordScope.searchQuery ||\n        row.amazon_domain !== keywordScope.marketplace || source.marketplace !== keywordScope.marketplace)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_scope'});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && expectedOffers.get(key) !== amazonOfferQuery(source.url)) {\n      scopeIssues.push({product_key:key,reason:expectedOffers.has(key) ? 'fixed_offer_mismatch' : 'outside_fixed_scope'});\n      rejected++;\n      continue;\n    }\n    const normalizedPrice = price.replace(/^\\+/, '');\n    accepted ??= loadAccepted();\n    const acceptedProduct = accepted.get(key);\n    if (acceptedProduct && acceptedProduct.currency !== currency) {\n      // Screen before deduplication so a foreign-currency row cannot hide a compatible update.\n      currencyIssues.push({\n        product_key:key, reason:'currency_mismatch', observed_currency:currency,\n        observed_price:normalizedPrice, accepted_currency:acceptedProduct.currency,\n        scraped_at:timestamp, accepted_scraped_at:acceptedProduct.scraped_at,\n      });\n      continue;\n    }\n    const previous = latest.get(key);\n    if (previous && observedAt < previous.observedAt) continue;\n    const product = {\n      product_key:key, asin, ...source, title:text(row.title),\n      price:normalizedPrice, currency, availability:text(row.availability),\n      rating:row.rating ?? null, reviews_count:row.reviews_count ?? null, scraped_at:timestamp,\n    };\n    const seller = text(row.seller);\n    if (seller) product.seller = seller;\n    const sameInstant = previous?.observedAt === observedAt;\n    // An older row cannot replace a conflict at the newest qualified instant.\n    // A later instant establishes a new observation independently of earlier ties.\n    const conflicting = sameInstant && (previous.conflicting || previous.product.currency !== currency ||\n      decimalIdentity(previous.product.price) !== decimalIdentity(normalizedPrice) ||\n      amazonOfferQuery(previous.product.url) !== amazonOfferQuery(product.url) ||\n      amazonSellerName(previous.product.seller) !== amazonSellerName(product.seller));\n    latest.set(key,{\n      observedAt,product,conflicting,\n      timestamp:sameInstant && previous.timestamp < timestamp ? previous.timestamp : timestamp,\n      count:sameInstant ? previous.count + 1 : 1,\n    });\n  }\n  const products = [], sourceConflicts = [];\n  for (const [product_key,{product,conflicting,timestamp,count}] of latest) {\n    if (conflicting) {\n      sourceConflicts.push({\n        product_key, reason:'same_time_source_conflict', scraped_at:timestamp,\n        accepted_scraped_at:accepted.get(product_key)?.scraped_at ?? null, source_observations:count,\n      });\n    } else products.push(product);\n  }\n  return {products,rejected_rows:rejected,currencyIssues,sourceConflicts,...(expectedOffers || keywordScope ? {scopeIssues} : {})};\n}\n\nfunction sourceTime(value,label = 'Amazon') {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n  if (!match) fail(label+' observation needs an ISO source timestamp with a timezone.');\n  const [,year,month,day,hour,minute,second] = match.map(Number);\n  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year,month,0)).getUTCDate() || hour > 23 || minute > 59 || second > 59) fail('Invalid '+label+' source timestamp.');\n  const parsed = Date.parse(value);\n  if (!Number.isFinite(parsed)) fail('Invalid '+label+' source timestamp.');\n  const fraction = (/\\.(\\d+)(?:Z|[+-])/.exec(value)?.[1] || '').padEnd(6,'0');\n  return BigInt(parsed) * 1000n + BigInt(fraction.slice(3));\n}\n\nfunction decimalIdentity(value) {\n  // Compare equivalent decimal spellings without rounding the persisted price.\n  const match = /^\\+?(\\d*)(?:\\.(\\d*))?(?:e([+-]?\\d+))?$/i.exec(String(value));\n  let coefficient = (match[1] + (match[2] || '')).replace(/^0+/,'');\n  let exponent = Number(match[3] || 0) - (match[2] || '').length;\n  while (coefficient.endsWith('0')) { coefficient = coefficient.slice(0,-1); exponent++; }\n  return coefficient+'e'+exponent;\n}\n\nfunction matchesAmazonKeywordScope(scope,expected) {\n  return object(scope) && Object.keys(scope).length === Object.keys(expected).length &&\n    Object.entries(expected).every(([key,value]) => Object.hasOwn(scope,key) && scope[key] === value);\n}\n\nfunction validateAmazonSnapshot(snapshot,maxRows,keywordScope = null) {\n  const allowed = ['schema_version','policy','products'];\n  if (keywordScope) allowed.push('keyword_scope');\n  if (!object(snapshot) || snapshot.schema_version !== 1 || snapshot.policy !== AMAZON_POLICY || !Array.isArray(snapshot.products) || Object.keys(snapshot).some(key => !allowed.includes(key))) fail('Invalid accepted Amazon snapshot contract.');\n  if (keywordScope && (snapshot.products.length || Object.hasOwn(snapshot,'keyword_scope')) &&\n      !matchesAmazonKeywordScope(snapshot.keyword_scope,keywordScope)) fail('Choose the accepted baseline for the pinned keyword and search settings.');\n  if (snapshot.products.length > maxRows || JSON.stringify(snapshot).length > 10 * 1024 * 1024) fail('Amazon snapshot exceeds the record or size cap.');\n  const seen = new Set(), products = [];\n  for (const row of snapshot.products) {\n    if (!object(row) || Object.keys(row).some(key => !AMAZON_FIELDS.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'seller') && !text(row.seller)) fail('Invalid Amazon baseline seller.');\n    const qualified = amazonProducts([row]).products;\n    if (qualified.length !== 1 || row.product_key !== qualified[0].product_key || row.marketplace !== qualified[0].marketplace || row.asin !== qualified[0].asin || seen.has(row.product_key)) fail('Invalid or duplicate Amazon baseline identity.');\n    if (keywordScope && row.marketplace !== keywordScope.marketplace) fail('The accepted keyword baseline contains a product from another marketplace.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key); products.push(qualified[0]);\n  }\n  return {schema_version:1,policy:AMAZON_POLICY,products,...(keywordScope ? {keyword_scope:keywordScope} : {})};\n}\n\nfunction amazonSellerName(seller) {\n  return (seller || '').replace(/\\s+/g,' ').toLowerCase();\n}\n\nfunction amazonContextMismatch(row,previous) {\n  if (amazonOfferQuery(row.url) !== amazonOfferQuery(previous.url)) return 'offer_context_mismatch';\n  // Legacy snapshots may have no seller. A newer observation can supply the first known seller.\n  if (!previous.seller) return null;\n  if (!row.seller) return 'seller_missing';\n  return amazonSellerName(row.seller) !== amazonSellerName(previous.seller) ? 'seller_changed' : null;\n}\n\nfunction amazonIncremental(products,accepted,maxRows,keywordScope = null) {\n  const saved = new Map(accepted);\n  const seen = new Set(), changes = [], issues = [];\n  const stats = {\n    unchanged_products:0,older_observations_suppressed:0,conflicting_observations_suppressed:0,retained_products:0,\n    offer_context_mismatches_suppressed:0,seller_changes_suppressed:0,missing_sellers_suppressed:0,\n  };\n  for (const row of products) {\n    const time = sourceTime(row.scraped_at), old = saved.get(row.product_key);\n    seen.add(row.product_key);\n    if (old) {\n      const previousTime = sourceTime(old.scraped_at);\n      if (time < previousTime) {\n        stats.older_observations_suppressed++;\n        issues.push({product_key:row.product_key,reason:'older_observation',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      const contextMismatch = amazonContextMismatch(row,old);\n      if (contextMismatch) {\n        stats[AMAZON_CONTEXT_COUNTERS[contextMismatch]]++;\n        issues.push({product_key:row.product_key,reason:contextMismatch,scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\n        continue;\n      }\n      if (time === previousTime) {\n        // Context has already been checked, so equivalent seller spellings or newly reported metadata do not change a replay.\n        const comparison = ({seller,...item}) => ({...meaningful(item),price:decimalIdentity(item.price)});\n        if (stable(comparison(row)) === stable(comparison(old))) stats.unchanged_products++;\n        else {\n          stats.conflicting_observations_suppressed++;\n          issues.push({product_key:row.product_key,reason:'same_observation_conflict',scraped_at:row.scraped_at});\n        }\n        continue;\n      }\n    }\n    saved.set(row.product_key,row); changes.push(row);\n  }\n  stats.retained_products = [...accepted.keys()].filter(key => !seen.has(key)).length;\n  const candidate = validateAmazonSnapshot({schema_version:1,policy:AMAZON_POLICY,products:[...saved.values()],\n    ...(keywordScope ? {keyword_scope:keywordScope} : {})},maxRows,keywordScope);\n  return {delta:{products:changes},candidate_baseline:candidate,stats,review_issues:issues};\n}\n\nfunction amazonHandoff(pages,config,run,scope = null) {\n  validateConfig(config);\n  const fixed = config.amazonReviewMode === 'fixed_products';\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if ((fixed || pinnedKeyword) !== (scope !== null)) fail('Pinned Amazon review needs verified input scope.');\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  if (pinnedKeyword && !matchesAmazonKeywordScope(scope,keywordScope)) fail('The verified input scope disagrees with the pinned keyword or search settings.');\n  const rows = datasetRows(pages,config);\n  const expectedOffers = fixed ? amazonFixedOffers(config.expectedDirectInput,scope) : null;\n  let accepted;\n  const loadAccepted = () => {\n    const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n    if (fixed) checkAmazonFixedBaseline(snapshot,expectedOffers);\n    accepted = new Map(snapshot.products.map(row => [row.product_key,row]));\n    return accepted;\n  };\n  const mapped = amazonProducts(rows,loadAccepted,expectedOffers,keywordScope);\n  if (!fixed && !mapped.products.length && !mapped.currencyIssues.length && !mapped.sourceConflicts.length) fail('No qualified priced products; preserve the last good feed and mark it stale.');\n  if (pinnedKeyword && mapped.products.length > keywordScope.maxProducts) fail('Qualified search-card count exceeds the pinned result cap.');\n  const previous = accepted ?? loadAccepted();\n  const incremental = amazonIncremental(mapped.products,previous,config.maxRows,keywordScope);\n  const observedCardPriceChanges = [];\n  if (pinnedKeyword) {\n    for (const row of incremental.delta.products) {\n      const prior = previous.get(row.product_key);\n      if (!prior || prior.currency !== row.currency || decimalIdentity(prior.price) === decimalIdentity(row.price)) continue;\n      observedCardPriceChanges.push({\n        product_key:row.product_key, currency:row.currency,\n        previous_price:prior.price, current_price:row.price,\n        previous_scraped_at:prior.scraped_at, current_scraped_at:row.scraped_at,\n      });\n    }\n  }\n  const issues = [...incremental.review_issues,...mapped.currencyIssues,...mapped.sourceConflicts];\n  const coverage = fixed ? amazonFixedCoverage(scope,mapped.products,[...issues,...mapped.scopeIssues]) : null;\n  return {...reviewEnvelope(run,'amazon-prices',config),source_dataset_complete:true,source_rows:rows.length,\n    source_products:mapped.products,rejected_rows:mapped.rejected_rows,...incremental,\n    stats:{...incremental.stats,currency_mismatches_suppressed:mapped.currencyIssues.length,\n      source_conflicts_suppressed:mapped.sourceConflicts.length},\n    review_issues:issues,\n    observation_key_fields:['product_key','scraped_at'],last_good_feed_policy:'upsert_qualified_observations_keep_missing_keys',\n    product_coverage_complete:null,coverage_note:pinnedKeyword ?\n      'These are observed search-card prices for the pinned input. Market coverage, rank and same-seller comparisons remain unverified.' :\n      'Reading every dataset row does not prove all requested products returned.',\n    ...(fixed ? {fixed_product_coverage:coverage,fixed_scope_review_issues:mapped.scopeIssues} : {}),\n    ...(pinnedKeyword ? {keyword_scope_verified:true,keyword_scope_review_issues:mapped.scopeIssues,\n      observed_card_price_changes:observedCardPriceChanges} : {})};\n}\n\n/* Scope checks for repeat reviews of the same native Contact CRM batch. */\nconst CONTACT_ACTOR_ID = 'bHzVpEmytvDNJk48m';\nconst CONTACT_INPUT_FIELDS = [\n  'urls','maxWebsites','maxPagesPerSite','includeSubpages','detectTechStack','validatePhones',\n  'verifyEmails','deepEmailVerification','maxEmailsToVerify','exportCrm','crmRequireMx',\n  'crmMxReservePerSite','enableAiAnalysis','proxyConfiguration',\n];\nconst CONTACT_DORMANT_DEFAULTS = {\n  startUrls:[], domains:[], url:'', website:'', outputConnectors:[], connectorAlertTarget:'',\n  llmProvider:'openrouter', llmModel:'',\n};\nconst CONTACT_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nfunction contactCompanyKey(host) {\n  if (typeof host !== 'string') return '';\n  const name = host.toLowerCase().replace(/\\.$/,'');\n  const parts = name.split('.');\n  if (name.length > 253 || parts.length < 2 || !/[a-z]/.test(parts.at(-1)) ||\n      !parts.every(part => CONTACT_HOST_LABEL.test(part))) return '';\n  const key = name.replace(/^www\\./,'');\n  return key.includes('.') ? key : '';\n}\n\nfunction contactTargetCompany(url) {\n  if (typeof url !== 'string' || /[\\s\\\\#\\p{Cc}]/u.test(url)) return '';\n  const match = /^https?:\\/\\/([a-z0-9.-]+)(?::([0-9]{1,5}))?(?:[/?][^#]*)?$/i.exec(url);\n  if (!match || (match[2] && (Number(match[2]) < 1 || Number(match[2]) > 65535))) return '';\n  return contactCompanyKey(match[1]);\n}\n\nfunction readContactFixedInput(input, label) {\n  if (!object(input) || Object.entries(input).some(([key,value]) =>\n      !CONTACT_INPUT_FIELDS.includes(key) && (!Object.hasOwn(CONTACT_DORMANT_DEFAULTS,key) ||\n        JSON.stringify(value) !== JSON.stringify(CONTACT_DORMANT_DEFAULTS[key])))) {\n    fail(label+' Contact input has unsupported settings.');\n  }\n  const {urls,maxWebsites,maxPagesPerSite,includeSubpages,verifyEmails,proxyConfiguration} = input;\n  const requireMx = Object.hasOwn(input,'crmRequireMx') ? input.crmRequireMx : false;\n  const reserveMx = Object.hasOwn(input,'crmMxReservePerSite') ? input.crmMxReservePerSite : false;\n  const maxMx = Object.hasOwn(input,'maxEmailsToVerify') ? input.maxEmailsToVerify : null;\n  if (!Array.isArray(urls) || urls.length < 1 || urls.length > 200 || maxWebsites !== urls.length ||\n      !Number.isInteger(maxPagesPerSite) || maxPagesPerSite < 1 || maxPagesPerSite > 20 ||\n      typeof includeSubpages !== 'boolean') fail(label+' Contact input needs explicit targets and crawl limits.');\n  const keys = urls.map(contactTargetCompany);\n  if (keys.includes('') || new Set(keys).size !== keys.length) {\n    fail(label+' Contact input needs one valid HTTP(S) URL per company.');\n  }\n  if (input.exportCrm !== true || ['detectTechStack','validatePhones','deepEmailVerification','enableAiAnalysis']\n      .some(field => input[field] !== false) || typeof verifyEmails !== 'boolean' || requireMx !== verifyEmails ||\n      typeof reserveMx !== 'boolean' || (!requireMx && reserveMx) ||\n      (requireMx && (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500)) ||\n      (!requireMx && Object.hasOwn(input,'maxEmailsToVerify') &&\n        (!Number.isInteger(maxMx) || maxMx < 1 || maxMx > 500))) {\n    fail(label+' Contact input must use supported basic or MX-only CRM export settings.');\n  }\n  if (!object(proxyConfiguration) || proxyConfiguration.useApifyProxy !== true || Object.keys(proxyConfiguration)\n      .some(key => !['useApifyProxy','apifyProxyGroups','apifyProxyCountry'].includes(key))) {\n    fail(label+' Contact input needs explicit Apify Proxy settings.');\n  }\n  const proxyGroups = Object.hasOwn(proxyConfiguration,'apifyProxyGroups') ? proxyConfiguration.apifyProxyGroups : [];\n  const proxyCountry = Object.hasOwn(proxyConfiguration,'apifyProxyCountry') ? proxyConfiguration.apifyProxyCountry : '';\n  if (!Array.isArray(proxyGroups) || !proxyGroups.every(group => typeof group === 'string' && /^[A-Z0-9_]+$/.test(group)) ||\n      typeof proxyCountry !== 'string' || (proxyCountry !== '' && !/^[A-Z]{2}$/.test(proxyCountry))) {\n    fail(label+' Contact input has unsupported proxy settings.');\n  }\n  return {\n    schema_version:1, urls:[...urls], planned_company_keys:keys, max_websites:maxWebsites,\n    max_pages_per_site:maxPagesPerSite, include_subpages:includeSubpages, require_mx:requireMx,\n    max_mx_checks:requireMx ? maxMx : null, reserve_mx_per_site:reserveMx,\n    proxy_groups:[...proxyGroups], proxy_country:proxyCountry,\n  };\n}\n\nfunction checkContactCohortRows(snapshot,scope,label,{native = false} = {}) {\n  if (!object(snapshot) || !Array.isArray(snapshot.companies) || !Array.isArray(snapshot.contacts)) {\n    fail(label+' has no usable CRM rows.');\n  }\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  const observed = new Set();\n  for (const company of snapshot.companies) {\n    const key = contactCompanyKey(company?.company_key);\n    if (!planned.has(key) || observed.has(key) || company.website !== planned.get(key)) {\n      fail(label+' company is outside the pinned Contact cohort or is duplicated.');\n    }\n    observed.add(key);\n  }\n  for (const contact of snapshot.contacts) {\n    const key = contactTargetCompany(contact?.source_url);\n    const company = contactCompanyKey(contact?.company_key);\n    const eligible = scope.require_mx\n      ? ['mx_medium_mailbox_unknown','mx_high_mailbox_unknown'].includes(contact?.email_status)\n      : contact?.email_status === 'published_unverified';\n    if (!observed.has(key) || contact.source_url !== planned.get(key) || !eligible ||\n        (native && typeof contact.company_key !== 'string') || (contact.company_key && company !== key)) {\n      fail(label+' contact is outside the pinned Contact cohort or verification mode.');\n    }\n  }\n  return observed;\n}\n\nfunction validateContactReviewConfig(config) {\n  validateConfig(config);\n  if (config.contactReviewMode === undefined || config.contactReviewMode === 'single_run') return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || config.expectedActorId !== CONTACT_ACTOR_ID) {\n    fail('Choose single_run or use fixed_cohort with the HarvestLab Contact Actor.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const previous = validateSnapshot(config.previousSnapshot,config.maxRows);\n  const acceptedScope = config.previousSnapshot.contact_scope;\n  if ((acceptedScope !== undefined || previous.companies.length || previous.contacts.length) &&\n      (!object(acceptedScope) || stable(acceptedScope) !== stable(scope))) {\n    fail('Accepted baseline does not match the pinned Contact cohort.');\n  }\n  checkContactCohortRows(previous,scope,'Accepted baseline');\n  return config;\n}\n\nfunction validateContactRunScope(config,currentInput) {\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  const current = readContactFixedInput(currentInput,'Run');\n  if (stable(expected) !== stable(current)) fail('Saved INPUT differs from the pinned Contact cohort or settings.');\n  return expected;\n}\n\nfunction validateContactRunManifest(manifest,config,scope) {\n  validateManifest(manifest,config.maxRows);\n  if (scope && (manifest.require_mx !== scope.require_mx || manifest.requested_sites !== scope.urls.length ||\n      manifest.source_rows > scope.urls.length)) {\n    fail('CRM manifest does not match the pinned Contact cohort or verification mode.');\n  }\n  return manifest;\n}\n\nfunction reviewContactRun(payload,manifest,config,run,scope) {\n  if (config.contactReviewMode !== 'fixed_cohort') return crmHandoff(payload,manifest,config,run);\n  if (!scope) fail('Saved INPUT was not checked against the pinned Contact cohort.');\n  validateContactRunManifest(manifest,config,scope);\n  const observed = checkContactCohortRows(payload,scope,'Current CRM export',{native:true});\n  const result = crmHandoff(payload,manifest,config,run);\n  const planned = scope.planned_company_keys;\n  const absent = planned.filter(key => !observed.has(key));\n  result.candidate_baseline.contact_scope = scope;\n  result.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete', planned_company_count:planned.length,\n    observed_company_count:observed.size, absent_company_count:absent.length,\n    planned_company_keys:planned, observed_company_keys:planned.filter(key => observed.has(key)), absent_company_keys:absent,\n  };\n  return result;\n}\n\n/* Review one completed retry against its exact checked Contact pilot cohort. */\nconst CONTACT_RETRY_COHORT_SITES = 25;\nconst CONTACT_RETRY_SOURCE_TYPES = new Set(['contact_data','partial_result','fetch_failed']);\n\nfunction contactRefreshBounds(window) {\n  if (!object(window) || ![window.startDate,window.endDate].every(day =>\n      typeof day === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(day))) {\n    fail('Set an explicit UTC start and end date for the Contact refresh.');\n  }\n  const start = sourceTime(window.startDate+'T00:00:00Z','Contact refresh');\n  const end = sourceTime(window.endDate+'T23:59:59.999999Z','Contact refresh');\n  if (end < start) fail('Contact refresh end date precedes its start date.');\n  return {start,end};\n}\n\nfunction validateContactRetryConfig(config) {\n  validateContactReviewConfig(config);\n  if (config.retryRunId == null && config.contactRefreshWindow == null) return config;\n  if (config.contactReviewMode !== 'fixed_cohort' || !validId(config.retryRunId) || config.retryRunId === config.runId) {\n    fail('Set one distinct completed retry run ID in fixed_cohort mode.');\n  }\n  const scope = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!scope.require_mx || scope.urls.length !== CONTACT_RETRY_COHORT_SITES) {\n    fail('The paired Contact review requires the checked-only 25-site cohort.');\n  }\n  contactRefreshBounds(config.contactRefreshWindow);\n  return config;\n}\n\nfunction checkContactRetryRunPair(original,retry,config) {\n  if (!object(original) || !object(retry) || !validId(config.retryRunId) || config.retryRunId === config.runId ||\n      original.runId !== config.runId || retry.runId !== config.retryRunId ||\n      original.actorId !== CONTACT_ACTOR_ID || retry.actorId !== CONTACT_ACTOR_ID ||\n      ![original.datasetId,retry.datasetId,original.storeId,retry.storeId].every(validId) ||\n      original.datasetId === retry.datasetId || original.storeId === retry.storeId) {\n    fail('Original and retry Contact run or default storage identities conflict.');\n  }\n  const {start,end} = contactRefreshBounds(config.contactRefreshWindow);\n  const [originalStart,originalEnd,retryStart,retryEnd] = [original.startedAt,original.finishedAt,retry.startedAt,retry.finishedAt]\n    .map(value => sourceTime(value,'Contact run'));\n  if (start > originalStart || originalStart > originalEnd || originalEnd > retryStart || retryStart > retryEnd || retryEnd > end) {\n    fail('Contact runs must finish in order within the same UTC refresh window.');\n  }\n}\n\nfunction validateContactRetryRun(retryResponse,originalResponse,config) {\n  validateContactRetryConfig(config);\n  const original = {...validateRun(originalResponse,config),\n    startedAt:originalResponse.data.startedAt,finishedAt:originalResponse.data.finishedAt};\n  const retry = {...validateRun(retryResponse,{...config,runId:config.retryRunId}),\n    startedAt:retryResponse.data.startedAt,finishedAt:retryResponse.data.finishedAt};\n  checkContactRetryRunPair(original,retry,config);\n  return retry;\n}\n\nfunction checkContactRetryPayload(payload,manifest,scope,config,label) {\n  const validated = validateSnapshot(payload,config.maxRows,true);\n  if (validated.companies.length !== manifest.exported_companies || validated.contacts.length !== manifest.exported_contacts) {\n    fail(label+' CRM payload does not match its completion manifest.');\n  }\n  return checkContactCohortRows(validated,scope,label+' CRM export',{native:true});\n}\n\nfunction checkContactRetryScope(retry,original,observed) {\n  if (!object(retry) || !Array.isArray(retry.planned_company_keys)) fail('Retry Contact scope is missing.');\n  const selected = new Set(retry.planned_company_keys);\n  if (!selected.size || selected.size !== retry.planned_company_keys.length ||\n      retry.planned_company_keys.some(key => observed.has(key) || !original.planned_company_keys.includes(key))) {\n    fail('Retry must target distinct companies absent from the original Contact export.');\n  }\n  const domains = original.planned_company_keys.filter(key => selected.has(key));\n  const urls = original.urls.filter((_,index) => selected.has(original.planned_company_keys[index]));\n  const expected = {...original,urls,planned_company_keys:domains,max_websites:urls.length,\n    max_mx_checks:Math.min(original.max_mx_checks,urls.length)};\n  if (stable(retry) !== stable(expected)) fail('Retry saved INPUT differs from the permitted Contact URLs, order or settings.');\n}\n\nfunction validateContactRetryInput(rawRetryInput,originalUpserts,originalManifest,scope,config) {\n  validateContactRetryConfig(config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(scope) || stable(scope) !== stable(expected)) fail('Original Contact scope differs from the pinned cohort.');\n  validateContactRunManifest(originalManifest,config,scope);\n  const observed = checkContactRetryPayload(originalUpserts,originalManifest,scope,config,'Original');\n  const retry = readContactFixedInput(rawRetryInput,'Retry');\n  checkContactRetryScope(retry,scope,observed);\n  return retry;\n}\n\nfunction validateContactRetryManifest(manifest,config,scope) {\n  if (!object(scope) || !Array.isArray(scope.urls) || !scope.urls.length || scope.require_mx !== true) {\n    fail('Verified checked-only Contact retry scope is missing.');\n  }\n  if (manifest?.exported_companies === 0) {\n    const files = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\n    if (manifest.status !== 'complete' || manifest.replace_existing_data !== false || manifest.delete_missing_records !== false ||\n        manifest.exported_contacts !== 0 || !Number.isInteger(manifest.source_rows) || manifest.source_rows < 0 ||\n        manifest.persisted_site_rows !== manifest.source_rows || manifest.source_rows > config.maxRows ||\n        !Array.isArray(manifest.files) || manifest.files.length !== files.length || !files.every(name => manifest.files.includes(name))) {\n      fail('Empty Contact retry must have a complete native manifest.');\n    }\n  } else {\n    validateManifest(manifest,config.maxRows);\n  }\n  if (manifest.require_mx !== true || manifest.requested_sites !== scope.urls.length || manifest.source_rows > scope.urls.length) {\n    fail('Contact retry manifest does not match its verified scope.');\n  }\n  return manifest;\n}\n\nfunction contactRetryDataset(pages,scope,run,config) {\n  const rows = datasetRows(pages,config);\n  const start = sourceTime(run.startedAt,'Contact run'), end = sourceTime(run.finishedAt,'Contact run');\n  const planned = new Map(scope.planned_company_keys.map((key,index) => [key,\n    scope.urls[index].replace(/^https?:/i,scheme => scheme.toLowerCase())]));\n  for (const row of rows) {\n    if (!CONTACT_RETRY_SOURCE_TYPES.has(row?.result_type)) continue;\n    const observed = sourceTime(row.scraped_at,'Contact dataset');\n    // Native rows timestamped to the second can fall in the run's opening second.\n    const earliest = /T\\d{2}:\\d{2}:\\d{2}(?:Z|[+-])/.test(row.scraped_at) ? start - (start % 1_000_000n) : start;\n    if (planned.get(contactCompanyKey(row.domain)) !== row.url || typeof row.url !== 'string' ||\n        observed < earliest || observed > end) {\n      fail('Contact dataset contains a source row outside its run scope or time range.');\n    }\n  }\n  return rows;\n}\n\nfunction reviewContactWithRetry({config,originalRun,retryRun,originalScope,retryScope,originalManifest,retryManifest,\n    originalUpserts,retryUpserts,originalPages,retryPages}) {\n  validateContactRetryConfig(config);\n  checkContactRetryRunPair(originalRun,retryRun,config);\n  const expected = readContactFixedInput(config.expectedContactInput,'Pinned');\n  if (!object(originalScope) || stable(originalScope) !== stable(expected)) {\n    fail('Original Contact scope differs from the pinned cohort.');\n  }\n  validateContactRunManifest(originalManifest,config,originalScope);\n  const observedOriginal = checkContactRetryPayload(originalUpserts,originalManifest,originalScope,config,'Original');\n  checkContactRetryScope(retryScope,originalScope,observedOriginal);\n  validateContactRetryManifest(retryManifest,config,retryScope);\n  const observedRetry = checkContactRetryPayload(retryUpserts,retryManifest,retryScope,config,'Retry');\n  const originalRows = contactRetryDataset(originalPages,originalScope,originalRun,config);\n  const retryRows = contactRetryDataset(retryPages,retryScope,retryRun,config);\n  if (originalRows.length + retryRows.length > config.maxRows) fail('Combined Contact dataset exceeds maxRows.');\n  const observations = verifyContactCrmDatasetCompanions([originalUpserts,retryUpserts],[\n    {manifest:originalManifest,dataset:originalRows},{manifest:retryManifest,dataset:retryRows},\n  ]);\n  const selected = [...originalUpserts.contacts,...retryUpserts.contacts];\n  const held = new Set();\n  for (const contact of selected) {\n    const sources = observations.get(contact.contact_key);\n    if (new Set(sources?.map(source => contactCompanyKey(source.companyKey))).size > 1) held.add(contact.contact_key);\n  }\n  const contacts = selected.filter(contact => !held.has(contact.contact_key));\n  const companies = [...originalUpserts.companies,...retryUpserts.companies];\n  const rows = originalManifest.source_rows + retryManifest.source_rows;\n  // Each real manifest has already been verified. This count record is internal to the merge.\n  const merged = crmHandoff({...originalUpserts,companies,contacts},{...originalManifest,\n    exported_companies:companies.length,exported_contacts:contacts.length,persisted_site_rows:rows,source_rows:rows},config,originalRun);\n  const planned = originalScope.planned_company_keys;\n  const observed = new Set([...observedOriginal,...observedRetry]);\n  const absent = planned.filter(key => !observed.has(key));\n  const qualified = new Set(contacts.filter(contact => contact.company_key).map(contact => contactCompanyKey(contact.company_key)));\n  merged.candidate_baseline.contact_scope = originalScope;\n  merged.handoff_id += ':'+retryRun.runId;\n  merged.source_retry_run_id = retryRun.runId;\n  merged.acknowledgement_binding.required = [\n    'source_run_id','source_retry_run_id','accepted_baseline_reference','exact_delta_and_candidate_payload',\n  ];\n  merged.contact_refresh_window = {startDate:config.contactRefreshWindow.startDate,endDate:config.contactRefreshWindow.endDate};\n  merged.review_issues.push(...[...held].sort().map(record_key => ({\n    record_type:'contacts',record_key,reason:'cross_run_ambiguous_company_association',\n  })));\n  merged.fixed_cohort_coverage = {\n    status:absent.length ? 'partial' : 'complete',planned_company_count:planned.length,\n    observed_company_count:observed.size,absent_company_count:absent.length,\n    planned_company_keys:planned,observed_company_keys:planned.filter(key => observed.has(key)),absent_company_keys:absent,\n    original_observed_company_count:observedOriginal.size,retry_observed_company_count:observedRetry.size,\n    current_mx_qualified_company_count:qualified.size,held_contact_count:held.size,\n    original_post_crawl_interruption:Object.hasOwn(originalManifest,'post_crawl_interruption'),\n    retry_post_crawl_interruption:Object.hasOwn(retryManifest,'post_crawl_interruption'),\n  };\n  return merged;\n}\n\n/* Reconcile checked-only native exports before a Contact MX handoff. */\nconst CONTACT_COMPANION_MAX_SITES = 200;\nconst CONTACT_COMPANION_CRM_FILES = ['CRM-companies.csv','CRM-contacts.csv','CRM-upserts.json'];\nconst CONTACT_COMPANION_SOURCE_TYPES = new Set(['contact_data','partial_result','fetch_failed']);\nconst CONTACT_COMPANION_DIAGNOSTIC_TYPES = new Set(['no_results','blocked','site_timeout','site_error','site_skipped']);\nconst CONTACT_COMPANION_EMAIL = /^[^\\p{White_Space}\\u001c-\\u001f@,;]+@[^\\p{White_Space}\\u001c-\\u001f@,;]+\\.[^\\p{White_Space}\\u001c-\\u001f@,;]+$/u;\nconst CONTACT_COMPANION_TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,6})?(?:Z|[+-]\\d{2}:\\d{2})$/;\nconst CONTACT_COMPANION_ERROR = 'Match every native CRM export with its complete checked-only MX manifest and full default dataset JSON from the same run.';\n\nfunction requireContactCompanionMatch(value) {\n  if (!value) fail(CONTACT_COMPANION_ERROR);\n}\n\nfunction contactCompanionText(value) {\n  return value.replace(/^[\\p{White_Space}\\u001c-\\u001f]+|[\\p{White_Space}\\u001c-\\u001f]+$/gu,'');\n}\n\nfunction contactCompanionEmail(value) {\n  const email = contactCompanionText(value).toLowerCase();\n  return CONTACT_COMPANION_EMAIL.test(email) ? email : '';\n}\n\nfunction isContactCompanionTime(value) {\n  const fields = typeof value === 'string' && CONTACT_COMPANION_TIME.exec(value);\n  if (!fields) return false;\n  const [,year,month,day] = fields.map(Number);\n  return year >= 1970 && month >= 1 && month <= 12 && day >= 1 &&\n    day <= new Date(Date.UTC(year,month,0)).getUTCDate() && Number.isFinite(Date.parse(fields[0]));\n}\n\nfunction readContactCompanionIdentity(row) {\n  requireContactCompanionMatch(typeof row.domain === 'string' && typeof row.url === 'string' && isContactCompanionTime(row.scraped_at));\n  const companyKey = contactCompanionText(row.domain).toLowerCase().replace(/^www\\./,'');\n  const url = contactCompanionText(row.url);\n  // n8n's Code sandbox has no URL global. The paired review accepts the fixed cohort's supported HTTP(S) targets.\n  const host = /^https?:\\/\\/([a-z0-9.-]+)(?=[:/?]|$)/i.exec(url)?.[1];\n  requireContactCompanionMatch(contactTargetCompany(url) && host?.toLowerCase().replace(/^www\\./,'') === companyKey);\n  return {companyKey,url,observedAt:row.scraped_at};\n}\n\nfunction contactCompanionMxCandidates(row) {\n  requireContactCompanionMatch(row.billable_contact_found === true && !row.diagnostic_item && !row.block_detected && !row.error &&\n    (row.ai_contact_analysis == null || (object(row.ai_contact_analysis) && !Object.keys(row.ai_contact_analysis).length)) &&\n    Array.isArray(row.emails) && row.emails.every(email => typeof email === 'string') && Array.isArray(row.emails_verified));\n  const checks = new Map();\n  for (const check of row.emails_verified) {\n    requireContactCompanionMatch(object(check) && typeof check.email === 'string' && typeof check.deliverability === 'string' &&\n      (typeof check.mx_valid === 'boolean' || (check.mx_valid === null && check.deliverability === 'UNKNOWN')) &&\n      (check.disposable == null || typeof check.disposable === 'boolean') &&\n      (check.typo_suggestion == null || typeof check.typo_suggestion === 'string') &&\n      (check.smtp_probe == null || object(check.smtp_probe)));\n    const email = contactCompanionEmail(check.email);\n    requireContactCompanionMatch(email);\n    // The Actor uses the last check for each normalized email.\n    checks.set(email,check);\n  }\n  const eligible = new Map();\n  for (const email of new Set(row.emails.map(contactCompanionEmail))) {\n    if (!email) continue;\n    const check = checks.get(email);\n    if (!check) continue;\n    const grade = contactCompanionText(check.deliverability);\n    if (check.mx_valid !== true || (grade !== 'HIGH' && grade !== 'MEDIUM') || check.disposable || check.typo_suggestion) continue;\n    const verdict = check.smtp_probe?.result;\n    if (verdict === 'undeliverable') continue;\n    requireContactCompanionMatch(verdict !== 'deliverable');\n    eligible.set(email,grade);\n  }\n  return eligible;\n}\n\nfunction reconcileContactCompanionDataset(rawExport,manifest,dataset) {\n  requireContactCompanionMatch(object(rawExport) && rawExport.merge_policy === MERGE_POLICY &&\n    rawExport.full_snapshot === false && rawExport.allow_deletions === false &&\n    rawExport.contact_selection === 'one_eligible_email_per_company_source_row' &&\n    rawExport.association_policy === 'preserve_existing_on_empty_review_ambiguous' &&\n    Array.isArray(rawExport.companies) && Array.isArray(rawExport.contacts) &&\n    rawExport.companies.length <= CONTACT_COMPANION_MAX_SITES && rawExport.contacts.length <= rawExport.companies.length);\n  requireContactCompanionMatch(object(manifest) && manifest.status === 'complete' && manifest.require_mx === true &&\n    manifest.replace_existing_data === false && manifest.delete_missing_records === false &&\n    Array.isArray(manifest.files) && manifest.files.length === CONTACT_COMPANION_CRM_FILES.length &&\n    CONTACT_COMPANION_CRM_FILES.every(name => manifest.files.includes(name)) && Number.isInteger(manifest.requested_sites) &&\n    manifest.requested_sites >= 1 && manifest.requested_sites <= CONTACT_COMPANION_MAX_SITES &&\n    Array.isArray(dataset) && dataset.length <= 2 * manifest.requested_sites + 1);\n\n  const sourceCompanies = new Map();\n  const persistedDomains = new Set();\n  const observations = new Map();\n  const selected = new Map();\n  let eligibleCount = 0;\n  let selectedCount = 0;\n  for (const row of dataset) {\n    requireContactCompanionMatch(object(row) && typeof row.result_type === 'string' &&\n      (CONTACT_COMPANION_SOURCE_TYPES.has(row.result_type) || CONTACT_COMPANION_DIAGNOSTIC_TYPES.has(row.result_type)));\n    if (!CONTACT_COMPANION_SOURCE_TYPES.has(row.result_type)) {\n      requireContactCompanionMatch(row.diagnostic_item === true && row.billable_contact_found === false);\n      continue;\n    }\n    const identity = readContactCompanionIdentity(row);\n    requireContactCompanionMatch(!persistedDomains.has(identity.companyKey));\n    persistedDomains.add(identity.companyKey);\n    if (row.result_type !== 'contact_data') {\n      requireContactCompanionMatch(row.billable_contact_found === false);\n      continue;\n    }\n    const eligible = contactCompanionMxCandidates(row);\n    sourceCompanies.set(identity.companyKey,identity);\n    eligibleCount += eligible.size;\n    for (const email of eligible.keys()) {\n      const domains = observations.get(email);\n      if (domains) domains.push(identity.companyKey);\n      else observations.set(email,[identity.companyKey]);\n    }\n    const selection = eligible.entries().next().value;\n    if (!selection) continue;\n    selectedCount++;\n    const [email,grade] = selection;\n    const prior = selected.get(email);\n    if (!prior || (grade === 'HIGH' && prior.grade === 'MEDIUM')) selected.set(email,{...identity,grade});\n  }\n\n  const seenCompanies = new Set();\n  requireContactCompanionMatch(rawExport.companies.length === sourceCompanies.size);\n  for (const company of rawExport.companies) {\n    requireContactCompanionMatch(object(company) && typeof company.company_key === 'string' && !seenCompanies.has(company.company_key));\n    const source = sourceCompanies.get(company.company_key);\n    requireContactCompanionMatch(source && company.domain === source.companyKey && company.website === source.url && company.scraped_at === source.observedAt);\n    seenCompanies.add(company.company_key);\n  }\n\n  const seenContacts = new Set();\n  let ambiguousCount = 0;\n  requireContactCompanionMatch(rawExport.contacts.length === selected.size);\n  for (const contact of rawExport.contacts) {\n    requireContactCompanionMatch(object(contact) && typeof contact.contact_key === 'string' && !seenContacts.has(contact.contact_key));\n    const source = selected.get(contact.contact_key);\n    const domains = observations.get(contact.contact_key);\n    requireContactCompanionMatch(source && domains && contact.email === contact.contact_key && contact.source_url === source.url &&\n      contact.scraped_at === source.observedAt && contact.email_status === `mx_${source.grade.toLowerCase()}_mailbox_unknown`);\n    const ambiguous = domains.length > 1;\n    requireContactCompanionMatch(contact.company_key === (ambiguous ? '' : source.companyKey));\n    if (ambiguous) ambiguousCount++;\n    seenContacts.add(contact.contact_key);\n  }\n\n  const counts = {\n    persisted_site_rows:persistedDomains.size,source_rows:persistedDomains.size,\n    rejected_source_rows:persistedDomains.size-sourceCompanies.size,input_company_records:sourceCompanies.size,\n    input_selected_contacts:selectedCount,company_only_source_rows:sourceCompanies.size-selectedCount,\n    eligible_email_candidates:eligibleCount,unselected_eligible_emails:eligibleCount-selectedCount,\n    exported_companies:sourceCompanies.size,exported_contacts:selected.size,company_records_deduplicated:0,\n    contact_records_deduplicated:selectedCount-selected.size,ambiguous_contact_associations:ambiguousCount,\n  };\n  requireContactCompanionMatch(persistedDomains.size <= manifest.requested_sites &&\n    Object.entries(counts).every(([field,count]) => manifest[field] === count));\n  return observations;\n}\n\n/** Inspect each file using trusted same-run storage and scope from the paired workflow. */\nfunction verifyContactCrmDatasetCompanions(nativeExports,companions) {\n  requireContactCompanionMatch(Array.isArray(nativeExports) && Array.isArray(companions) &&\n    nativeExports.length > 0 && nativeExports.length === companions.length);\n  const observations = new Map();\n  for (const [index,nativeExport] of nativeExports.entries()) {\n    const companion = companions[index];\n    requireContactCompanionMatch(object(companion));\n    const local = reconcileContactCompanionDataset(nativeExport,companion.manifest,companion.dataset);\n    for (const [email,companies] of local) {\n      const matched = companies.map(companyKey => ({fileIndex:index+1,companyKey}));\n      const existing = observations.get(email);\n      if (existing) existing.push(...matched);\n      else observations.set(email,matched);\n    }\n  }\n  return observations;\n}\n\nconst config = $('Configure existing run').first().json;\nconst {startedAt,finishedAt} = $('Read existing run').first().json.data;\nconst originalRun = {...$('Verify succeeded run').first().json,startedAt,finishedAt};\nreturn [{json:reviewContactWithRetry({config,originalRun,retryRun:$('Verify retry run').first().json,originalScope:$('Verify Contact cohort').first().json,retryScope:$('Verify retry scope').first().json,originalManifest:$('Verify CRM manifest').first().json,retryManifest:$('Verify retry CRM manifest').first().json,originalUpserts:$('Read native CRM upserts').first().json,retryUpserts:$('Read retry CRM upserts').first().json,originalPages:$('Bind original Contact dataset pages').first().json.pages,retryPages:$input.all().map(item=>item.json)})}];"
      }
    },
    {
      "id": "81b1fcad-9318-5471-a704-7381bbd582e2",
      "name": "Destination adapter placeholder - disabled",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4840,
        200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "throw new Error('Replace this placeholder only after buyer-authorized destination testing. No write or acknowledgement implementation is supplied.');"
      },
      "disabled": true
    },
    {
      "id": "dde80570-7351-58aa-ad44-c7c46634699b",
      "name": "Read before running",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -120
      ],
      "parameters": {
        "content": "## Existing-run review handoff\nInactive, manual only. Set an exact completed run ID and private HTTP Header Auth on each GET.\nContact requires exportCrm=true on that already completed run. Use fixed_cohort to pin the same ordered Contact URLs and settings with expectedContactInput. For the checked-only 25-site workflow, add one retryRunId and a UTC contactRefreshWindow to review both runs. Use single_run to review native CRM files without pinning a cohort. Baseline is explicit private input. Acknowledgement must bind run, baseline revision and exact payload.\nNo Actor is started, no destination is written, and no baseline is advanced. Disabled adapter is a placeholder, not a working integration.\nSee examples/n8n/README.md. Treat execution previews as private data.",
        "height": 240,
        "width": 800
      }
    }
  ],
  "connections": {
    "Manual review": {
      "main": [
        [
          {
            "node": "Configure existing run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Configure existing run": {
      "main": [
        [
          {
            "node": "Read existing run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read existing run": {
      "main": [
        [
          {
            "node": "Verify succeeded run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify succeeded run": {
      "main": [
        [
          {
            "node": "Pinned Contact cohort?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pinned Contact cohort?": {
      "main": [
        [
          {
            "node": "Read saved Contact input",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read CRM manifest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read saved Contact input": {
      "main": [
        [
          {
            "node": "Verify Contact cohort",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify Contact cohort": {
      "main": [
        [
          {
            "node": "Read CRM manifest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read CRM manifest": {
      "main": [
        [
          {
            "node": "Verify CRM manifest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify CRM manifest": {
      "main": [
        [
          {
            "node": "Read native CRM upserts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read native CRM upserts": {
      "main": [
        [
          {
            "node": "Review a Contact retry?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Review a Contact retry?": {
      "main": [
        [
          {
            "node": "Read retry run",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Review CRM changes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Review CRM changes": {
      "main": [
        [
          {
            "node": "Destination adapter placeholder - disabled",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read retry run": {
      "main": [
        [
          {
            "node": "Verify retry run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify retry run": {
      "main": [
        [
          {
            "node": "Read saved retry input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read saved retry input": {
      "main": [
        [
          {
            "node": "Verify retry scope",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify retry scope": {
      "main": [
        [
          {
            "node": "Read retry CRM manifest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read retry CRM manifest": {
      "main": [
        [
          {
            "node": "Verify retry CRM manifest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify retry CRM manifest": {
      "main": [
        [
          {
            "node": "Read retry CRM upserts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read retry CRM upserts": {
      "main": [
        [
          {
            "node": "Read original Contact dataset pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read original Contact dataset pages": {
      "main": [
        [
          {
            "node": "Bind original Contact dataset pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Bind original Contact dataset pages": {
      "main": [
        [
          {
            "node": "Read retry Contact dataset pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read retry Contact dataset pages": {
      "main": [
        [
          {
            "node": "Review original plus retry",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Review original plus retry": {
      "main": [
        [
          {
            "node": "Destination adapter placeholder - disabled",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "executionTimeout": 300,
    "saveManualExecutions": false,
    "saveExecutionProgress": false,
    "saveDataErrorExecution": "none",
    "saveDataSuccessExecution": "none"
  },
  "pinData": {},
  "tags": []
}
