{
  "name": "HarvestLab Amazon qualified price observations - 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\": \"JyRjxUswjrRheOdmh\",\n  \"maxRows\": 1000,\n  \"pageSize\": 100,\n  \"baselineReference\": \"initial-empty\",\n  \"previousSnapshot\": {\n    \"schema_version\": 1,\n    \"policy\": \"retain_last_good_per_product_key\",\n    \"products\": []\n  },\n  \"amazonReviewMode\": \"single_run\",\n  \"expectedDirectInput\": null,\n  \"expectedKeywordInput\": null,\n  \"sellerRebaseline\": 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_KEYWORD_PRICE_BASIS = 'unmarked_search_card';\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|gp\\/aw\\/d|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 (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(asin)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_asin_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]) => {\n      if (!Object.hasOwn(scope,key)) return false;\n      const current = scope[key];\n      return Array.isArray(value)\n        ? Array.isArray(current) && current.length === value.length && value.every((entry,index) => current[index] === entry)\n        : current === value;\n    });\n}\n\nfunction amazonKeywordTargetCoverage(scope,products) {\n  const planned = scope.keywordAsins.map(asin => scope.marketplace+':'+asin);\n  const observed = new Set(products.map(row => row.product_key));\n  return {\n    planned_product_keys:planned,\n    qualified_price_keys:planned.filter(key => observed.has(key)),\n    missing_price_keys:planned.filter(key => !observed.has(key)),\n  };\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    const allowedFields = keywordScope ? [...AMAZON_FIELDS,'price_basis'] : AMAZON_FIELDS;\n    if (!object(row) || Object.keys(row).some(key => !allowedFields.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'price_basis') && row.price_basis !== AMAZON_KEYWORD_PRICE_BASIS) fail('Unknown Amazon keyword baseline price basis.');\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    if (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(row.asin)) fail('The accepted keyword baseline contains an ASIN outside its target list.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key);\n    products.push(Object.hasOwn(row,'price_basis') ? {...qualified[0],price_basis:row.price_basis} : 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  const targetCoverage = keywordScope?.keywordAsins ? amazonKeywordTargetCoverage(keywordScope,mapped.products) : null;\n  const heldTargetRefresh = targetCoverage !== null && !mapped.products.length;\n  if (!fixed && !heldTargetRefresh && !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    ...(targetCoverage ? {keyword_target_coverage:targetCoverage} : {}),\n    ...(heldTargetRefresh ? {delivery_status:'HELD_NO_QUALIFIED_PRICES',candidate_baseline:null,\n      acknowledgement_required:false,coverage_note:'No target ASIN has a qualified price in the supplied dataset. Keep the previously accepted snapshot.'} : {})};\n}\n\n/* Amazon pinned input reviews. Compiled into the Amazon configuration and scope nodes. */\n\nconst AMAZON_FIXED_COUNTRIES = {\n  'amazon.com':'US', 'amazon.ca':'CA', 'amazon.com.mx':'MX', 'amazon.com.br':'BR',\n  'amazon.co.uk':'GB', 'amazon.de':'DE', 'amazon.fr':'FR', 'amazon.es':'ES', 'amazon.it':'IT',\n  'amazon.nl':'NL', 'amazon.pl':'PL', 'amazon.se':'SE', 'amazon.co.jp':'JP', 'amazon.in':'IN',\n  'amazon.com.au':'AU', 'amazon.ae':'AE', 'amazon.sa':'SA', 'amazon.sg':'SG', 'amazon.com.tr':'TR',\n};\nconst AMAZON_FIXED_INPUT_FIELDS = [\n  'productUrls','amazonDomain','maxProducts','fetchDetails','trackBestsellerRank','enableAiAnalysis','proxyConfiguration',\n];\n// Some saved runs include default values for disabled optional features.\nconst AMAZON_DORMANT_DEFAULTS = {\n  searchQuery:'',sortBy:'relevance',alertRankThreshold:50,alertWebhookUrl:'',connectorAlertTarget:'',\n  outputConnectors:[],llmProvider:'openrouter',\n};\nconst AMAZON_FIXED_PROXY_FIELDS = ['useApifyProxy','apifyProxyGroups','apifyProxyCountry'];\nconst AMAZON_KEYWORD_FIELDS = [\n  'searchQuery','amazonDomain','maxProducts','sortBy','fetchDetails','trackBestsellerRank','enableAiAnalysis','proxyConfiguration',\n];\nconst AMAZON_KEYWORD_TARGET_FIELDS = ['keywordAsins','keywordScanPages'];\nconst AMAZON_KEYWORD_DORMANT_DEFAULTS = {...AMAZON_DORMANT_DEFAULTS,productUrls:[]};\nconst AMAZON_KEYWORD_SORTS = ['relevance','price_low','price_high','avg_review','newest'];\nconst AMAZON_DIRECT_PRODUCT_PATH = /^\\/(?:dp|gp\\/product|product|(?!(?:s|search|gp|dp|product)\\/)[^/]+\\/dp)\\/([a-z0-9]{10})(?=\\/|$)/i;\nconst AMAZON_DOT_SEGMENT = /(?:^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/i;\n\nfunction readAmazonFixedInput(input, label) {\n  if (!object(input) || !AMAZON_FIXED_INPUT_FIELDS.every(field => Object.hasOwn(input,field)) ||\n      Object.entries(input).some(([field,value]) => !AMAZON_FIXED_INPUT_FIELDS.includes(field) &&\n        (!Object.hasOwn(AMAZON_DORMANT_DEFAULTS,field) || JSON.stringify(value) !== JSON.stringify(AMAZON_DORMANT_DEFAULTS[field])))) {\n    fail(label+' Amazon input must use the fixed direct-price fields without aliases or extra settings.');\n  }\n  const {productUrls,amazonDomain,maxProducts,fetchDetails,trackBestsellerRank,enableAiAnalysis,proxyConfiguration} = input;\n  if (typeof amazonDomain !== 'string' || !MARKET.test(amazonDomain)) fail(label+' Amazon marketplace is unsupported.');\n  if (!Array.isArray(productUrls) || !Number.isInteger(maxProducts) ||\n      productUrls.length < 1 || productUrls.length > maxProducts || maxProducts > 100) {\n    fail(label+' Amazon input needs one to 100 product URLs and a cap that includes every URL.');\n  }\n  if (typeof fetchDetails !== 'boolean' || trackBestsellerRank !== false || enableAiAnalysis !== false) {\n    fail(label+' Amazon input needs an explicit detail setting with rank tracking and AI off.');\n  }\n  if (!object(proxyConfiguration) || Object.keys(proxyConfiguration).length !== AMAZON_FIXED_PROXY_FIELDS.length ||\n      !AMAZON_FIXED_PROXY_FIELDS.every(field => Object.hasOwn(proxyConfiguration,field)) ||\n      proxyConfiguration.useApifyProxy !== true || !Array.isArray(proxyConfiguration.apifyProxyGroups) ||\n      proxyConfiguration.apifyProxyGroups.length !== 1 || proxyConfiguration.apifyProxyGroups[0] !== 'RESIDENTIAL' ||\n      proxyConfiguration.apifyProxyCountry !== AMAZON_FIXED_COUNTRIES[amazonDomain]) {\n    fail(label+' Amazon input must use a residential proxy in the selected marketplace country.');\n  }\n\n  const keys = new Set();\n  for (const [index,productUrl] of productUrls.entries()) {\n    const url = typeof productUrl === 'string' && /^[A-Za-z0-9]{10}$/.test(productUrl)\n      ? 'https://www.' + amazonDomain + '/dp/' + productUrl.toUpperCase() : productUrl;\n    const parts = typeof url === 'string' && !/[\\s\\\\,#\\p{Cc}]/u.test(url) && /^https:\\/\\/([^/?#]+)(\\/[^?#]*)/i.exec(url);\n    const host = parts ? parts[1].toLowerCase() : '';\n    const path = parts ? parts[2] : '';\n    const product = AMAZON_DIRECT_PRODUCT_PATH.exec(path);\n    if (!product || (host !== amazonDomain && host !== 'www.'+amazonDomain) || AMAZON_DOT_SEGMENT.test(path)) {\n      fail(label+' Amazon product URL '+(index+1)+' must be an unambiguous HTTPS product page in the selected marketplace.');\n    }\n    const asin = product[1].toUpperCase();\n    if ([...path.matchAll(/\\/(?:dp|gp\\/product|product)\\/([a-z0-9]{10})(?=\\/|$)/gi)].some(match => match[1].toUpperCase() !== asin)) {\n      fail(label+' Amazon product URL '+(index+1)+' has conflicting product identities.');\n    }\n    const key = amazonDomain+':'+asin;\n    if (keys.has(key)) fail(label+' Amazon input repeats a product identity.');\n    keys.add(key);\n  }\n  return {marketplace:amazonDomain,plannedProductKeys:[...keys]};\n}\n\nfunction validateAmazonFixedScope(expectedDirectInput,currentInput) {\n  const expected = readAmazonFixedInput(expectedDirectInput,'Pinned');\n  const current = readAmazonFixedInput(currentInput,'Run');\n  if (expected.marketplace !== current.marketplace ||\n      expectedDirectInput.maxProducts !== currentInput.maxProducts ||\n      expectedDirectInput.fetchDetails !== currentInput.fetchDetails ||\n      expectedDirectInput.productUrls.length !== currentInput.productUrls.length ||\n      expectedDirectInput.productUrls.some((url,index) => url !== currentInput.productUrls[index])) {\n    fail('The Amazon run input does not match the pinned marketplace, product URLs or settings.');\n  }\n  return expected;\n}\n\nfunction amazonFixedOffers(input,scope) {\n  return new Map(scope.plannedProductKeys.map((key,index) => [key,amazonOfferQuery(input.productUrls[index])]));\n}\n\nfunction checkAmazonFixedBaseline(snapshot,expectedOffers) {\n  if (snapshot.products.some(row => expectedOffers.get(row.product_key) !== amazonOfferQuery(row.url))) {\n    fail('The accepted baseline contains a product or offer outside the fixed input. Choose the matching baseline.');\n  }\n}\n\nfunction readAmazonKeywordInput(input,label) {\n  if (!object(input) || !AMAZON_KEYWORD_FIELDS.every(field => Object.hasOwn(input,field)) ||\n      Object.entries(input).some(([field,value]) => !AMAZON_KEYWORD_FIELDS.includes(field) &&\n        !AMAZON_KEYWORD_TARGET_FIELDS.includes(field) &&\n        (!Object.hasOwn(AMAZON_KEYWORD_DORMANT_DEFAULTS,field) ||\n          JSON.stringify(value) !== JSON.stringify(AMAZON_KEYWORD_DORMANT_DEFAULTS[field])))) {\n    fail(label+' Amazon input must use supported keyword fields with no extra settings or credentials.');\n  }\n  const {searchQuery,amazonDomain,maxProducts,sortBy,fetchDetails,trackBestsellerRank,enableAiAnalysis,proxyConfiguration} = input;\n  if (!text(searchQuery) || searchQuery !== searchQuery.trim() || searchQuery.length > 500 || /\\p{Cc}/u.test(searchQuery) ||\n      typeof amazonDomain !== 'string' || !MARKET.test(amazonDomain) || !AMAZON_KEYWORD_SORTS.includes(sortBy) ||\n      !Number.isInteger(maxProducts) || maxProducts < 1 || maxProducts > 100 ||\n      fetchDetails !== false || trackBestsellerRank !== false || enableAiAnalysis !== false) {\n    fail(label+' Amazon keyword input needs a supported search, market, sort and cap with details, rank tracking and AI off.');\n  }\n  if (!object(proxyConfiguration) || Object.keys(proxyConfiguration).some(field => !AMAZON_FIXED_PROXY_FIELDS.includes(field)) ||\n      proxyConfiguration.useApifyProxy !== true || !Array.isArray(proxyConfiguration.apifyProxyGroups) ||\n      proxyConfiguration.apifyProxyGroups.length !== 1 || proxyConfiguration.apifyProxyGroups[0] !== 'RESIDENTIAL' ||\n      (Object.hasOwn(proxyConfiguration,'apifyProxyCountry') && proxyConfiguration.apifyProxyCountry !== AMAZON_FIXED_COUNTRIES[amazonDomain])) {\n    fail(label+' Amazon keyword input needs the selected marketplace\u2019s residential proxy.');\n  }\n  const scope = {searchQuery,marketplace:amazonDomain,maxProducts,sortBy,proxyCountry:proxyConfiguration.apifyProxyCountry ?? null};\n  const {keywordAsins} = input;\n  if (!Object.hasOwn(input,'keywordAsins')) {\n    if (Object.hasOwn(input,'keywordScanPages')) fail(label+' Amazon keyword scan limit requires a target ASIN list.');\n    return scope;\n  }\n  const keywordScanPages = Object.hasOwn(input,'keywordScanPages') ? input.keywordScanPages : 1;\n  if (!Array.isArray(keywordAsins) || keywordAsins.length < 1 || keywordAsins.length > 100 ||\n      keywordAsins.some(asin => typeof asin !== 'string' || asin.length !== 10 || !/^[A-Z0-9]{10}$/.test(asin)) ||\n      new Set(keywordAsins).size !== keywordAsins.length ||\n      !Number.isInteger(keywordScanPages) || keywordScanPages < 1 || keywordScanPages > 3) {\n    fail(label+' Amazon keyword targets need one to 100 distinct uppercase ASINs and a limit of one to three search pages.');\n  }\n  return {...scope,keywordAsins:[...keywordAsins].sort(),keywordScanPages};\n}\n\nfunction validateAmazonKeywordScope(expectedKeywordInput,currentInput) {\n  const expected = readAmazonKeywordInput(expectedKeywordInput,'Pinned');\n  const current = readAmazonKeywordInput(currentInput,'Run');\n  if (!matchesAmazonKeywordScope(current,expected)) fail('The Amazon run input does not match the pinned keyword or search settings.');\n  return expected;\n}\n\nfunction validateAmazonRunScope(config,currentInput) {\n  if (config.amazonReviewMode === 'pinned_keyword') return validateAmazonKeywordScope(config.expectedKeywordInput,currentInput);\n  return validateAmazonFixedScope(config.expectedDirectInput,currentInput);\n}\n\nfunction amazonSellerObservation(row) {\n  return {seller:row.seller,price:row.price,scrapedAt:row.scraped_at};\n}\n\nfunction isAmazonSellerObservation(observation) {\n  return object(observation) && Object.keys(observation).length === 3 && !!text(observation.seller) &&\n    typeof observation.price === 'string' && Number.isFinite(Number(observation.price)) && Number(observation.price) > 0 &&\n    typeof observation.scrapedAt === 'string';\n}\n\nfunction sameAmazonSellerObservation(approved,observed) {\n  return isAmazonSellerObservation(approved) && approved.seller === observed.seller &&\n    approved.price === observed.price && approved.scrapedAt === observed.scrapedAt;\n}\n\nfunction hasGenericAmazonSellerIdentity(row,marketplace,asin) {\n  if (row.amazon_domain != null && row.amazon_domain !== '' && row.amazon_domain !== marketplace) return false;\n  if (amazonSource(row,asin)?.marketplace !== marketplace) return false;\n  return [row.url,row.product_url].filter(url => url != null && url !== '').every(url => {\n    if (typeof url !== 'string' || /[\\s\\\\\\p{Cc}]/u.test(url)) return false;\n    const path = /^https?:\\/\\/[^/?#]+(\\/[^?#]*)/i.exec(url)?.[1] ?? '';\n    return !AMAZON_DOT_SEGMENT.test(path) && AMAZON_DIRECT_PRODUCT_PATH.exec(path)?.[1].toUpperCase() === asin &&\n      !amazonOfferQuery(url);\n  });\n}\n\nfunction hasUnambiguousAmazonSellerSource(rows,observed) {\n  const observedTime = sourceTime(observed.scraped_at);\n  const sameTime = new Set();\n  for (const row of rows) {\n    if (!object(row) || text(row.asin).toUpperCase() !== observed.asin) continue;\n    if (!hasGenericAmazonSellerIdentity(row,observed.marketplace,observed.asin) ||\n        text(row.currency).toUpperCase() !== observed.currency) return false;\n    const {scraped_at,...fields} = row;\n    let time;\n    try {\n      time = sourceTime(scraped_at);\n    } catch {\n      return false;\n    }\n    if (time > observedTime) return false;\n    if (time === observedTime) sameTime.add(stable(fields));\n  }\n  return sameTime.size === 1;\n}\n\nfunction validateAmazonSellerRebaseline(config,snapshot,scope) {\n  const approval = config.sellerRebaseline;\n  if (!object(approval) || Object.keys(approval).length !== 5 || approval.runId !== config.runId ||\n      approval.baselineReference !== config.baselineReference || !scope.plannedProductKeys.includes(approval.productKey) ||\n      !isAmazonSellerObservation(approval.previous) || !isAmazonSellerObservation(approval.observed)) {\n    fail('Use one seller rebaseline option for this run, accepted revision and fixed product.');\n  }\n  const previous = snapshot.products.find(row => row.product_key === approval.productKey);\n  if (!previous || !sameAmazonSellerObservation(approval.previous,amazonSellerObservation(previous)) ||\n      amazonSellerName(approval.previous.seller) === amazonSellerName(approval.observed.seller) ||\n      sourceTime(approval.observed.scrapedAt) <= sourceTime(approval.previous.scrapedAt)) {\n    fail('The seller rebaseline approval must match the accepted observation and name a newer different seller.');\n  }\n  if (!hasGenericAmazonSellerIdentity(previous,scope.marketplace,previous.asin)) {\n    fail('Seller rebaseline requires a generic Amazon product URL without an offer selector.');\n  }\n}\n\nfunction validateAmazonReviewConfig(config) {\n  validateConfig(config);\n  if (config.sellerRebaseline != null && config.amazonReviewMode !== 'fixed_products') {\n    fail('Seller rebaseline is only available for fixed Amazon products.');\n  }\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if (pinnedKeyword ? config.expectedDirectInput != null : config.expectedKeywordInput != null) {\n    fail('Set only the expected input for the selected Amazon review mode.');\n  }\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n  switch (config.amazonReviewMode) {\n    case 'fixed_products': {\n      const scope = validateAmazonFixedScope(config.expectedDirectInput,config.expectedDirectInput);\n      checkAmazonFixedBaseline(snapshot,amazonFixedOffers(config.expectedDirectInput,scope));\n      if (config.sellerRebaseline != null) validateAmazonSellerRebaseline(config,snapshot,scope);\n      break;\n    }\n    case 'single_run':\n      if (snapshot.products.length) fail('Choose fixed_products, pinned_keyword or discovery to review a run against an accepted baseline.');\n      if (config.expectedDirectInput !== null) fail('Set expectedDirectInput only in fixed_products mode.');\n      break;\n    case 'discovery':\n      if (config.expectedDirectInput !== null) fail('Set expectedDirectInput only in fixed_products mode.');\n      break;\n    case 'pinned_keyword':\n      break;\n    default:\n      fail('Choose single_run, fixed_products, pinned_keyword or discovery for Amazon review.');\n  }\n  return config;\n}\n\nfunction amazonFixedCoverage(scope,products,issues) {\n  const returned = new Set(products.map(row => row.product_key));\n  const held = new Set(issues.map(issue => issue.product_key));\n  const pending = scope.plannedProductKeys.filter(key => !returned.has(key) || held.has(key));\n  return {\n    complete:pending.length === 0 && issues.length === 0,\n    planned:scope.plannedProductKeys.length,\n    qualified:scope.plannedProductKeys.length - pending.length,\n    pending_product_keys:pending,\n  };\n}\n\nfunction reviewAmazonRun(pages,config,run,scope) {\n  if (run.runId !== config.runId || run.actorId !== config.expectedActorId) fail('Use the verified Amazon run for this review.');\n  const review = amazonHandoff(pages,config,run,scope);\n  if (config.amazonReviewMode !== 'fixed_products') return review;\n\n  const observedByKey = new Map(review.source_products.map(row => [row.product_key,row]));\n  const candidate = review.candidate_baseline.products;\n  const acceptedByKey = new Map(candidate.map(row => [row.product_key,row]));\n  const blocked = new Set([...review.review_issues.filter(issue => issue.reason !== 'seller_changed'),\n    ...review.fixed_scope_review_issues].map(issue => issue.product_key));\n  const rows = pages.flatMap(page => page.body);\n  const options = [];\n  for (const issue of review.review_issues) {\n    if (issue.reason !== 'seller_changed' || blocked.has(issue.product_key)) continue;\n    const productKey = issue.product_key;\n    const previous = acceptedByKey.get(productKey);\n    const observed = observedByKey.get(productKey);\n    if (!previous?.seller || !observed?.seller || previous.currency !== observed.currency ||\n        sourceTime(observed.scraped_at) <= sourceTime(previous.scraped_at) ||\n        !hasGenericAmazonSellerIdentity(previous,scope.marketplace,observed.asin) ||\n        !hasUnambiguousAmazonSellerSource(rows,observed)) continue;\n    options.push({runId:run.runId,baselineReference:config.baselineReference,productKey,\n      previous:amazonSellerObservation(previous),observed:amazonSellerObservation(observed)});\n  }\n  review.seller_rebaseline_options = options;\n\n  const approval = config.sellerRebaseline;\n  if (approval == null) return review;\n  const option = options.find(option => option.productKey === approval.productKey);\n  if (!option || option.runId !== approval.runId || option.baselineReference !== approval.baselineReference ||\n      !sameAmazonSellerObservation(approval.previous,option.previous) ||\n      !sameAmazonSellerObservation(approval.observed,option.observed)) {\n    review.seller_rebaseline = {status:'held',product_key:approval.productKey,reason:'approved_observation_unavailable'};\n    return review;\n  }\n\n  // Seller transitions start a new baseline and remain outside comparable price coverage and delta.\n  review.candidate_baseline.products = candidate.map(row =>\n    row.product_key === option.productKey ? observedByKey.get(option.productKey) : row);\n  review.seller_rebaseline_options = options.filter(item => item.productKey !== option.productKey);\n  const {previous,observed} = option;\n  review.seller_rebaseline = {status:'proposed',product_key:option.productKey,\n    previous:{seller:previous.seller,price:previous.price,scraped_at:previous.scrapedAt},\n    observed:{seller:observed.seller,price:observed.price,scraped_at:observed.scrapedAt}};\n  return review;\n}\n\nreturn [{json:validateAmazonReviewConfig(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|gp\\/aw\\/d|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 (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(asin)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_asin_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]) => {\n      if (!Object.hasOwn(scope,key)) return false;\n      const current = scope[key];\n      return Array.isArray(value)\n        ? Array.isArray(current) && current.length === value.length && value.every((entry,index) => current[index] === entry)\n        : current === value;\n    });\n}\n\nfunction amazonKeywordTargetCoverage(scope,products) {\n  const planned = scope.keywordAsins.map(asin => scope.marketplace+':'+asin);\n  const observed = new Set(products.map(row => row.product_key));\n  return {\n    planned_product_keys:planned,\n    qualified_price_keys:planned.filter(key => observed.has(key)),\n    missing_price_keys:planned.filter(key => !observed.has(key)),\n  };\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    if (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(row.asin)) fail('The accepted keyword baseline contains an ASIN outside its target list.');\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  const targetCoverage = keywordScope?.keywordAsins ? amazonKeywordTargetCoverage(keywordScope,mapped.products) : null;\n  const heldTargetRefresh = targetCoverage !== null && !mapped.products.length;\n  if (!fixed && !heldTargetRefresh && !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    ...(targetCoverage ? {keyword_target_coverage:targetCoverage} : {}),\n    ...(heldTargetRefresh ? {delivery_status:'HELD_NO_QUALIFIED_PRICES',candidate_baseline:null,\n      acknowledgement_required:false,coverage_note:'No target ASIN has a qualified price in the supplied dataset. Keep the previously accepted snapshot.'} : {})};\n}\n\nreturn [{json:validateRun($input.first().json,$('Configure existing run').first().json)}];"
      }
    },
    {
      "id": "1c07db4a-c82b-5cef-9865-f0e454257cd6",
      "name": "Pinned input review?",
      "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.amazonReviewMode }}",
              "rightValue": "fixed_products",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "leftValue": "={{ $('Configure existing run').first().json.amazonReviewMode }}",
              "rightValue": "pinned_keyword",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "or"
        },
        "options": {
          "ignoreCase": false
        }
      }
    },
    {
      "id": "cecc26e3-39ad-57a3-84a1-cc12508af27e",
      "name": "Read saved run 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": "de34c009-28c7-558c-943a-1dfbe88363f5",
      "name": "Verify pinned input scope",
      "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|gp\\/aw\\/d|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 (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(asin)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_asin_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]) => {\n      if (!Object.hasOwn(scope,key)) return false;\n      const current = scope[key];\n      return Array.isArray(value)\n        ? Array.isArray(current) && current.length === value.length && value.every((entry,index) => current[index] === entry)\n        : current === value;\n    });\n}\n\nfunction amazonKeywordTargetCoverage(scope,products) {\n  const planned = scope.keywordAsins.map(asin => scope.marketplace+':'+asin);\n  const observed = new Set(products.map(row => row.product_key));\n  return {\n    planned_product_keys:planned,\n    qualified_price_keys:planned.filter(key => observed.has(key)),\n    missing_price_keys:planned.filter(key => !observed.has(key)),\n  };\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    if (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(row.asin)) fail('The accepted keyword baseline contains an ASIN outside its target list.');\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  const targetCoverage = keywordScope?.keywordAsins ? amazonKeywordTargetCoverage(keywordScope,mapped.products) : null;\n  const heldTargetRefresh = targetCoverage !== null && !mapped.products.length;\n  if (!fixed && !heldTargetRefresh && !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    ...(targetCoverage ? {keyword_target_coverage:targetCoverage} : {}),\n    ...(heldTargetRefresh ? {delivery_status:'HELD_NO_QUALIFIED_PRICES',candidate_baseline:null,\n      acknowledgement_required:false,coverage_note:'No target ASIN has a qualified price in the supplied dataset. Keep the previously accepted snapshot.'} : {})};\n}\n\n/* Amazon pinned input reviews. Compiled into the Amazon configuration and scope nodes. */\n\nconst AMAZON_FIXED_COUNTRIES = {\n  'amazon.com':'US', 'amazon.ca':'CA', 'amazon.com.mx':'MX', 'amazon.com.br':'BR',\n  'amazon.co.uk':'GB', 'amazon.de':'DE', 'amazon.fr':'FR', 'amazon.es':'ES', 'amazon.it':'IT',\n  'amazon.nl':'NL', 'amazon.pl':'PL', 'amazon.se':'SE', 'amazon.co.jp':'JP', 'amazon.in':'IN',\n  'amazon.com.au':'AU', 'amazon.ae':'AE', 'amazon.sa':'SA', 'amazon.sg':'SG', 'amazon.com.tr':'TR',\n};\nconst AMAZON_FIXED_INPUT_FIELDS = [\n  'productUrls','amazonDomain','maxProducts','fetchDetails','trackBestsellerRank','enableAiAnalysis','proxyConfiguration',\n];\n// Some saved runs include default values for disabled optional features.\nconst AMAZON_DORMANT_DEFAULTS = {\n  searchQuery:'',sortBy:'relevance',alertRankThreshold:50,alertWebhookUrl:'',connectorAlertTarget:'',\n  outputConnectors:[],llmProvider:'openrouter',\n};\nconst AMAZON_FIXED_PROXY_FIELDS = ['useApifyProxy','apifyProxyGroups','apifyProxyCountry'];\nconst AMAZON_KEYWORD_FIELDS = [\n  'searchQuery','amazonDomain','maxProducts','sortBy','fetchDetails','trackBestsellerRank','enableAiAnalysis','proxyConfiguration',\n];\nconst AMAZON_KEYWORD_TARGET_FIELDS = ['keywordAsins','keywordScanPages'];\nconst AMAZON_KEYWORD_DORMANT_DEFAULTS = {...AMAZON_DORMANT_DEFAULTS,productUrls:[]};\nconst AMAZON_KEYWORD_SORTS = ['relevance','price_low','price_high','avg_review','newest'];\nconst AMAZON_DIRECT_PRODUCT_PATH = /^\\/(?:dp|gp\\/product|product|(?!(?:s|search|gp|dp|product)\\/)[^/]+\\/dp)\\/([a-z0-9]{10})(?=\\/|$)/i;\nconst AMAZON_DOT_SEGMENT = /(?:^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/i;\n\nfunction readAmazonFixedInput(input, label) {\n  if (!object(input) || !AMAZON_FIXED_INPUT_FIELDS.every(field => Object.hasOwn(input,field)) ||\n      Object.entries(input).some(([field,value]) => !AMAZON_FIXED_INPUT_FIELDS.includes(field) &&\n        (!Object.hasOwn(AMAZON_DORMANT_DEFAULTS,field) || JSON.stringify(value) !== JSON.stringify(AMAZON_DORMANT_DEFAULTS[field])))) {\n    fail(label+' Amazon input must use the fixed direct-price fields without aliases or extra settings.');\n  }\n  const {productUrls,amazonDomain,maxProducts,fetchDetails,trackBestsellerRank,enableAiAnalysis,proxyConfiguration} = input;\n  if (typeof amazonDomain !== 'string' || !MARKET.test(amazonDomain)) fail(label+' Amazon marketplace is unsupported.');\n  if (!Array.isArray(productUrls) || !Number.isInteger(maxProducts) ||\n      productUrls.length < 1 || productUrls.length > maxProducts || maxProducts > 100) {\n    fail(label+' Amazon input needs one to 100 product URLs and a cap that includes every URL.');\n  }\n  if (typeof fetchDetails !== 'boolean' || trackBestsellerRank !== false || enableAiAnalysis !== false) {\n    fail(label+' Amazon input needs an explicit detail setting with rank tracking and AI off.');\n  }\n  if (!object(proxyConfiguration) || Object.keys(proxyConfiguration).length !== AMAZON_FIXED_PROXY_FIELDS.length ||\n      !AMAZON_FIXED_PROXY_FIELDS.every(field => Object.hasOwn(proxyConfiguration,field)) ||\n      proxyConfiguration.useApifyProxy !== true || !Array.isArray(proxyConfiguration.apifyProxyGroups) ||\n      proxyConfiguration.apifyProxyGroups.length !== 1 || proxyConfiguration.apifyProxyGroups[0] !== 'RESIDENTIAL' ||\n      proxyConfiguration.apifyProxyCountry !== AMAZON_FIXED_COUNTRIES[amazonDomain]) {\n    fail(label+' Amazon input must use a residential proxy in the selected marketplace country.');\n  }\n\n  const keys = new Set();\n  for (const [index,productUrl] of productUrls.entries()) {\n    const url = typeof productUrl === 'string' && /^[A-Za-z0-9]{10}$/.test(productUrl)\n      ? 'https://www.' + amazonDomain + '/dp/' + productUrl.toUpperCase() : productUrl;\n    const parts = typeof url === 'string' && !/[\\s\\\\,#\\p{Cc}]/u.test(url) && /^https:\\/\\/([^/?#]+)(\\/[^?#]*)/i.exec(url);\n    const host = parts ? parts[1].toLowerCase() : '';\n    const path = parts ? parts[2] : '';\n    const product = AMAZON_DIRECT_PRODUCT_PATH.exec(path);\n    if (!product || (host !== amazonDomain && host !== 'www.'+amazonDomain) || AMAZON_DOT_SEGMENT.test(path)) {\n      fail(label+' Amazon product URL '+(index+1)+' must be an unambiguous HTTPS product page in the selected marketplace.');\n    }\n    const asin = product[1].toUpperCase();\n    if ([...path.matchAll(/\\/(?:dp|gp\\/product|product)\\/([a-z0-9]{10})(?=\\/|$)/gi)].some(match => match[1].toUpperCase() !== asin)) {\n      fail(label+' Amazon product URL '+(index+1)+' has conflicting product identities.');\n    }\n    const key = amazonDomain+':'+asin;\n    if (keys.has(key)) fail(label+' Amazon input repeats a product identity.');\n    keys.add(key);\n  }\n  return {marketplace:amazonDomain,plannedProductKeys:[...keys]};\n}\n\nfunction validateAmazonFixedScope(expectedDirectInput,currentInput) {\n  const expected = readAmazonFixedInput(expectedDirectInput,'Pinned');\n  const current = readAmazonFixedInput(currentInput,'Run');\n  if (expected.marketplace !== current.marketplace ||\n      expectedDirectInput.maxProducts !== currentInput.maxProducts ||\n      expectedDirectInput.fetchDetails !== currentInput.fetchDetails ||\n      expectedDirectInput.productUrls.length !== currentInput.productUrls.length ||\n      expectedDirectInput.productUrls.some((url,index) => url !== currentInput.productUrls[index])) {\n    fail('The Amazon run input does not match the pinned marketplace, product URLs or settings.');\n  }\n  return expected;\n}\n\nfunction amazonFixedOffers(input,scope) {\n  return new Map(scope.plannedProductKeys.map((key,index) => [key,amazonOfferQuery(input.productUrls[index])]));\n}\n\nfunction checkAmazonFixedBaseline(snapshot,expectedOffers) {\n  if (snapshot.products.some(row => expectedOffers.get(row.product_key) !== amazonOfferQuery(row.url))) {\n    fail('The accepted baseline contains a product or offer outside the fixed input. Choose the matching baseline.');\n  }\n}\n\nfunction readAmazonKeywordInput(input,label) {\n  if (!object(input) || !AMAZON_KEYWORD_FIELDS.every(field => Object.hasOwn(input,field)) ||\n      Object.entries(input).some(([field,value]) => !AMAZON_KEYWORD_FIELDS.includes(field) &&\n        !AMAZON_KEYWORD_TARGET_FIELDS.includes(field) &&\n        (!Object.hasOwn(AMAZON_KEYWORD_DORMANT_DEFAULTS,field) ||\n          JSON.stringify(value) !== JSON.stringify(AMAZON_KEYWORD_DORMANT_DEFAULTS[field])))) {\n    fail(label+' Amazon input must use supported keyword fields with no extra settings or credentials.');\n  }\n  const {searchQuery,amazonDomain,maxProducts,sortBy,fetchDetails,trackBestsellerRank,enableAiAnalysis,proxyConfiguration} = input;\n  if (!text(searchQuery) || searchQuery !== searchQuery.trim() || searchQuery.length > 500 || /\\p{Cc}/u.test(searchQuery) ||\n      typeof amazonDomain !== 'string' || !MARKET.test(amazonDomain) || !AMAZON_KEYWORD_SORTS.includes(sortBy) ||\n      !Number.isInteger(maxProducts) || maxProducts < 1 || maxProducts > 100 ||\n      fetchDetails !== false || trackBestsellerRank !== false || enableAiAnalysis !== false) {\n    fail(label+' Amazon keyword input needs a supported search, market, sort and cap with details, rank tracking and AI off.');\n  }\n  if (!object(proxyConfiguration) || Object.keys(proxyConfiguration).some(field => !AMAZON_FIXED_PROXY_FIELDS.includes(field)) ||\n      proxyConfiguration.useApifyProxy !== true || !Array.isArray(proxyConfiguration.apifyProxyGroups) ||\n      proxyConfiguration.apifyProxyGroups.length !== 1 || proxyConfiguration.apifyProxyGroups[0] !== 'RESIDENTIAL' ||\n      (Object.hasOwn(proxyConfiguration,'apifyProxyCountry') && proxyConfiguration.apifyProxyCountry !== AMAZON_FIXED_COUNTRIES[amazonDomain])) {\n    fail(label+' Amazon keyword input needs the selected marketplace\u2019s residential proxy.');\n  }\n  const scope = {searchQuery,marketplace:amazonDomain,maxProducts,sortBy,proxyCountry:proxyConfiguration.apifyProxyCountry ?? null};\n  const {keywordAsins} = input;\n  if (!Object.hasOwn(input,'keywordAsins')) {\n    if (Object.hasOwn(input,'keywordScanPages')) fail(label+' Amazon keyword scan limit requires a target ASIN list.');\n    return scope;\n  }\n  const keywordScanPages = Object.hasOwn(input,'keywordScanPages') ? input.keywordScanPages : 1;\n  if (!Array.isArray(keywordAsins) || keywordAsins.length < 1 || keywordAsins.length > 100 ||\n      keywordAsins.some(asin => typeof asin !== 'string' || asin.length !== 10 || !/^[A-Z0-9]{10}$/.test(asin)) ||\n      new Set(keywordAsins).size !== keywordAsins.length ||\n      !Number.isInteger(keywordScanPages) || keywordScanPages < 1 || keywordScanPages > 3) {\n    fail(label+' Amazon keyword targets need one to 100 distinct uppercase ASINs and a limit of one to three search pages.');\n  }\n  return {...scope,keywordAsins:[...keywordAsins].sort(),keywordScanPages};\n}\n\nfunction validateAmazonKeywordScope(expectedKeywordInput,currentInput) {\n  const expected = readAmazonKeywordInput(expectedKeywordInput,'Pinned');\n  const current = readAmazonKeywordInput(currentInput,'Run');\n  if (!matchesAmazonKeywordScope(current,expected)) fail('The Amazon run input does not match the pinned keyword or search settings.');\n  return expected;\n}\n\nfunction validateAmazonRunScope(config,currentInput) {\n  if (config.amazonReviewMode === 'pinned_keyword') return validateAmazonKeywordScope(config.expectedKeywordInput,currentInput);\n  return validateAmazonFixedScope(config.expectedDirectInput,currentInput);\n}\n\nfunction amazonSellerObservation(row) {\n  return {seller:row.seller,price:row.price,scrapedAt:row.scraped_at};\n}\n\nfunction isAmazonSellerObservation(observation) {\n  return object(observation) && Object.keys(observation).length === 3 && !!text(observation.seller) &&\n    typeof observation.price === 'string' && Number.isFinite(Number(observation.price)) && Number(observation.price) > 0 &&\n    typeof observation.scrapedAt === 'string';\n}\n\nfunction sameAmazonSellerObservation(approved,observed) {\n  return isAmazonSellerObservation(approved) && approved.seller === observed.seller &&\n    approved.price === observed.price && approved.scrapedAt === observed.scrapedAt;\n}\n\nfunction hasGenericAmazonSellerIdentity(row,marketplace,asin) {\n  if (row.amazon_domain != null && row.amazon_domain !== '' && row.amazon_domain !== marketplace) return false;\n  if (amazonSource(row,asin)?.marketplace !== marketplace) return false;\n  return [row.url,row.product_url].filter(url => url != null && url !== '').every(url => {\n    if (typeof url !== 'string' || /[\\s\\\\\\p{Cc}]/u.test(url)) return false;\n    const path = /^https?:\\/\\/[^/?#]+(\\/[^?#]*)/i.exec(url)?.[1] ?? '';\n    return !AMAZON_DOT_SEGMENT.test(path) && AMAZON_DIRECT_PRODUCT_PATH.exec(path)?.[1].toUpperCase() === asin &&\n      !amazonOfferQuery(url);\n  });\n}\n\nfunction hasUnambiguousAmazonSellerSource(rows,observed) {\n  const observedTime = sourceTime(observed.scraped_at);\n  const sameTime = new Set();\n  for (const row of rows) {\n    if (!object(row) || text(row.asin).toUpperCase() !== observed.asin) continue;\n    if (!hasGenericAmazonSellerIdentity(row,observed.marketplace,observed.asin) ||\n        text(row.currency).toUpperCase() !== observed.currency) return false;\n    const {scraped_at,...fields} = row;\n    let time;\n    try {\n      time = sourceTime(scraped_at);\n    } catch {\n      return false;\n    }\n    if (time > observedTime) return false;\n    if (time === observedTime) sameTime.add(stable(fields));\n  }\n  return sameTime.size === 1;\n}\n\nfunction validateAmazonSellerRebaseline(config,snapshot,scope) {\n  const approval = config.sellerRebaseline;\n  if (!object(approval) || Object.keys(approval).length !== 5 || approval.runId !== config.runId ||\n      approval.baselineReference !== config.baselineReference || !scope.plannedProductKeys.includes(approval.productKey) ||\n      !isAmazonSellerObservation(approval.previous) || !isAmazonSellerObservation(approval.observed)) {\n    fail('Use one seller rebaseline option for this run, accepted revision and fixed product.');\n  }\n  const previous = snapshot.products.find(row => row.product_key === approval.productKey);\n  if (!previous || !sameAmazonSellerObservation(approval.previous,amazonSellerObservation(previous)) ||\n      amazonSellerName(approval.previous.seller) === amazonSellerName(approval.observed.seller) ||\n      sourceTime(approval.observed.scrapedAt) <= sourceTime(approval.previous.scrapedAt)) {\n    fail('The seller rebaseline approval must match the accepted observation and name a newer different seller.');\n  }\n  if (!hasGenericAmazonSellerIdentity(previous,scope.marketplace,previous.asin)) {\n    fail('Seller rebaseline requires a generic Amazon product URL without an offer selector.');\n  }\n}\n\nfunction validateAmazonReviewConfig(config) {\n  validateConfig(config);\n  if (config.sellerRebaseline != null && config.amazonReviewMode !== 'fixed_products') {\n    fail('Seller rebaseline is only available for fixed Amazon products.');\n  }\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if (pinnedKeyword ? config.expectedDirectInput != null : config.expectedKeywordInput != null) {\n    fail('Set only the expected input for the selected Amazon review mode.');\n  }\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n  switch (config.amazonReviewMode) {\n    case 'fixed_products': {\n      const scope = validateAmazonFixedScope(config.expectedDirectInput,config.expectedDirectInput);\n      checkAmazonFixedBaseline(snapshot,amazonFixedOffers(config.expectedDirectInput,scope));\n      if (config.sellerRebaseline != null) validateAmazonSellerRebaseline(config,snapshot,scope);\n      break;\n    }\n    case 'single_run':\n      if (snapshot.products.length) fail('Choose fixed_products, pinned_keyword or discovery to review a run against an accepted baseline.');\n      if (config.expectedDirectInput !== null) fail('Set expectedDirectInput only in fixed_products mode.');\n      break;\n    case 'discovery':\n      if (config.expectedDirectInput !== null) fail('Set expectedDirectInput only in fixed_products mode.');\n      break;\n    case 'pinned_keyword':\n      break;\n    default:\n      fail('Choose single_run, fixed_products, pinned_keyword or discovery for Amazon review.');\n  }\n  return config;\n}\n\nfunction amazonFixedCoverage(scope,products,issues) {\n  const returned = new Set(products.map(row => row.product_key));\n  const held = new Set(issues.map(issue => issue.product_key));\n  const pending = scope.plannedProductKeys.filter(key => !returned.has(key) || held.has(key));\n  return {\n    complete:pending.length === 0 && issues.length === 0,\n    planned:scope.plannedProductKeys.length,\n    qualified:scope.plannedProductKeys.length - pending.length,\n    pending_product_keys:pending,\n  };\n}\n\nfunction reviewAmazonRun(pages,config,run,scope) {\n  if (run.runId !== config.runId || run.actorId !== config.expectedActorId) fail('Use the verified Amazon run for this review.');\n  const review = amazonHandoff(pages,config,run,scope);\n  if (config.amazonReviewMode !== 'fixed_products') return review;\n\n  const observedByKey = new Map(review.source_products.map(row => [row.product_key,row]));\n  const candidate = review.candidate_baseline.products;\n  const acceptedByKey = new Map(candidate.map(row => [row.product_key,row]));\n  const blocked = new Set([...review.review_issues.filter(issue => issue.reason !== 'seller_changed'),\n    ...review.fixed_scope_review_issues].map(issue => issue.product_key));\n  const rows = pages.flatMap(page => page.body);\n  const options = [];\n  for (const issue of review.review_issues) {\n    if (issue.reason !== 'seller_changed' || blocked.has(issue.product_key)) continue;\n    const productKey = issue.product_key;\n    const previous = acceptedByKey.get(productKey);\n    const observed = observedByKey.get(productKey);\n    if (!previous?.seller || !observed?.seller || previous.currency !== observed.currency ||\n        sourceTime(observed.scraped_at) <= sourceTime(previous.scraped_at) ||\n        !hasGenericAmazonSellerIdentity(previous,scope.marketplace,observed.asin) ||\n        !hasUnambiguousAmazonSellerSource(rows,observed)) continue;\n    options.push({runId:run.runId,baselineReference:config.baselineReference,productKey,\n      previous:amazonSellerObservation(previous),observed:amazonSellerObservation(observed)});\n  }\n  review.seller_rebaseline_options = options;\n\n  const approval = config.sellerRebaseline;\n  if (approval == null) return review;\n  const option = options.find(option => option.productKey === approval.productKey);\n  if (!option || option.runId !== approval.runId || option.baselineReference !== approval.baselineReference ||\n      !sameAmazonSellerObservation(approval.previous,option.previous) ||\n      !sameAmazonSellerObservation(approval.observed,option.observed)) {\n    review.seller_rebaseline = {status:'held',product_key:approval.productKey,reason:'approved_observation_unavailable'};\n    return review;\n  }\n\n  // Seller transitions start a new baseline and remain outside comparable price coverage and delta.\n  review.candidate_baseline.products = candidate.map(row =>\n    row.product_key === option.productKey ? observedByKey.get(option.productKey) : row);\n  review.seller_rebaseline_options = options.filter(item => item.productKey !== option.productKey);\n  const {previous,observed} = option;\n  review.seller_rebaseline = {status:'proposed',product_key:option.productKey,\n    previous:{seller:previous.seller,price:previous.price,scraped_at:previous.scrapedAt},\n    observed:{seller:observed.seller,price:observed.price,scraped_at:observed.scrapedAt}};\n  return review;\n}\n\nconst config = $('Configure existing run').first().json;\nreturn [{json:validateAmazonRunScope(config,$input.first().json)}];"
      }
    },
    {
      "id": "62a73e8c-0c26-56d0-9665-a0a565308913",
      "name": "Read all bounded dataset pages",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1540,
        200
      ],
      "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": "0fbfab08-e8a8-56f0-99dc-e6bc961e7b0d",
      "name": "Review qualified prices",
      "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_KEYWORD_PRICE_BASIS = 'unmarked_search_card';\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|gp\\/aw\\/d|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 (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(asin)) {\n      scopeIssues.push({product_key:key,reason:'outside_keyword_asin_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    if (!expectedOffers && [row.price_source,row.price_min,row.price_max].some(value => value != null)) {\n      scopeIssues.push({product_key:key,reason:'price_basis_not_comparable',scraped_at:timestamp});\n      rejected++;\n      continue;\n    }\n    if (expectedOffers && (row.in_stock === false || row.price_reason != null)) {\n      scopeIssues.push({product_key:key,reason:'direct_price_not_comparable',scraped_at:timestamp});\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    if (keywordScope) product.price_basis = AMAZON_KEYWORD_PRICE_BASIS;\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,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]) => {\n      if (!Object.hasOwn(scope,key)) return false;\n      const current = scope[key];\n      return Array.isArray(value)\n        ? Array.isArray(current) && current.length === value.length && value.every((entry,index) => current[index] === entry)\n        : current === value;\n    });\n}\n\nfunction amazonKeywordTargetCoverage(scope,products) {\n  const planned = scope.keywordAsins.map(asin => scope.marketplace+':'+asin);\n  const observed = new Set(products.map(row => row.product_key));\n  return {\n    planned_product_keys:planned,\n    qualified_price_keys:planned.filter(key => observed.has(key)),\n    missing_price_keys:planned.filter(key => !observed.has(key)),\n  };\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    const allowedFields = keywordScope ? [...AMAZON_FIELDS,'price_basis'] : AMAZON_FIELDS;\n    if (!object(row) || Object.keys(row).some(key => !allowedFields.includes(key))) fail('Invalid Amazon baseline record fields.');\n    if (Object.hasOwn(row,'price_basis') && row.price_basis !== AMAZON_KEYWORD_PRICE_BASIS) fail('Unknown Amazon keyword baseline price basis.');\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    if (keywordScope?.keywordAsins && !keywordScope.keywordAsins.includes(row.asin)) fail('The accepted keyword baseline contains an ASIN outside its target list.');\n    sourceTime(row.scraped_at);\n    seen.add(row.product_key);\n    products.push(Object.hasOwn(row,'price_basis') ? {...qualified[0],price_basis:row.price_basis} : 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,price_basis,...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    if (keywordScope && old && old.price_basis !== AMAZON_KEYWORD_PRICE_BASIS) {\n      issues.push({product_key:row.product_key,reason:'price_basis_starting_price',scraped_at:row.scraped_at,accepted_scraped_at:old.scraped_at});\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  const targetCoverage = keywordScope?.keywordAsins ? amazonKeywordTargetCoverage(keywordScope,mapped.products) : null;\n  const heldTargetRefresh = targetCoverage !== null && !mapped.products.length;\n  const generalPriceIssues = fixed || pinnedKeyword ? [] : mapped.scopeIssues;\n  const heldGeneralRefresh = generalPriceIssues.length > 0 && !mapped.products.length;\n  if (!fixed && !heldTargetRefresh && !heldGeneralRefresh && !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?.price_basis !== AMAZON_KEYWORD_PRICE_BASIS || 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,...generalPriceIssues];\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    ...(targetCoverage ? {keyword_target_coverage:targetCoverage} : {}),\n    ...(heldTargetRefresh || heldGeneralRefresh ? {delivery_status:'HELD_NO_QUALIFIED_PRICES',candidate_baseline:null,\n      acknowledgement_required:false,coverage_note:heldTargetRefresh ?\n        'No target ASIN has a qualified price in the supplied dataset. Keep the previously accepted snapshot.' :\n        'No comparable product price was found in the supplied dataset. Keep the previously accepted snapshot.'} : {})};\n}\n\n/* Amazon pinned input reviews. Compiled into the Amazon configuration and scope nodes. */\n\nconst AMAZON_FIXED_COUNTRIES = {\n  'amazon.com':'US', 'amazon.ca':'CA', 'amazon.com.mx':'MX', 'amazon.com.br':'BR',\n  'amazon.co.uk':'GB', 'amazon.de':'DE', 'amazon.fr':'FR', 'amazon.es':'ES', 'amazon.it':'IT',\n  'amazon.nl':'NL', 'amazon.pl':'PL', 'amazon.se':'SE', 'amazon.co.jp':'JP', 'amazon.in':'IN',\n  'amazon.com.au':'AU', 'amazon.ae':'AE', 'amazon.sa':'SA', 'amazon.sg':'SG', 'amazon.com.tr':'TR',\n};\nconst AMAZON_FIXED_INPUT_FIELDS = [\n  'productUrls','amazonDomain','maxProducts','fetchDetails','trackBestsellerRank','enableAiAnalysis','proxyConfiguration',\n];\n// Some saved runs include default values for disabled optional features.\nconst AMAZON_DORMANT_DEFAULTS = {\n  searchQuery:'',sortBy:'relevance',alertRankThreshold:50,alertWebhookUrl:'',connectorAlertTarget:'',\n  outputConnectors:[],llmProvider:'openrouter',\n};\nconst AMAZON_FIXED_PROXY_FIELDS = ['useApifyProxy','apifyProxyGroups','apifyProxyCountry'];\nconst AMAZON_KEYWORD_FIELDS = [\n  'searchQuery','amazonDomain','maxProducts','sortBy','fetchDetails','trackBestsellerRank','enableAiAnalysis','proxyConfiguration',\n];\nconst AMAZON_KEYWORD_TARGET_FIELDS = ['keywordAsins','keywordScanPages'];\nconst AMAZON_KEYWORD_DORMANT_DEFAULTS = {...AMAZON_DORMANT_DEFAULTS,productUrls:[]};\nconst AMAZON_KEYWORD_SORTS = ['relevance','price_low','price_high','avg_review','newest'];\nconst AMAZON_DIRECT_PRODUCT_PATH = /^\\/(?:dp|gp\\/product|product|(?!(?:s|search|gp|dp|product)\\/)[^/]+\\/dp)\\/([a-z0-9]{10})(?=\\/|$)/i;\nconst AMAZON_DOT_SEGMENT = /(?:^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/i;\n\nfunction readAmazonFixedInput(input, label) {\n  if (!object(input) || !AMAZON_FIXED_INPUT_FIELDS.every(field => Object.hasOwn(input,field)) ||\n      Object.entries(input).some(([field,value]) => !AMAZON_FIXED_INPUT_FIELDS.includes(field) &&\n        (!Object.hasOwn(AMAZON_DORMANT_DEFAULTS,field) || JSON.stringify(value) !== JSON.stringify(AMAZON_DORMANT_DEFAULTS[field])))) {\n    fail(label+' Amazon input must use the fixed direct-price fields without aliases or extra settings.');\n  }\n  const {productUrls,amazonDomain,maxProducts,fetchDetails,trackBestsellerRank,enableAiAnalysis,proxyConfiguration} = input;\n  if (typeof amazonDomain !== 'string' || !MARKET.test(amazonDomain)) fail(label+' Amazon marketplace is unsupported.');\n  if (!Array.isArray(productUrls) || !Number.isInteger(maxProducts) ||\n      productUrls.length < 1 || productUrls.length > maxProducts || maxProducts > 100) {\n    fail(label+' Amazon input needs one to 100 product URLs and a cap that includes every URL.');\n  }\n  if (typeof fetchDetails !== 'boolean' || trackBestsellerRank !== false || enableAiAnalysis !== false) {\n    fail(label+' Amazon input needs an explicit detail setting with rank tracking and AI off.');\n  }\n  if (!object(proxyConfiguration) || Object.keys(proxyConfiguration).length !== AMAZON_FIXED_PROXY_FIELDS.length ||\n      !AMAZON_FIXED_PROXY_FIELDS.every(field => Object.hasOwn(proxyConfiguration,field)) ||\n      proxyConfiguration.useApifyProxy !== true || !Array.isArray(proxyConfiguration.apifyProxyGroups) ||\n      proxyConfiguration.apifyProxyGroups.length !== 1 || proxyConfiguration.apifyProxyGroups[0] !== 'RESIDENTIAL' ||\n      proxyConfiguration.apifyProxyCountry !== AMAZON_FIXED_COUNTRIES[amazonDomain]) {\n    fail(label+' Amazon input must use a residential proxy in the selected marketplace country.');\n  }\n\n  const keys = new Set();\n  for (const [index,productUrl] of productUrls.entries()) {\n    const url = typeof productUrl === 'string' && /^[A-Za-z0-9]{10}$/.test(productUrl)\n      ? 'https://www.' + amazonDomain + '/dp/' + productUrl.toUpperCase() : productUrl;\n    const parts = typeof url === 'string' && !/[\\s\\\\,#\\p{Cc}]/u.test(url) && /^https:\\/\\/([^/?#]+)(\\/[^?#]*)/i.exec(url);\n    const host = parts ? parts[1].toLowerCase() : '';\n    const path = parts ? parts[2] : '';\n    const product = AMAZON_DIRECT_PRODUCT_PATH.exec(path);\n    if (!product || (host !== amazonDomain && host !== 'www.'+amazonDomain) || AMAZON_DOT_SEGMENT.test(path)) {\n      fail(label+' Amazon product URL '+(index+1)+' must be an unambiguous HTTPS product page in the selected marketplace.');\n    }\n    const asin = product[1].toUpperCase();\n    if ([...path.matchAll(/\\/(?:dp|gp\\/product|product)\\/([a-z0-9]{10})(?=\\/|$)/gi)].some(match => match[1].toUpperCase() !== asin)) {\n      fail(label+' Amazon product URL '+(index+1)+' has conflicting product identities.');\n    }\n    const key = amazonDomain+':'+asin;\n    if (keys.has(key)) fail(label+' Amazon input repeats a product identity.');\n    keys.add(key);\n  }\n  return {marketplace:amazonDomain,plannedProductKeys:[...keys]};\n}\n\nfunction validateAmazonFixedScope(expectedDirectInput,currentInput) {\n  const expected = readAmazonFixedInput(expectedDirectInput,'Pinned');\n  const current = readAmazonFixedInput(currentInput,'Run');\n  if (expected.marketplace !== current.marketplace ||\n      expectedDirectInput.maxProducts !== currentInput.maxProducts ||\n      expectedDirectInput.fetchDetails !== currentInput.fetchDetails ||\n      expectedDirectInput.productUrls.length !== currentInput.productUrls.length ||\n      expectedDirectInput.productUrls.some((url,index) => url !== currentInput.productUrls[index])) {\n    fail('The Amazon run input does not match the pinned marketplace, product URLs or settings.');\n  }\n  return expected;\n}\n\nfunction amazonFixedOffers(input,scope) {\n  return new Map(scope.plannedProductKeys.map((key,index) => [key,amazonOfferQuery(input.productUrls[index])]));\n}\n\nfunction checkAmazonFixedBaseline(snapshot,expectedOffers) {\n  if (snapshot.products.some(row => expectedOffers.get(row.product_key) !== amazonOfferQuery(row.url))) {\n    fail('The accepted baseline contains a product or offer outside the fixed input. Choose the matching baseline.');\n  }\n}\n\nfunction readAmazonKeywordInput(input,label) {\n  if (!object(input) || !AMAZON_KEYWORD_FIELDS.every(field => Object.hasOwn(input,field)) ||\n      Object.entries(input).some(([field,value]) => !AMAZON_KEYWORD_FIELDS.includes(field) &&\n        !AMAZON_KEYWORD_TARGET_FIELDS.includes(field) &&\n        (!Object.hasOwn(AMAZON_KEYWORD_DORMANT_DEFAULTS,field) ||\n          JSON.stringify(value) !== JSON.stringify(AMAZON_KEYWORD_DORMANT_DEFAULTS[field])))) {\n    fail(label+' Amazon input must use supported keyword fields with no extra settings or credentials.');\n  }\n  const {searchQuery,amazonDomain,maxProducts,sortBy,fetchDetails,trackBestsellerRank,enableAiAnalysis,proxyConfiguration} = input;\n  if (!text(searchQuery) || searchQuery !== searchQuery.trim() || searchQuery.length > 500 || /\\p{Cc}/u.test(searchQuery) ||\n      typeof amazonDomain !== 'string' || !MARKET.test(amazonDomain) || !AMAZON_KEYWORD_SORTS.includes(sortBy) ||\n      !Number.isInteger(maxProducts) || maxProducts < 1 || maxProducts > 100 ||\n      fetchDetails !== false || trackBestsellerRank !== false || enableAiAnalysis !== false) {\n    fail(label+' Amazon keyword input needs a supported search, market, sort and cap with details, rank tracking and AI off.');\n  }\n  if (!object(proxyConfiguration) || Object.keys(proxyConfiguration).some(field => !AMAZON_FIXED_PROXY_FIELDS.includes(field)) ||\n      proxyConfiguration.useApifyProxy !== true || !Array.isArray(proxyConfiguration.apifyProxyGroups) ||\n      proxyConfiguration.apifyProxyGroups.length !== 1 || proxyConfiguration.apifyProxyGroups[0] !== 'RESIDENTIAL' ||\n      (Object.hasOwn(proxyConfiguration,'apifyProxyCountry') && proxyConfiguration.apifyProxyCountry !== AMAZON_FIXED_COUNTRIES[amazonDomain])) {\n    fail(label+' Amazon keyword input needs the selected marketplace\u2019s residential proxy.');\n  }\n  const scope = {searchQuery,marketplace:amazonDomain,maxProducts,sortBy,proxyCountry:proxyConfiguration.apifyProxyCountry ?? null};\n  const {keywordAsins} = input;\n  if (!Object.hasOwn(input,'keywordAsins')) {\n    if (Object.hasOwn(input,'keywordScanPages')) fail(label+' Amazon keyword scan limit requires a target ASIN list.');\n    return scope;\n  }\n  const keywordScanPages = Object.hasOwn(input,'keywordScanPages') ? input.keywordScanPages : 1;\n  if (!Array.isArray(keywordAsins) || keywordAsins.length < 1 || keywordAsins.length > 100 ||\n      keywordAsins.some(asin => typeof asin !== 'string' || asin.length !== 10 || !/^[A-Z0-9]{10}$/.test(asin)) ||\n      new Set(keywordAsins).size !== keywordAsins.length ||\n      !Number.isInteger(keywordScanPages) || keywordScanPages < 1 || keywordScanPages > 3) {\n    fail(label+' Amazon keyword targets need one to 100 distinct uppercase ASINs and a limit of one to three search pages.');\n  }\n  return {...scope,keywordAsins:[...keywordAsins].sort(),keywordScanPages};\n}\n\nfunction validateAmazonKeywordScope(expectedKeywordInput,currentInput) {\n  const expected = readAmazonKeywordInput(expectedKeywordInput,'Pinned');\n  const current = readAmazonKeywordInput(currentInput,'Run');\n  if (!matchesAmazonKeywordScope(current,expected)) fail('The Amazon run input does not match the pinned keyword or search settings.');\n  return expected;\n}\n\nfunction validateAmazonRunScope(config,currentInput) {\n  if (config.amazonReviewMode === 'pinned_keyword') return validateAmazonKeywordScope(config.expectedKeywordInput,currentInput);\n  return validateAmazonFixedScope(config.expectedDirectInput,currentInput);\n}\n\nfunction amazonSellerObservation(row) {\n  return {seller:row.seller,price:row.price,scrapedAt:row.scraped_at};\n}\n\nfunction isAmazonSellerObservation(observation) {\n  return object(observation) && Object.keys(observation).length === 3 && !!text(observation.seller) &&\n    typeof observation.price === 'string' && Number.isFinite(Number(observation.price)) && Number(observation.price) > 0 &&\n    typeof observation.scrapedAt === 'string';\n}\n\nfunction sameAmazonSellerObservation(approved,observed) {\n  return isAmazonSellerObservation(approved) && approved.seller === observed.seller &&\n    approved.price === observed.price && approved.scrapedAt === observed.scrapedAt;\n}\n\nfunction hasGenericAmazonSellerIdentity(row,marketplace,asin) {\n  if (row.amazon_domain != null && row.amazon_domain !== '' && row.amazon_domain !== marketplace) return false;\n  if (amazonSource(row,asin)?.marketplace !== marketplace) return false;\n  return [row.url,row.product_url].filter(url => url != null && url !== '').every(url => {\n    if (typeof url !== 'string' || /[\\s\\\\\\p{Cc}]/u.test(url)) return false;\n    const path = /^https?:\\/\\/[^/?#]+(\\/[^?#]*)/i.exec(url)?.[1] ?? '';\n    return !AMAZON_DOT_SEGMENT.test(path) && AMAZON_DIRECT_PRODUCT_PATH.exec(path)?.[1].toUpperCase() === asin &&\n      !amazonOfferQuery(url);\n  });\n}\n\nfunction hasUnambiguousAmazonSellerSource(rows,observed) {\n  const observedTime = sourceTime(observed.scraped_at);\n  const sameTime = new Set();\n  for (const row of rows) {\n    if (!object(row) || text(row.asin).toUpperCase() !== observed.asin) continue;\n    if (!hasGenericAmazonSellerIdentity(row,observed.marketplace,observed.asin) ||\n        text(row.currency).toUpperCase() !== observed.currency) return false;\n    const {scraped_at,...fields} = row;\n    let time;\n    try {\n      time = sourceTime(scraped_at);\n    } catch {\n      return false;\n    }\n    if (time > observedTime) return false;\n    if (time === observedTime) sameTime.add(stable(fields));\n  }\n  return sameTime.size === 1;\n}\n\nfunction validateAmazonSellerRebaseline(config,snapshot,scope) {\n  const approval = config.sellerRebaseline;\n  if (!object(approval) || Object.keys(approval).length !== 5 || approval.runId !== config.runId ||\n      approval.baselineReference !== config.baselineReference || !scope.plannedProductKeys.includes(approval.productKey) ||\n      !isAmazonSellerObservation(approval.previous) || !isAmazonSellerObservation(approval.observed)) {\n    fail('Use one seller rebaseline option for this run, accepted revision and fixed product.');\n  }\n  const previous = snapshot.products.find(row => row.product_key === approval.productKey);\n  if (!previous || !sameAmazonSellerObservation(approval.previous,amazonSellerObservation(previous)) ||\n      amazonSellerName(approval.previous.seller) === amazonSellerName(approval.observed.seller) ||\n      sourceTime(approval.observed.scrapedAt) <= sourceTime(approval.previous.scrapedAt)) {\n    fail('The seller rebaseline approval must match the accepted observation and name a newer different seller.');\n  }\n  if (!hasGenericAmazonSellerIdentity(previous,scope.marketplace,previous.asin)) {\n    fail('Seller rebaseline requires a generic Amazon product URL without an offer selector.');\n  }\n}\n\nfunction validateAmazonReviewConfig(config) {\n  validateConfig(config);\n  if (config.sellerRebaseline != null && config.amazonReviewMode !== 'fixed_products') {\n    fail('Seller rebaseline is only available for fixed Amazon products.');\n  }\n  const pinnedKeyword = config.amazonReviewMode === 'pinned_keyword';\n  if (pinnedKeyword ? config.expectedDirectInput != null : config.expectedKeywordInput != null) {\n    fail('Set only the expected input for the selected Amazon review mode.');\n  }\n  const keywordScope = pinnedKeyword ? readAmazonKeywordInput(config.expectedKeywordInput,'Pinned') : null;\n  const snapshot = validateAmazonSnapshot(config.previousSnapshot,config.maxRows,keywordScope);\n  switch (config.amazonReviewMode) {\n    case 'fixed_products': {\n      const scope = validateAmazonFixedScope(config.expectedDirectInput,config.expectedDirectInput);\n      checkAmazonFixedBaseline(snapshot,amazonFixedOffers(config.expectedDirectInput,scope));\n      if (config.sellerRebaseline != null) validateAmazonSellerRebaseline(config,snapshot,scope);\n      break;\n    }\n    case 'single_run':\n      if (snapshot.products.length) fail('Choose fixed_products, pinned_keyword or discovery to review a run against an accepted baseline.');\n      if (config.expectedDirectInput !== null) fail('Set expectedDirectInput only in fixed_products mode.');\n      break;\n    case 'discovery':\n      if (config.expectedDirectInput !== null) fail('Set expectedDirectInput only in fixed_products mode.');\n      break;\n    case 'pinned_keyword':\n      break;\n    default:\n      fail('Choose single_run, fixed_products, pinned_keyword or discovery for Amazon review.');\n  }\n  return config;\n}\n\nfunction amazonFixedCoverage(scope,products,issues) {\n  const returned = new Set(products.map(row => row.product_key));\n  const held = new Set(issues.map(issue => issue.product_key));\n  const pending = scope.plannedProductKeys.filter(key => !returned.has(key) || held.has(key));\n  return {\n    complete:pending.length === 0 && issues.length === 0,\n    planned:scope.plannedProductKeys.length,\n    qualified:scope.plannedProductKeys.length - pending.length,\n    pending_product_keys:pending,\n  };\n}\n\nfunction reviewAmazonRun(pages,config,run,scope) {\n  if (run.runId !== config.runId || run.actorId !== config.expectedActorId) fail('Use the verified Amazon run for this review.');\n  const review = amazonHandoff(pages,config,run,scope);\n  if (config.amazonReviewMode !== 'fixed_products') return review;\n\n  const observedByKey = new Map(review.source_products.map(row => [row.product_key,row]));\n  const candidate = review.candidate_baseline.products;\n  const acceptedByKey = new Map(candidate.map(row => [row.product_key,row]));\n  const blocked = new Set([...review.review_issues.filter(issue => issue.reason !== 'seller_changed'),\n    ...review.fixed_scope_review_issues].map(issue => issue.product_key));\n  const rows = pages.flatMap(page => page.body);\n  const options = [];\n  for (const issue of review.review_issues) {\n    if (issue.reason !== 'seller_changed' || blocked.has(issue.product_key)) continue;\n    const productKey = issue.product_key;\n    const previous = acceptedByKey.get(productKey);\n    const observed = observedByKey.get(productKey);\n    if (!previous?.seller || !observed?.seller || previous.currency !== observed.currency ||\n        sourceTime(observed.scraped_at) <= sourceTime(previous.scraped_at) ||\n        !hasGenericAmazonSellerIdentity(previous,scope.marketplace,observed.asin) ||\n        !hasUnambiguousAmazonSellerSource(rows,observed)) continue;\n    options.push({runId:run.runId,baselineReference:config.baselineReference,productKey,\n      previous:amazonSellerObservation(previous),observed:amazonSellerObservation(observed)});\n  }\n  review.seller_rebaseline_options = options;\n\n  const approval = config.sellerRebaseline;\n  if (approval == null) return review;\n  const option = options.find(option => option.productKey === approval.productKey);\n  if (!option || option.runId !== approval.runId || option.baselineReference !== approval.baselineReference ||\n      !sameAmazonSellerObservation(approval.previous,option.previous) ||\n      !sameAmazonSellerObservation(approval.observed,option.observed)) {\n    review.seller_rebaseline = {status:'held',product_key:approval.productKey,reason:'approved_observation_unavailable'};\n    return review;\n  }\n\n  // Seller transitions start a new baseline and remain outside comparable price coverage and delta.\n  review.candidate_baseline.products = candidate.map(row =>\n    row.product_key === option.productKey ? observedByKey.get(option.productKey) : row);\n  review.seller_rebaseline_options = options.filter(item => item.productKey !== option.productKey);\n  const {previous,observed} = option;\n  review.seller_rebaseline = {status:'proposed',product_key:option.productKey,\n    previous:{seller:previous.seller,price:previous.price,scraped_at:previous.scrapedAt},\n    observed:{seller:observed.seller,price:observed.price,scraped_at:observed.scrapedAt}};\n  return review;\n}\n\nconst config = $('Configure existing run').first().json;\nconst pinned = ['fixed_products','pinned_keyword'].includes(config.amazonReviewMode);\nconst scope = pinned ? $('Verify pinned input scope').first().json : null;\nreturn [{json:reviewAmazonRun($input.all().map(item=>item.json),config,$('Verify succeeded run').first().json,scope)}];"
      }
    },
    {
      "id": "81b1fcad-9318-5471-a704-7381bbd582e2",
      "name": "Destination adapter placeholder - disabled",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1980,
        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.\nUse fixed_products for a recurring ASIN list or pinned_keyword for the same keyword settings. Use single_run for one review or discovery for rotating searches. Missing products keep their last accepted value. 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 input review?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pinned input review?": {
      "main": [
        [
          {
            "node": "Read saved run input",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read all bounded dataset pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read saved run input": {
      "main": [
        [
          {
            "node": "Verify pinned input scope",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify pinned input scope": {
      "main": [
        [
          {
            "node": "Read all bounded dataset pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read all bounded dataset pages": {
      "main": [
        [
          {
            "node": "Review qualified prices",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Review qualified prices": {
      "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": []
}
