{
  "name": "LinkedIn Sourcing Bot - Form (template)",
  "nodes": [
    {
      "parameters": {
        "formTitle": "Sourcing Bot",
        "formDescription": "Fill in the job, and the bot will add matching LinkedIn candidates to the sheet.",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Job title",
              "placeholder": "PPC Media Manager",
              "requiredField": true
            },
            {
              "fieldLabel": "Location",
              "placeholder": "Tel Aviv, Israel",
              "requiredField": true
            },
            {
              "fieldLabel": "Job description",
              "fieldType": "textarea",
              "placeholder": "Paste the full job description, including the years of experience",
              "requiredField": true
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.2,
      "position": [
        -336,
        -288
      ],
      "id": "c9ea3400-f437-466e-a0c3-ccf0fd2d3696",
      "name": "Job Form",
      "webhookId": "c5ef72f5-d10b-406c-9845-87a6a1c5aaea"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "// Reads the job from the form: title, location and description.\nconst f = $input.first().json;\nconst title = String(f['Job title'] || '').trim();\nconst location = String(f['Location'] || '').trim();\nconst description = String(f['Job description'] || '').replace(/<[^>]*>/g, ' ').trim();\nconst locationParts = location.split(',').map(s => s.trim()).filter(Boolean);\nreturn [{ json: { jobId: '', title, description, pitch: '', location, locationParts } }];",
        "notice": ""
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -112,
        -288
      ],
      "id": "a7f3f64b-036a-4fb9-ba24-c2be4cd6fe9d",
      "name": "Code in JavaScript"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "General",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Name": "={{  $('Parse Candidates').item.json['Name']  }}",
            "current role": "={{ $('Parse Candidates').item.json['current role'] }}",
            "years_experience": "={{ $('Parse Candidates').item.json['years_experience'] }}",
            "location": "={{ $('Parse Candidates').item.json['location'] }}",
            "pros": "={{ [].concat($('Parse Candidates').item.json['pros'] || []).map(p => '• ' + p).join('\\n') }}",
            "cons": "={{ [].concat($('Parse Candidates').item.json['cons'] || []).map(c => '• ' + c).join('\\n') }}",
            "fit_score": "={{ $('Parse Candidates').item.json['fit_score'] }}",
            "date sourced": "={{ $('Parse Candidates').item.json['date sourced'] }}",
            "jobTitle": "={{ $('Parse Candidates').item.json['jobTitle'] }}",
            "inmail": "={{ $('Write InMail').item.json.content[0].text }}",
            "linkedin profile": "==HYPERLINK(\"{{ $('Parse Candidates').item.json['linkedin profile'] }}\", \"LinkedIn Profile\")"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Name",
              "displayName": "Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "linkedin profile",
              "displayName": "linkedin profile",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "current role",
              "displayName": "current role",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "years_experience",
              "displayName": "years_experience",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "location",
              "displayName": "location",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "pros",
              "displayName": "pros",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "cons",
              "displayName": "cons",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "fit_score",
              "displayName": "fit_score",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "date sourced",
              "displayName": "date sourced",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "jobTitle",
              "displayName": "jobTitle",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "inmail",
              "displayName": "inmail",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        2960,
        -192
      ],
      "id": "8da25767-8534-43cc-ad5f-1d1df94732f5",
      "name": "Append row in sheet",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "resource": "text",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "value": "claude-sonnet-4-6",
          "mode": "list",
          "cachedResultName": "claude-sonnet-4-6"
        },
        "messages": {
          "values": [
            {
              "content": "=You are a recruiting sourcing expert. Generate exactly 5 Google X-ray search queries to find LinkedIn candidates for this job.\n\nJob Title: {{ $json.title }}\nJob Location: {{ $json.location }}\nJob Description: {{ $json.description }}\n\nIMPORTANT RULES:\n1. Read the job description carefully and extract the required years of experience (e.g. \"0-1 years\", \"1-2 years\", \"5+ years\").\n2. If the role is junior/entry-level (0-2 years required), your queries MUST target early-career people. Include terms like \"junior\", \"entry level\", \"graduate\", \"associate\", \"0-1 years\", \"1-2 years\". Do NOT use terms that attract senior people.\n3. If the role is senior (5+ years), target experienced professionals accordingly.\n4. Each query MUST include the job location to find candidates in the right area.\n5. Use the format: site:linkedin.com/in/ followed by relevant keywords.\n\nRespond ONLY with a JSON array of 5 search query strings. No other text.",
              "role": "user"
            }
          ]
        },
        "addAttachments": false,
        "simplify": true,
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.anthropic",
      "typeVersion": 1,
      "position": [
        112,
        -288
      ],
      "id": "c897e000-717e-4983-bfe8-cdd570664cde",
      "name": "Generate Search Queries"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const __items = await (async function(){\nconst results = [];\nfor (let idx = 0; idx < $input.all().length; idx++) {\n  const item = $input.all()[idx];\n  const resp = item.json;\n  const textContent = (resp.content && resp.content[0] && resp.content[0].text) ? resp.content[0].text : '[]';\n  let queries = [];\n  try {\n    const cleaned = textContent.replace(/```json/g, '').replace(/```/g, '').trim();\n    queries = JSON.parse(cleaned);\n  } catch(e) { queries = []; }\n  let jobTitle = 'Unknown', jobId = '', description = '', location = '';\n  try {\n    const allJobs = $('Code in JavaScript').all();\n    if (allJobs && allJobs[idx]) {\n      jobTitle = allJobs[idx].json.title || 'Unknown';\n      jobId = allJobs[idx].json.jobId || '';\n      description = (allJobs[idx].json.description || '').substring(0, 500);\n      location = allJobs[idx].json.location || '';\n    }\n  } catch(e) {\n    try {\n      const sheetRows = $('Read Candidates from Sheet').all();\n      if (sheetRows && sheetRows[0]) {\n        jobTitle = sheetRows[0].json.jobTitle || 'Unknown';\n        location = '' /* feedback: refined search already encodes location; never use a past candidate's location */;\n      }\n    } catch(e2) {}\n  }\n  for (const q of queries) {\n    results.push({ json: { query: q, jobTitle, jobId, description, location } });\n  }\n}\nreturn results.length > 0 ? results : [{ json: { error: 'No queries parsed' } }];\n})();\n/* ENFORCE_LOCATION_MARKER - carry source location forward on feedback runs */\ntry {\n  let __existing = [];\n  try { __existing = $('Read Candidates from Sheet').all(); } catch(e) { __existing = []; }\n  const __canon = {};\n  for (const __e of (__existing||[])) {\n    const __loc = String((__e.json && __e.json.location) || '').trim();\n    if (!__loc) continue;\n    const __parts = __loc.split(',').map(function(s){return s.trim();}).filter(Boolean);\n    const __c = __parts[__parts.length-1];\n    if (__c) __canon[__c.toLowerCase()] = __c;\n  }\n  const __list = Object.values(__canon);\n  if (__list.length) {\n    const __bool = '(' + __list.map(function(c){return '\"'+c+'\"';}).join(' OR ') + ')';\n    for (const __it of (__items||[])) {\n      const __q = __it && __it.json && __it.json.query;\n      if (typeof __q !== 'string') continue;\n      const __has = __list.some(function(c){return __q.toLowerCase().includes(c.toLowerCase());});\n      if (!__has) __it.json.query = __q.trim() + ' ' + __bool;\n    }\n  }\n} catch(e) {}\nreturn __items;\n",
        "notice": ""
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        464,
        -192
      ],
      "id": "10319d01-78e4-4c79-9ded-3badd211ff40",
      "name": "Parse Queries"
    },
    {
      "parameters": {
        "resource": "Actors",
        "operation": "Run actor and get dataset",
        "actorSource": "store",
        "actorId": {
          "__rl": true,
          "value": "apify~google-search-scraper",
          "mode": "list",
          "cachedResultName": "Google Search Results Scraper"
        },
        "customBody": "={{ JSON.stringify({ queries: $json.query, maxPagesPerQuery: 1, resultsPerPage: 10 }) }}",
        "timeout": {},
        "memory": 1024,
        "build": "",
        "authentication": "apifyOAuth2Api"
      },
      "type": "@apify/n8n-nodes-apify.apify",
      "typeVersion": 1,
      "position": [
        688,
        -192
      ],
      "id": "5f3261b0-b7a9-4c7f-af6d-db1d06681dcf",
      "name": "Google Search Scraper"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "\n// Helper to strip markdown code fences\nfunction stripFences(str) {\n  if (!str) return str;\n  return str.replace(/^```(?:json)?\\n?/i, '').replace(/\\n?```\\s*$/i, '').trim();\n}\n\nconst results = [];\nconst qi = $('Parse Queries').all();\nconst jobs = {};\nconst d = new Date().toISOString().split('T')[0];\nfor (let i = 0; i < $input.all().length; i++) {\n  const it = $input.all()[i];\n  const jt = (qi[i] && qi[i].json.jobTitle) || 'Unknown';\n  if (!jobs[jt]) jobs[jt] = {c: [], u: new Set()};\n  let t = '';\n  if (it.json.content && Array.isArray(it.json.content)) t = it.json.content[0].text || '';\n  else if (it.json.text) t = it.json.text;\n  else t = JSON.stringify(it.json);\n  // Strip markdown code fences if present\n  t = t.replace(/^```json\\s*/i, '').replace(/```\\s*$/, '').trim();\n  try {\n    let parsed = JSON.parse(stripFences(t));\n    if (!Array.isArray(parsed)) parsed = [];\n    for (const c of parsed) {\n      if (c.linkedin_profile && !jobs[jt].u.has(c.linkedin_profile)) {\n        jobs[jt].u.add(c.linkedin_profile);\n        jobs[jt].c.push(c);\n      }\n    }\n  } catch(e) {}\n}\nfor (const jt of Object.keys(jobs)) {\n  const top = jobs[jt].c.sort((a, b) => { return b.fit_score - a.fit_score; }).slice(0, 10);\n  for (const c of top) {\n    results.push({json: {Name: c.name || '', 'linkedin profile': c.linkedin_profile || '', 'current role': c.current_role || '', years_experience: c.years_experience || '', location: c.location || '', pros: Array.isArray(c.pros) ? c.pros.join('; ') : c.pros || '', cons: Array.isArray(c.cons) ? c.cons.join('; ') : c.cons || '', fit_score: c.fit_score || 0, 'date sourced': d, jobTitle: jt}});\n  }\n}\nif (results.length > 0) return results;\nreturn [];",
        "notice": ""
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1904,
        -192
      ],
      "id": "59853233-43a9-4715-971d-b527cfbecedb",
      "name": "Parse Candidates"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "// Extract LinkedIn URLs from Google Search results, grouped by job\nconst items = $input.all();\nconst parseQueriesItems = $('Parse Queries').all();\n\nconst jobGroups = {};\nconst jobOrder = [];\n\nfor (const pq of parseQueriesItems) {\n    const groupKey = pq.json.jobTitle + '_' + pq.json.location;\n    if (!jobGroups[groupKey]) {\n          jobGroups[groupKey] = {\n                  jobTitle: pq.json.jobTitle,\n                  location: pq.json.location,\n                  jobKey: groupKey,\n                  urls: new Set(),\n                  rawResults: []\n          };\n          jobOrder.push(groupKey);\n    }\n}\n\nfor (let i = 0; i < items.length; i++) {\n    const pq = parseQueriesItems[i];\n    if (!pq) continue;\n    const groupKey = pq.json.jobTitle + '_' + pq.json.location;\n    const organicResults = items[i].json.organicResults || [];\n    if (jobGroups[groupKey]) {\n          jobGroups[groupKey].rawResults.push(...organicResults);\n          for (const result of organicResults) {\n                  const url = result.url || '';\n                  const match = url.match(/linkedin\\.com\\/in\\/([a-zA-Z0-9\\-_%]+)/);\n                  if (match && match[1]) {\n                            jobGroups[groupKey].urls.add('https://www.linkedin.com/in/' + match[1] + '/');\n                  }\n          }\n    }\n}\n\nconst urlToJobMap = {};\nconst allProfileUrls = [];\nconst jobRawResults = {};\n\nfor (const key of jobOrder) {\n    const group = jobGroups[key];\n    jobRawResults[key] = { rawResults: group.rawResults, jobTitle: group.jobTitle, location: group.location };\n    for (const url of group.urls) {\n          allProfileUrls.push(url);\n          urlToJobMap[url] = { jobTitle: group.jobTitle, location: group.location, jobKey: key };\n    }\n}\n\nreturn [{ json: { profileUrls: allProfileUrls, urlToJobMap, jobRawResults } }];\n",
        "notice": ""
      },
      "id": "scrape-li-1776697229865",
      "name": "Scrape LinkedIn Profiles",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        912,
        -192
      ]
    },
    {
      "parameters": {
        "resource": "text",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "value": "claude-sonnet-4-6",
          "mode": "list",
          "cachedResultName": "claude-sonnet-4-6"
        },
        "messages": {
          "values": [
            {
              "content": "=You are a recruiting sourcing expert. Evaluate the following LinkedIn profiles for the job role and return ONLY a valid JSON array with no extra text, no markdown.\n\nJob Title: {{    $json.jobTitle }}\nJob Location: {{    $json.location }}\n\nFull LinkedIn Profile Data (structured, from direct profile scrape):\n{{    JSON.stringify($json.profiles) }}\n\nGoogle Search Snippets (use as supplementary context if profile data is sparse):\n{{    JSON.stringify($json.rawResults) }}\n\nPrioritize the full profile data for your evaluation. If profiles array is empty, use the Google snippets only.\n\nFor each candidate, evaluate their fit based on all available info. Return a JSON array. Each object must have these exact fields:\n- linkedin_profile: (string) LinkedIn URL\n- name: (string) full name, or \"Unknown\" if not clear\n- current_role: (string) current job title and company\n- location: (string) location if mentioned, otherwise \"Unknown\"\n- years_experience: (number) estimated total years of experience, or 5 if unknown\n- pros: (array of strings) 2-4 bullet points. CRITICAL FORMAT: each must be a SHORT PHRASE only, max 8 words, NO full sentences, NO semicolons. Good examples: [\"Title matches role exactly\", \"Based in Florida (EST)\", \"B2B SaaS background\", \"10+ years outbound sales\"]. BAD examples (do NOT do this): [\"Title aligns directly with Sales Executive role; Located in Florida\"]\n- cons: (array of strings) 1-3 bullet points. CRITICAL FORMAT: each must be a SHORT PHRASE only, max 8 words, NO full sentences, NO semicolons. Good examples: [\"Limited profile detail\", \"Franchise-only sales focus\"]. BAD examples (do NOT do this): [\"Franchise-specific focus may be a narrow specialization; Limited profile detail\"]\n- fit_score: (number 1-10) overall fit score. IMPORTANT: Use the FULL scale. A candidate who perfectly matches the job title, has the right seniority, right skills, right location should score 9 or 10. A very strong fit with minor gaps scores 8-9. Only a mediocre match scores exactly 8. Do NOT cluster everyone at 8 — differentiate clearly. Score every candidate strictly and honestly using the full scale — do NOT inflate scores to fill a quota.\n\nMANDATORY EXCLUSION RULES — exclude any candidate who fails ANY of these:\n\n1. SENIORITY MATCH & EXPERIENCE CAP:\n   - First, extract the required years of experience from {{ $json.description }} (e.g. \"0-1 years\", \"up to 1 year\", \"1-2 years\", \"5+ years experience\").\n   - This is a HARD rule: candidates outside this experience range must be EXCLUDED (fit_score = 0), regardless of other qualities.\n   - If the job title contains \"Junior\" or \"Jr\", the experience cap is typically 0-2 years — HARD EXCLUDE anyone with 3+ years total experience or with senior-sounding titles (Manager, Senior, Lead, Head, Director, VP, Founder).\n   - If the job title contains \"Senior\" or \"Sr\", require 5+ years.\n   - Always use the actual number stated in the job description as the primary source.\n   - If the job is a VP or C-suite role (e.g., VP of Sales, Chief Revenue Officer), then VP/SVP/C-suite candidates are CORRECT and should be included. Exclude people who are too junior (manager-level or below).\n   - If the job is an individual contributor or mid-level role (e.g., Sales Executive, Account Executive, BDR), then EXCLUDE anyone who is VP, SVP, EVP, C-suite (CEO/CFO/COO/CRO/CMO), Partner, Managing Director, President, or Founder at executive level. Also exclude under-qualified candidates (intern, entry-level, associate) for senior IC roles.\n   - Match the seniority of the candidate to the seniority implied by \"{{ $json.jobTitle }}\".\n\n2. LOCATION: [Optional. Add your own location rules here, or delete this rule.]\n\nFirst EXCLUDE anyone who fails the MANDATORY EXCLUSION RULES above (those candidates do not qualify at all). Then, from the remaining qualified candidates, return the TOP 10 ranked by fit_score, highest first. Keep scoring strict and differentiated — do NOT inflate scores just to reach 10. If fewer than 10 qualified candidates remain after exclusions, return all of them. Return ONLY the JSON array, sorted by fit_score descending.",
              "role": "user"
            }
          ]
        },
        "addAttachments": false,
        "simplify": true,
        "options": {
          "maxTokens": 8192
        }
      },
      "type": "@n8n/n8n-nodes-langchain.anthropic",
      "typeVersion": 1,
      "position": [
        1552,
        -192
      ],
      "id": "26b1eab4-3da3-4224-9492-86ccd480dc06",
      "name": "Score Candidates"
    },
    {
      "parameters": {
        "resource": "text",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "value": "claude-sonnet-4-6",
          "mode": "list",
          "cachedResultName": "claude-sonnet-4-6"
        },
        "messages": {
          "values": [
            {
              "content": "=Write a short, personalized LinkedIn InMail to recruit this candidate. Be warm, conversational and human - no buzzwords, no long sentences. Write like a real person reaching out.\n\nCandidate: {{  $json['Name'] }}\nRole: {{  $json['current role'] }}\nLocation: {{  $json['location'] }}\nStrengths: {{  $json['pros'] }}\n\nHiring for: {{  $json['jobTitle'] }} at [YOUR COMPANY NAME]\nCompany website: [YOUR WEBSITE URL]\nCareers page: [YOUR CAREERS PAGE URL]\n\nRules: Open with something specific about them, mention the role, include a link to the company website naturally, end with a soft CTA. Max 5-6 short sentences. Sound human, not AI.\n\nReturn ONLY the message text, nothing else.",
              "role": "user"
            }
          ]
        },
        "addAttachments": false,
        "simplify": true,
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.anthropic",
      "typeVersion": 1,
      "position": [
        2112,
        -192
      ],
      "id": "8aa29aa3-7d3e-4589-bccb-5c91a5b74f7c",
      "name": "Write InMail"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const __items = await (async function(){\n// Group Apify results by job using URL mapping from upstream node\nconst apifyProfiles = $input.all();\nconst urlToJobMap = $('Scrape LinkedIn Profiles').first().json.urlToJobMap;\nconst jobRawResults = $('Scrape LinkedIn Profiles').first().json.jobRawResults;\n\nconst jobProfileMap = {};\nfor (const item of apifyProfiles) {\n    const profile = item.json;\n    const profileUrl = profile.linkedinUrl || profile.linkedInUrl || profile.profileUrl || profile.url;\n    const normalizedUrl = profileUrl ? (profileUrl.endsWith('/') ? profileUrl : profileUrl + '/') : null;\n    const jobInfo = normalizedUrl ? (urlToJobMap[normalizedUrl] || urlToJobMap[profileUrl]) : null;\n    if (!jobInfo) continue;\n    // Deterministic location safety-net: drop profiles whose country doesn't match the job location\n    const jobLoc = (jobInfo.location || '').toLowerCase();\n    const pc = profile.location && profile.location.parsed;\n    const profCountry = /*UKFIX*/ (function(){var _c=(pc&&(pc.country||pc.countryFull)||'').toLowerCase().trim();var _a={'uk':'united kingdom','u.k.':'united kingdom','great britain':'united kingdom','england':'united kingdom','scotland':'united kingdom','wales':'united kingdom','usa':'united states','us':'united states','u.s.':'united states','u.s.a.':'united states','uae':'united arab emirates'};return _a[_c]||_c;})();\n    if (jobLoc && profCountry && !jobLoc.includes(profCountry)) continue;\n    if (!jobProfileMap[jobInfo.jobKey]) {\n        jobProfileMap[jobInfo.jobKey] = { profiles: [], jobTitle: jobInfo.jobTitle, location: jobInfo.location, jobKey: jobInfo.jobKey };\n    }\n    jobProfileMap[jobInfo.jobKey].profiles.push({ url: profileUrl, ...profile });\n}\n\nreturn Object.values(jobProfileMap).map(job => ({\n    json: {\n        profiles: job.profiles,\n        rawResults: (jobRawResults[job.jobKey] || {}).rawResults || [],\n        jobTitle: job.jobTitle,\n        location: job.location,\n        jobKey: job.jobKey\n    }\n}));\n})();\n/* ENFORCE_LOCATION_GROUP_MARKER - country filter carried from source on feedback runs */\ntry {\n  let __ex = [];\n  try { __ex = $('Read Candidates from Sheet').all(); } catch(e) { __ex = []; }\n  const __set = new Set();\n  for (const __e of (__ex||[])) {\n    const __l = String((__e.json && __e.json.location) || '').trim();\n    if (!__l) continue;\n    const __p = __l.split(',').map(function(s){return s.trim();}).filter(Boolean);\n    const __c = __p[__p.length-1];\n    if (__c) __set.add(__c.toLowerCase());\n  }\n  const __allowed = Array.from(__set);\n  if (__allowed.length) {\n    for (const __it of (__items||[])) {\n      if (!__it || !__it.json || !Array.isArray(__it.json.profiles)) continue;\n      __it.json.profiles = __it.json.profiles.filter(function(__pr){\n        const __loc = (__pr && __pr.location) || {};\n        const __ps = __loc.parsed || {};\n        const __hay = ((__ps.country||'')+' '+(__ps.countryName||'')+' '+(__loc.linkedinText||'')).toLowerCase();\n        return __allowed.some(function(c){ return __hay.indexOf(c) >= 0; });\n      });\n    }\n  }\n} catch(e) {}\nreturn __items;\n",
        "notice": ""
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1328,
        -192
      ],
      "id": "8a590e9b-141b-4395-80a6-4868521ca708",
      "name": "Group LinkedIn Results"
    },
    {
      "parameters": {
        "resource": "Actors",
        "operation": "Run actor and get dataset",
        "actorSource": "store",
        "actorId": {
          "__rl": true,
          "mode": "list",
          "value": "harvestapi~linkedin-profile-scraper"
        },
        "customBody": "={{ JSON.stringify({ \"urls\": $json.profileUrls }) }}",
        "timeout": null,
        "memory": 1024,
        "build": "",
        "authentication": "apifyOAuth2Api"
      },
      "type": "@apify/n8n-nodes-apify.apify",
      "typeVersion": 1,
      "position": [
        1120,
        -192
      ],
      "id": "6c034000-01a3-4087-b58d-d77166de5438",
      "name": "Run an Actor and get dataset"
    },
    {
      "parameters": {
        "curlImport": "",
        "method": "GET",
        "url": "https://sheets.googleapis.com/v4/spreadsheets/YOUR_SPREADSHEET_ID/values/General",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "provideSslCertificates": false,
        "sendQuery": true,
        "specifyQuery": "keypair",
        "queryParameters": {
          "parameters": [
            {
              "name": "valueRenderOption",
              "value": "FORMULA"
            }
          ]
        },
        "sendHeaders": false,
        "sendBody": false,
        "options": {},
        "infoMessage": ""
      },
      "id": "590f4e28-1df1-4b79-8fdf-a6d17be52aca",
      "name": "Read Existing Candidates",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        944,
        48
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "// Cross-run de-dup: drop LinkedIn URLs already in the Google Sheet (read via Sheets API, valueRenderOption=FORMULA)\nconst scrape = $('Scrape LinkedIn Profiles').first().json;\nconst profileUrls = scrape.profileUrls || [];\nconst norm = u => (u||'').toString().trim().toLowerCase().replace(/^https?:\\/\\//,'').replace(/^www\\./,'').replace(/\\/+$/,'');\nconst extractUrl = v => { const s=(v||'').toString(); const m=s.match(/HYPERLINK\\(\\s*[\"']([^\"']+)[\"']/i); return m ? m[1] : s; };\nconst resp = $input.first() ? $input.first().json : {};\nconst values = (resp && resp.values) || [];\nconst header = (values[0] || []).map(h => String(h).trim().toLowerCase());\nconst col = header.indexOf('linkedin profile');\nconst seen = new Set();\nif (col >= 0) { for (let i=1;i<values.length;i++){ const url = extractUrl(values[i] ? values[i][col] : ''); if (url) seen.add(norm(url)); } }\nconst newUrls = profileUrls.filter(u => !seen.has(norm(u)));\nconst MAX_PROFILES = 30; // cap: 28 profiles (~291K tokens) ran OK; 116 (~889K) hit the API size limit\nreturn [{ json: { profileUrls: newUrls.slice(0, MAX_PROFILES), urlToJobMap: scrape.urlToJobMap, jobRawResults: scrape.jobRawResults, totalFound: profileUrls.length, existingInSheet: seen.size, alreadyInSheet: profileUrls.length - newUrls.length, newCount: newUrls.length } }];",
        "notice": ""
      },
      "id": "2e6a80ef-1624-43c4-8e07-0cd9bf82549c",
      "name": "Filter New Profiles",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1024,
        -80
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "// Pre-scoring experience filter. Relevance terms are DERIVED FROM THE JD by the 'Derive Relevance Terms' AI node (no hardcoded list).\nfunction getTerms(){ try { const raw=$('Derive Relevance Terms').first().json.content[0].text||''; const clean=raw.replace(/```(?:json)?/gi,'').replace(/```/g,'').trim(); const arr=JSON.parse(clean); return Array.isArray(arr)?arr.map(t=>String(t).toLowerCase().trim()).filter(Boolean):[]; } catch(e){ return []; } }\nconst terms=getTerms();\nconst RE = terms.length ? new RegExp(terms.map(t=>t.replace(/[^a-z0-9 ]/g,'').trim()).filter(Boolean).join('|'),'i') : null;\nfunction extractYears(text){ const t=(text||'').toString().replace(/[\\u2013\\u2014]/g,'-'); let m=t.match(/(\\d+)\\s*(?:-|to)\\s*(\\d+)\\s*\\+?\\s*years?/i); if(m) return {min:+m[1],max:+m[2]}; m=t.match(/(?:minimum|at least)\\s*(\\d+)\\s*years?/i)||t.match(/(\\d+(?:\\.\\d+)?)\\s*\\+\\s*years?/i); if(m) return {min:Math.floor(+m[1]),max:null}; m=t.match(/up to\\s*(\\d+)\\s*years?/i); if(m) return {min:0,max:+m[1]}; return {min:null,max:null}; }\nfunction parseExp(p){ let e=p.experience; if(typeof e==='string'){ try{ e=JSON.parse(e);}catch(_){ } } return Array.isArray(e)?e:[]; }\nfunction durMonths(d){ d=(d||'').toLowerCase(); let m=0; const y=d.match(/(\\d+)\\s*yr/); const mo=d.match(/(\\d+)\\s*mo/); if(y)m+=Number(y[1])*12; if(mo)m+=Number(mo[1]); return m; }\nfunction relYears(p){ let mo=0; parseExp(p).forEach(x=>{ if(RE && RE.test(x.position||'')) mo+=durMonths(x.duration); }); return mo/12; }\nlet jobs=[]; try { jobs=$('Code in JavaScript').all().map(x=>x.json); } catch(e) { jobs=[]; } // feedback path: Code in JavaScript didn't run -> no JD ranges -> fall through to keep-all\nconst rangeByTitle={}; jobs.forEach(j=>{ rangeByTitle[(j.title||'').toLowerCase()]=extractYears((j.description||'')+' '+(j.pitch||'')); });\nconst firstRange=jobs.length?extractYears((jobs[0].description||'')+' '+(jobs[0].pitch||'')):{min:null,max:null};\nconst out=[];\nfor(const item of $input.all()){\n  const j=item.json; const r=rangeByTitle[(j.jobTitle||'').toLowerCase()]||firstRange; const profiles=j.profiles||[]; let kept=profiles;\n  if(RE && (r.min!=null||r.max!=null)){ const lo=r.min!=null?r.min:0; const hi=r.max!=null?r.max+3:Infinity; kept=profiles.filter(p=>{ const y=relYears(p); return y>=lo && y<=hi; }); }\n  out.push({ json: Object.assign({}, j, { profiles: kept, profilesBeforeExpFilter: profiles.length, profilesAfterExpFilter: kept.length, relevanceTermsCount: terms.length }) });\n}\nreturn out;",
        "notice": ""
      },
      "id": "530080ee-69cf-4588-acd6-47a2397c574f",
      "name": "Filter By Experience (pre-scoring)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        -336
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "// Override years_experience with RELEVANT experience using JD-derived terms (no hardcoded list). Fail-safe: leave as-is if no terms.\nfunction getTerms(){ try { const raw=$('Derive Relevance Terms').first().json.content[0].text||''; const clean=raw.replace(/```(?:json)?/gi,'').replace(/```/g,'').trim(); const arr=JSON.parse(clean); return Array.isArray(arr)?arr.map(t=>String(t).toLowerCase().trim()).filter(Boolean):[]; } catch(e){ return []; } }\nconst terms=getTerms();\nconst RE = terms.length ? new RegExp(terms.map(t=>t.replace(/[^a-z0-9 ]/g,'').trim()).filter(Boolean).join('|'),'i') : null;\nfunction parseExp(p){ let e=p.experience; if(typeof e==='string'){ try{ e=JSON.parse(e);}catch(_){ } } return Array.isArray(e)?e:[]; }\nfunction durMonths(d){ d=(d||'').toLowerCase(); let m=0; const y=d.match(/(\\d+)\\s*yr/); const mo=d.match(/(\\d+)\\s*mo/); if(y)m+=Number(y[1])*12; if(mo)m+=Number(mo[1]); return m; }\nfunction relYears(p){ let mo=0; parseExp(p).forEach(x=>{ if(RE && RE.test(x.position||'')) mo+=durMonths(x.duration); }); return Math.round(mo/12*10)/10; }\nconst slug = u => { const m=(u||'').toString().toLowerCase().match(/\\/in\\/([^\\/?#]+)/); return m?m[1].replace(/\\/+$/,''):''; };\nconst profs = $('Run an Actor and get dataset').all().map(it=>it.json);\nconst byId={}; profs.forEach(p=>{ const k=slug(p.linkedinUrl||p.url); if(k) byId[k]=p; if(p.publicIdentifier) byId[p.publicIdentifier.toLowerCase()]=p; });\nreturn $input.all().map(item=>{\n  const j = Object.assign({}, item.json);\n  if(!RE) return { json: j };\n  let url=(j['linkedin profile']||j['linkedin_profile']||'').toString(); const m=url.match(/HYPERLINK\\(\\s*[\"']([^\"']+)[\"']/i); if(m) url=m[1];\n  const p = byId[slug(url)]; if (p) j['years_experience'] = relYears(p);\n  return { json: j };\n});",
        "notice": ""
      },
      "id": "c3b050a9-c8d2-43c9-8565-eebccd4ae28b",
      "name": "Set Relevant Experience",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1216,
        -128
      ]
    },
    {
      "parameters": {
        "resource": "text",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "value": "claude-sonnet-4-6",
          "mode": "list",
          "cachedResultName": "claude-sonnet-4-6"
        },
        "messages": {
          "values": [
            {
              "content": "=You are a recruiting sourcing expert. For the job below, list the role titles, job functions, abbreviations, and close synonyms that indicate RELEVANT work experience for this specific role — so we can measure how many years of relevant experience a candidate has. Include the role itself, common variants, and closely adjacent functions (e.g. for a PR role: public relations, communications, media relations, account executive, publicist; for a paid-media role: ppc, paid media, performance marketing, sem, paid search). Output ONLY a JSON array of 10-20 short lowercase keyword strings and nothing else.\n\nJob Title: {{ $json.title }}\nJob Description: {{ $json.description }}",
              "role": "user"
            }
          ]
        },
        "addAttachments": false,
        "simplify": true,
        "options": {}
      },
      "id": "a43e0641-3e00-465d-a19b-c78500a458b7",
      "name": "Derive Relevance Terms",
      "type": "@n8n/n8n-nodes-langchain.anthropic",
      "typeVersion": 1,
      "position": [
        528,
        -368
      ]
    },
    {
      "parameters": {
        "content": "## Setup (form version)\nNo Slack and no ATS needed: you fill in the job in a form.\n\n1. **Google Sheets** nodes + **Read Existing Candidates**: connect Google, replace `YOUR_SPREADSHEET_ID`. Sheet tab is `General` with columns: Name, linkedin profile, current role, years_experience, location, pros, cons, fit_score, date sourced, jobTitle, inmail.\n2. **Anthropic** nodes: connect your Anthropic API key.\n3. **Apify** nodes: connect your Apify account.\n4. **Write InMail**: fill in your company name and links.\n5. **Score Candidates**: add your own location rules (optional).\n\nUsage: open the form from the **Job Form** node (Test URL while testing, Production URL after Publish). Write the location with the country, e.g. `Tel Aviv, Israel`.",
        "height": 520,
        "width": 520
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1600,
        -560
      ],
      "id": "df400471-fdb7-4e74-b372-3e10c0f546e9",
      "name": "Setup instructions"
    }
  ],
  "connections": {
    "Code in JavaScript": {
      "main": [
        [
          {
            "node": "Generate Search Queries",
            "type": "main",
            "index": 0
          },
          {
            "node": "Derive Relevance Terms",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Search Queries": {
      "main": [
        [
          {
            "node": "Parse Queries",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Queries": {
      "main": [
        [
          {
            "node": "Google Search Scraper",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Search Scraper": {
      "main": [
        [
          {
            "node": "Scrape LinkedIn Profiles",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Candidates": {
      "main": [
        [
          {
            "node": "Set Relevant Experience",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scrape LinkedIn Profiles": {
      "main": [
        [
          {
            "node": "Read Existing Candidates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Score Candidates": {
      "main": [
        [
          {
            "node": "Parse Candidates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write InMail": {
      "main": [
        [
          {
            "node": "Append row in sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Group LinkedIn Results": {
      "main": [
        [
          {
            "node": "Filter By Experience (pre-scoring)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run an Actor and get dataset": {
      "main": [
        [
          {
            "node": "Group LinkedIn Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Existing Candidates": {
      "main": [
        [
          {
            "node": "Filter New Profiles",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter New Profiles": {
      "main": [
        [
          {
            "node": "Run an Actor and get dataset",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter By Experience (pre-scoring)": {
      "main": [
        [
          {
            "node": "Score Candidates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Relevant Experience": {
      "main": [
        [
          {
            "node": "Write InMail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Job Form": {
      "main": [
        [
          {
            "node": "Code in JavaScript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  }
}