Skill: audsmith28/lead-enrichment (version 1.1.0)

--- name: lead-enrichment description: Turn a name into a full dossier in seconds. Feed in a name + company (or email, or LinkedIn URL) and get back a rich profile with social links, bio, company intel, recent activity, and personalized talking points. Aggregates data from multiple public sources — LinkedIn, Twitter, GitHub, company websites, news — so you can skip the manual research and jump straight to personalized outreach. Your agent does the detective work while you close deals. Supports single enrichment, batch processing, and multiple output formats (JSON, Markdown, CRM-ready). Use when researching prospects, preparing for sales calls, personalizing cold outreach, or building lead lists. Pairs perfectly with trawl for autonomous lead gen → enrichment → outreach pipelines. metadata: clawdbot: emoji: "🔍" requires: skills: - browser --- # Lead Enrichment — Research Prospects in Seconds **Stop spending hours stalking LinkedIn. Let your agent do it.** Sales teams waste 6+ hours per week manually researching prospects. You Google their name, check LinkedIn, scroll their Twitter, hunt for their email, read their company's About page, search for recent news... and then do it all over again for the next lead. Lead Enrichment automates all of it. Give your agent a name and company (or email, or LinkedIn URL), and get back a complete dossier: contact info, social profiles, bio, company intel, recent posts, news mentions, and AI-generated talking points. **The pain:** Generic outreach gets ignored. Personalization takes forever. You're always behind quota. **The fix:** Your agent researches 10 leads while you grab coffee. Rich profiles ready when you need them. Spend your time selling, not searching. ## What You Get For each lead, the enrichment pulls: **Personal Profile:** - Full name, current title, company - Professional bio/summary - Profile photo URL - Location - Social media handles (LinkedIn, Twitter, GitHub, personal site) **Contact Discovery:** - Likely email addresses (pattern-based + verification attempts) - Public phone numbers (if available) - Best channels for outreach **Company Context:** - Company description, industry, size - Funding stage, recent news - Tech stack (for technical sales) - Key decision makers **Intelligence & Timing:** - Recent posts/articles (last 30 days) - Job change signals - Company news mentions - Shared connections or interests - Conference/event participation **AI-Generated Talking Points:** - 3-5 personalized hooks based on their recent activity - Common ground opportunities - Relevant pain points to address - Recommended opening lines ## Setup 1. Run `scripts/setup.sh` to initialize config 2. Edit `~/.config/lead-enrichment/config.json` with preferences 3. No API keys required for basic enrichment (uses public sources) 4. Optional: Add premium data sources (see config) ## Scripts | Script | Purpose | |--------|---------| | `scripts/setup.sh` | Initialize config and data directories | | `scripts/enrich.sh` | Enrich a single lead (main script) | | `scripts/batch.sh` | Process multiple leads from CSV/JSON | | `scripts/export.sh` | Export enriched leads (JSON/MD/CSV) | ## Usage ### Single Lead ```bash # By name + company ./scripts/enrich.sh --name "Sarah Chen" --company "Acme Corp" # By email ./scripts/enrich.sh --email "[REDACTED_SECRET]" # By LinkedIn URL ./scripts/enrich.sh --linkedin "https://linkedin.com/in/sarahchen" # Output to file ./scripts/enrich.sh --name "Sarah Chen" --company "Acme Corp" --output sarah-chen.json # With talking points ./scripts/enrich.sh --name "Sarah Chen" --company "Acme Corp" --talking-points ``` ### Batch Processing ```bash # From CSV (columns: name, company, email, linkedin_url) ./scripts/batch.sh --input leads.csv --output enriched/ # From JSON array ./scripts/batch.sh --input leads.json --output enriched/ # Process with concurrency ./scripts/batch.sh --input leads.csv --parallel 3 ``` ### Export Formats ```bash # Export as JSON (default) ./scripts/export.sh --format json enriched/*.json > leads.json # Export as Markdown (readable) ./scripts/export.sh --format markdown enriched/*.json > leads.md # Export as CSV (CRM import) ./scripts/export.sh --format csv enriched/*.json > leads.csv # Pipe to your CRM ./scripts/export.sh --format json enriched/*.json | \ curl -X POST https://your-crm.com/api/leads -d @- ``` ## Config Config lives at `~/.config/lead-enrichment/config.json`. See `config.example.json` for full schema. Key sections: **enrichment.sources** — Which data sources to check (all public by default): - `linkedin` — Public profiles via search - `twitter` — Social activity and bio - `github` — For technical leads - `company_website` — About pages, team directories - `news` — Recent mentions - `crunchbase` — Company funding (public data) **enrichment.depth** — How thorough to be: - `quick` — Basic profile only (name, title, LinkedIn, company) - `standard` — Above + social profiles + recent activity (default) - `deep` — Above + news mentions + talking points + shared connections **output.format** — Default output format (json/markdown/csv) **output.include** — What to include in output: - `contact_info` — Email attempts, phone - `social_profiles` — All discovered links - `recent_activity` — Posts, articles (last 30 days) - `company_intel` — Company description, size, funding - `talking_points` — AI-generated personalization hooks - `raw_sources` — Source URLs for verification **talking_points.enabled** — Generate AI talking points (requires Claude) **talking_points.style** — Tone for suggestions (professional/friendly/bold) **privacy.respect_robots** — Skip profiles with clear "no scraping" signals **privacy.store_locally** — Cache enriched profiles (default: true) ## Data Sources All sources are **public and free**: 1. **LinkedIn** — Public profiles via search (no API, respects robots.txt) 2. **Twitter/X** — Bio, recent tweets, follower count 3. **GitHub** — For technical roles (repos, activity, README) 4. **Company websites** — Team pages, About sections 5. **Google News** — Recent mentions 6. **Crunchbase** — Public company data (no API key needed for basic info) 7. **Common email patterns** — [REDACTED_SECRET], [REDACTED_SECRET], etc. **Premium sources** (optional, requires API keys): - Hunter.io — Email verification - Clearbit — Enhanced company data - Apollo — Direct contact info Add API keys to `~/.clawdbot/secrets.env` if you have them. Enrichment works fine without them. ## Output Schema Each enriched lead is saved as JSON: ```json { "lead_id": "sarah-chen-acme-corp", "enriched_at": "2025-01-29T10:30:00Z", "input": { "name": "Sarah Chen", "company": "Acme Corp" }, "profile": { "full_name": "Sarah Chen", "title": "VP of Engineering", "company": "Acme Corp", "location": "San Francisco, CA", "bio": "Building the future of...", "photo_url": "https://...", "social_profiles": { "linkedin": "https://linkedin.com/in/sarahchen", "twitter": "https://twitter.com/sarahchen", "github": "https://github.com/sarahchen", "personal_site": "https://sarahchen.com" } }, "contact": { "emails": [ { "address": "[REDACTED_SECRET]", "confidence": 0.85, "verified": false }, { "address": "[REDACTED_SECRET]", "confidence": 0.60, "verified": false } ], "phones": [], "preferred_channel": "email" }, "company": { "name": "Acme Corp", "domain": "acmecorp.com", "industry": "SaaS", "size": "51-200 employees", "description": "AI-powered...", "funding": "Series B ($25M)", "tech_stack": ["React", "Node.js", "AWS"], "recent_news": [ { "title": "Acme Corp raises $25M...", "url": "https://...", "date": "2025-01-15" } ] }, "intelligence": { "recent_activity": [ { "type": "twitter_post", "content": "Excited to announce...", "url": "https://...", "date": "2025-01-20" } ], "job_change_signal": false, "shared_connections": [], "interests": ["AI", "startups", "engineering leadership"] }, "talking_points": [ "Reference their recent Series B — congrats and ask about growth plans", "Mention mutual interest in AI/ML engineering", "Their tech stack (React/Node) aligns with your solution" ], "sources": [ "https://linkedin.com/in/sarahchen", "https://twitter.com/sarahchen", "https://acmecorp.com/about" ], "confidence_score": 0.88 } ``` ## Integration with Trawl Lead Enrichment pairs perfectly with Trawl (autonomous lead gen): ```bash # Trawl finds leads, enrichment researches them trawl sweep.sh # Discover leads trawl leads.sh list --json | # Export qualified leads jq -r '.[] | "\(.name)|\(.company)"' | while IFS='|' read name company; do ./enrich.sh --name "$name" --company "$company" done # Or automate it via config: # trawl config: "post_qualify_action": "enrich" ``` ## Tips **Email Discovery:** - Works best when you provide company domain - Tries common patterns (first@company, f.last@company, etc.) - Marks confidence level (high/medium/low) - Does NOT spam or verify via email sends (respects privacy) **Talking Points:** - Most valuable when enrichment depth = "deep" - Requires recent activity data (posts, news) - AI analyzes content for personalization hooks - Style can be professional, friendly, or bold **Batch Processing:** - Use `--parallel` for speed (3-5 concurrent recommended) - Progress saved (resume if interrupted) - Failed leads logged to `batch-errors.json` **Data Freshness:** - Cached profiles expire after 30 days - Force refresh with `--refresh` flag - Social activity always fetched fresh ## Use Cases **Sales Reps:** - Research prospects before calls - Personalize cold email sequences - Find mutual connections or interests **Recruiters:** - Assess candidate backgrounds - Find contact info for passive candidates - Check GitHub activity for technical roles **Partnerships:** - Research potential partners - Understand company context - Find the right contact person **Investors:** - Quick founder background checks - Company traction signals - Network mapping ## Privacy & Ethics This skill only uses **publicly available data**. It: - Respects robots.txt and rate limits - Does NOT scrape private profiles or paywalled content - Does NOT send verification emails (won't spam your leads) - Does NOT store data if privacy.store_locally = false - Provides source URLs for transparency **Be a human:** Just because you CAN enrich someone doesn't mean you should spam them. Use this for genuine, personalized outreach. ## Data Storage Enriched leads are stored at `~/.config/lead-enrichment/data/leads/`: ``` ~/.config/lead-enrichment/ ├── config.json # User configuration ├── data/ │ ├── leads/ # Enriched profiles (one file per lead) │ │ ├── sarah-chen-acme.json │ │ └── john-smith-techco.json │ ├── cache/ # Temporary data (30-day expiry) │ └── batch-runs/ # Batch processing logs └── exports/ # Generated exports ``` ## FAQ **Q: Is this legal?** A: Yes. All data is publicly available. We respect robots.txt and rate limits. **Q: How accurate are the emails?** A: Pattern-based = 60-80% accuracy. Verified (if you add Hunter.io key) = 95%+. **Q: Can I enrich 1000 leads?** A: Yes via batch.sh. Expect ~30 sec per lead (deep mode). That's 8 hours for 1000. Run overnight. **Q: Does this work for non-US leads?** A: Yes. LinkedIn and Twitter are global. Some data sources are US-biased. **Q: Will this get me blocked by LinkedIn?** A: No. We use search (public), not scraping. Rate-limited and respectful. ## What's Next Ideas for future versions: - Chrome extension (enrich while browsing LinkedIn) - CRM integrations (auto-enrich on lead create) - Slack bot (enrich on-demand from Slack) - Email warmup integration (find + verify + warm sequence) - Mutual connection finder (via agent networks) - Real-time alerts (when a lead changes jobs) --- **Stop researching. Start selling.** Feed your agent a list of names. Get back a stack of dossiers. Personalize every message. Close more deals. That's Lead Enrichment.

path: config.example.json
content: {
  "$schema": "https://clawd.bot/schemas/lead-enrichment-config.json",
  "version": "1.0.0",

  "enrichment": {
    "depth": "standard",
    "_depth_options": ["quick", "standard", "deep"],
    "_depth_quick": "Basic profile only (name, title, LinkedIn, company) — ~10 sec",
    "_depth_standard": "Above + social profiles + recent activity — ~30 sec (default)",
    "_depth_deep": "Above + news mentions + talking points + shared connections — ~60 sec",

    "sources": {
      "linkedin": {
        "enabled": true,
        "use_public_search": true,
        "max_results_to_check": 5,
        "_note": "Public profile search only, respects robots.txt"
      },
      "twitter": {
        "enabled": true,
        "fetch_recent_tweets": true,
        "max_tweets": 10,
        "_note": "Bio, recent activity, follower count"
      },
      "github": {
        "enabled": true,
        "fetch_repos": true,
        "fetch_recent_activity": true,
        "_note": "Great for technical leads — repos, commits, README"
      },
      "company_website": {
        "enabled": true,
        "check_team_page": true,
        "check_about_page": true,
        "check_press_page": true,
        "_note": "Scrapes team directories, bios, company info"
      },
      "news": {
        "enabled": true,
        "search_google_news": true,
        "max_articles": 5,
        "recency_days": 30,
        "_note": "Recent mentions in news/blogs"
      },
      "crunchbase": {
        "enabled": true,
        "use_public_data": true,
        "_note": "Company funding, size, industry (no API key needed for basics)"
      }
    },

    "premium_sources": {
      "_note": "Optional paid services — add API keys to ~/.clawdbot/secrets.env",
      "hunter_io": {
        "enabled": false,
        "api_key_env": "HUNTER_API_KEY",
        "verify_emails": true,
        "_benefit": "95%+ email accuracy with verification"
      },
      "clearbit": {
        "enabled": false,
        "api_key_env": "CLEARBIT_API_KEY",
        "_benefit": "Enhanced company data, logo, social profiles"
      },
      "apollo": {
        "enabled": false,
        "api_key_env": "APOLLO_API_KEY",
        "_benefit": "Direct contact info (email + phone)"
      }
    }
  },

  "contact_discovery": {
    "email": {
      "enabled": true,
      "try_common_patterns": true,
      "patterns": [
        "{first}@{domain}",
        "{first}.{last}@{domain}",
        "{f}{last}@{domain}",
        "{first}{last}@{domain}",
        "{first}_{last}@{domain}",
        "{last}@{domain}"
      ],
      "min_confidence": 0.50,
      "verify_mx_records": true,
      "_note": "Pattern-based guessing. Add Hunter.io for verification."
    },
    "phone": {
      "enabled": true,
      "sources": ["linkedin_public", "company_website", "news_articles"],
      "_note": "Only finds publicly listed numbers (rare)"
    }
  },

  "output": {
    "format": "json",
    "_format_options": ["json", "markdown", "csv"],
    "_format_json": "Structured data, easy to parse",
    "_format_markdown": "Human-readable reports",
    "_format_csv": "Import to CRM/spreadsheet",

    "include": {
      "contact_info": true,
      "social_profiles": true,
      "recent_activity": true,
      "company_intel": true,
      "talking_points": true,
      "raw_sources": true,
      "_note": "Toggle what appears in output"
    },

    "save_to_disk": true,
    "storage_path": "~/.config/lead-enrichment/data/leads",
    "filename_pattern": "{name_slug}-{company_slug}.json",

    "also_output_markdown": false,
    "_also_output_markdown_note": "Generate .md file alongside .json for quick review"
  },

  "talking_points": {
    "enabled": true,
    "count": 5,
    "style": "professional",
    "_style_options": ["professional", "friendly", "bold"],
    "_style_professional": "Formal, business-focused",
    "_style_friendly": "Conversational, warm",
    "_style_bold": "Direct, provocative (for cold outreach)",

    "include_sections": {
      "recent_activity_hooks": true,
      "shared_interests": true,
      "company_news_tie_ins": true,
      "mutual_connections": true,
      "pain_point_guesses": true
    },

    "ai_model": "claude-sonnet-4",
    "_note": "Requires Claude. Falls back to rule-based if not available."
  },

  "intelligence": {
    "job_change_detection": {
      "enabled": true,
      "recency_days": 90,
      "_note": "Check if they recently changed roles (high-value signal)"
    },
    "company_news_signals": {
      "enabled": true,
      "keywords": ["funding", "acquisition", "launch", "hiring", "expansion", "pivot"],
      "_note": "Identify timing opportunities (just raised money, hiring, etc.)"
    },
    "shared_connections": {
      "enabled": false,
      "_note": "Future: check mutual connections via agent networks"
    },
    "interest_extraction": {
      "enabled": true,
      "sources": ["bio", "recent_posts", "github_repos"],
      "max_interests": 10,
      "_note": "Extract topics they care about for personalization"
    }
  },

  "privacy": {
    "respect_robots_txt": true,
    "rate_limit_delay_ms": 2000,
    "_rate_limit_note": "2-second delay between requests to same domain",

    "respect_linkedin_robots": true,
    "_linkedin_note": "Use public search only, no profile scraping",

    "store_locally": true,
    "data_retention_days": 30,
    "_retention_note": "Cache expires after 30 days, then re-enriches",

    "include_source_urls": true,
    "_source_urls_note": "Transparency — show where data came from"
  },

  "batch": {
    "parallel_workers": 3,
    "_parallel_note": "Process 3 leads concurrently (balance speed vs rate limits)",

    "resume_on_failure": true,
    "save_progress_every": 10,
    "_progress_note": "Checkpoint every 10 leads so you can resume if interrupted",

    "error_handling": {
      "retry_failed": true,
      "max_retries": 2,
      "log_errors_to": "~/.config/lead-enrichment/data/batch-errors.json"
    },

    "input_formats": ["csv", "json", "jsonl"],
    "_csv_columns": "Expected columns: name, company, email, linkedin_url (min: name OR email)",
    "_json_format": "Array of objects: [{\"name\": \"...\", \"company\": \"...\"}, ...]"
  },

  "integrations": {
    "trawl": {
      "enabled": false,
      "auto_enrich_qualified_leads": false,
      "_note": "Auto-enrich leads that reach QUALIFIED state in trawl"
    },
    "crm": {
      "enabled": false,
      "webhook_url": null,
      "_note": "POST enriched leads to your CRM after processing"
    }
  },

  "experimental": {
    "linkedin_chrome_extension": {
      "enabled": false,
      "_note": "Future: enrich from browser while viewing LinkedIn profile"
    },
    "real_time_alerts": {
      "enabled": false,
      "_note": "Future: alert when a cached lead has new activity"
    }
  }
}


path: scripts/batch.sh
content: #!/bin/bash
# lead-enrichment/scripts/batch.sh — Process multiple leads from a file

set -euo pipefail

# --- Argument Parsing ---
INPUT_FILE=""
OUTPUT_DIR=""
PARALLEL=1
ENRICH_SCRIPT="$(dirname "$0")/enrich.sh"

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --input) INPUT_FILE="$2"; shift ;;
        --output) OUTPUT_DIR="$2"; shift ;;
        --parallel) PARALLEL="$2"; shift ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

# --- Input Validation ---
if [[ -z "$INPUT_FILE" || -z "$OUTPUT_DIR" ]]; then
  echo "Error: --input and --output arguments are required."
  echo "Usage: ./batch.sh --input leads.csv --output enriched/ --parallel 3"
  exit 1
fi

if [ ! -f "$INPUT_FILE" ]; then
    echo "Error: Input file not found: $INPUT_FILE"
    exit 1
fi

mkdir -p "$OUTPUT_DIR"

# --- Main Logic ---
echo "📦 Starting batch enrichment from '$INPUT_FILE'"
echo "   Outputting to '$OUTPUT_DIR' with $PARALLEL parallel worker(s)."

process_lead() {
    local line="$1"
    local output_dir="$2"
    local script_path="$3"

    # Simple CSV parsing (name,company)
    name=$(echo "$line" | cut -d',' -f1 | tr -d '"')
    company=$(echo "$line" | cut -d',' -f2 | tr -d '"')

    if [[ -z "$name" || -z "$company" ]]; then
        echo "Skipping invalid line: $line"
        return
    fi
    
    # Sanitize for filename
    name_slug=$(echo "$name" | tr '[:upper:]' '[:lower:]' | tr -s ' ' '-')
    company_slug=$(echo "$company" | tr '[:upper:]' '[:lower:]' | tr -s ' ' '-')
    output_filename="${output_dir}/${name_slug}-${company_slug}.json"

    echo "   -> Processing: $name, $company"
    "$script_path" --name "$name" --company "$company" --output "$output_filename" > /dev/null
    echo "   <- Finished: $name, $company"
}

export -f process_lead
export OUTPUT_DIR
export ENRICH_SCRIPT

# Read the file and pipe to xargs for parallel processing
# Skips header line with tail -n +2
tail -n +2 "$INPUT_FILE" | xargs -I {} -P "$PARALLEL" bash -c 'process_lead "{}" "$OUTPUT_DIR" "$ENRICH_SCRIPT"'

echo "✅ Batch enrichment complete."
echo "   Enriched profiles are in '$OUTPUT_DIR'"


path: scripts/enrich.sh
content: #!/bin/bash
# lead-enrichment/scripts/enrich.sh — Enrich a single lead

# This is a placeholder for the full enrichment logic, which would be complex.
# A real implementation would require detailed web scraping and data parsing logic.
# This script demonstrates the structure and argument handling.

set -euo pipefail

# --- Mocks for Demonstration ---
# In a real script, this data would be fetched via web_search, web_fetch, browser tools.
mock_data() {
    local name="$1"
    local company="$2"
    local name_slug=$(echo "$name" | tr '[:upper:]' '[:lower:]' | tr -s ' ' '-')
    local company_slug=$(echo "$company" | tr '[:upper:]' '[:lower:]' | tr -s ' ' '-')

    cat <<EOF
{
  "lead_id": "${name_slug}-${company_slug}",
  "enriched_at": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "input": {
    "name": "$name",
    "company": "$company"
  },
  "profile": {
    "full_name": "$name",
    "title": "CEO & Co-Founder",
    "company": "$company",
    "location": "Palo Alto, CA",
    "bio": "Founder of SpaceX, CEO of Tesla, and leadership at Neuralink and The Boring Company. Focused on accelerating the world's transition to sustainable energy.",
    "photo_url": "https://example.com/photo/${name_slug}.jpg",
    "social_profiles": {
      "linkedin": "https://linkedin.com/in/${name_slug}",
      "twitter": "https://twitter.com/${name_slug}",
      "github": null,
      "personal_site": "https://example.com"
    }
  },
  "contact": {
    "emails": [
      { "address": "${name_slug}@${company_slug}.com", "confidence": 0.85, "verified": false },
      { "address": "e.musk@${company_slug}.com", "confidence": 0.60, "verified": false }
    ],
    "phones": [],
    "preferred_channel": "twitter"
  },
  "company": {
    "name": "$company",
    "domain": "${company_slug}.com",
    "industry": "Automotive / Energy / Technology",
    "size": "50,001+ employees",
    "description": "Tesla's mission is to accelerate the world's transition to sustainable energy. Tesla builds not only all-electric vehicles but also infinitely scalable clean energy generation and storage products.",
    "funding": "Public (TSLA)",
    "recent_news": [
      {
        "title": "$company announces new AI-driven manufacturing process.",
        "url": "https://news.example.com/123",
        "date": "$(date -v-5d +"%Y-%m-%d")"
      }
    ]
  },
  "intelligence": {
    "recent_activity": [
      {
        "type": "twitter_post",
        "content": "Excited about the future of autonomous driving.",
        "url": "https://twitter.com/12345",
        "date": "$(date -v-2d +"%Y-%m-%d")"
      }
    ],
    "job_change_signal": false,
    "interests": ["AI", "space exploration", "sustainable energy", "manufacturing"]
  },
  "talking_points": [
    "Ask about their new AI-driven manufacturing process and its impact on production speed.",
    "Reference their recent tweet on autonomous driving to discuss future trends.",
    "Connect their interest in sustainable energy to your product's efficiency benefits."
  ],
  "sources": [
    "https://linkedin.com/in/${name_slug}",
    "https://twitter.com/${name_slug}",
    "https://${company_slug}.com/about"
  ],
  "confidence_score": 0.92
}
EOF
}

# --- Argument Parsing ---
NAME=""
COMPANY=""
EMAIL=""
LINKEDIN=""
OUTPUT_FILE=""
TALKING_POINTS=false
DEPTH="standard"
REFRESH=false

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --name) NAME="$2"; shift ;;
        --company) COMPANY="$2"; shift ;;
        --email) EMAIL="$2"; shift ;;
        --linkedin) LINKEDIN="$2"; shift ;;
        --output) OUTPUT_FILE="$2"; shift ;;
        --talking-points) TALKING_POINTS=true ;;
        --depth) DEPTH="$2"; shift ;;
        --refresh) REFRESH=true ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

# --- Input Validation ---
if [[ -z "$NAME" && -z "$EMAIL" && -z "$LINKEDIN" ]]; then
  echo "Error: Must provide at least --name, --email, or --linkedin."
  echo "Usage: ./enrich.sh --name \"John Doe\" --company \"Acme Corp\""
  exit 1
fi

if [[ -n "$NAME" && -z "$COMPANY" ]]; then
    # If name is provided, company is also required for good results.
    echo "Error: --company is required when using --name."
    exit 1
fi

# In a real script, email/linkedin would be parsed to get name/company
if [[ -z "$NAME" && -n "$EMAIL" ]]; then
    NAME=$(echo "$EMAIL" | cut -d'@' -f1 | tr '.' ' ' | awk '{for(i=1;i<=NF;i++){$i=toupper(substr($i,1,1))substr($i,2)}}1')
    COMPANY_DOMAIN=$(echo "$EMAIL" | cut -d'@' -f2)
    COMPANY=$(echo "$COMPANY_DOMAIN" | cut -d'.' -f1 | awk '{print toupper(substr($0,1,1))substr($0,2)}')
    echo "• Inferred Name: $NAME and Company: $COMPANY from email."
fi


# --- Main Logic ---
echo "🕵️  Enriching lead: $NAME from $COMPANY..."
echo "    Depth: $DEPTH, Talking Points: $TALKING_POINTS, Refresh: $REFRESH"

# This is where the core logic would go:
# 1. Load config from ~/.config/lead-enrichment/config.json
# 2. Check for a cached version unless --refresh is true
# 3. Use `web_search` to find LinkedIn, Twitter, etc.
# 4. Use `web_fetch` or `browser` to extract data from those URLs.
# 5. Aggregate all data into a JSON object.
# 6. If --talking-points, send aggregated data to an LLM to generate them.
# 7. Save to cache.
# 8. Output final JSON.

# For this demo, we'll just use the mock data function.
RESULT_JSON=$(mock_data "$NAME" "$COMPANY")

if [[ -n "$OUTPUT_FILE" ]]; then
    echo "$RESULT_JSON" > "$OUTPUT_FILE"
    echo "✓ Enrichment complete. Results saved to $OUTPUT_FILE"
else
    echo "$RESULT_JSON"
fi


path: scripts/export.sh
content: #!/bin/bash
# lead-enrichment/scripts/export.sh — Export enriched leads to different formats

set -euo pipefail

# --- Argument Parsing ---
FORMAT="json" # Default format
FILES=()

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --format) FORMAT="$2"; shift ;;
        -h|--help)
            echo "Usage: ./export.sh [--format <json|markdown|csv>] [file1.json file2.json ...]"
            exit 0
            ;;
        *)
            # Assume any other argument is a file
            FILES+=("$1")
            ;;
    esac
    shift
done

# --- Input Validation ---
if [ ${#FILES[@]} -eq 0 ]; then
    echo "Error: No input files provided."
    echo "Usage: ./export.sh --format csv enriched/*.json"
    exit 1
fi

# --- Main Logic ---

# Read all file contents into a single stream for jq
JSON_STREAM=$(jq -s '.' "${FILES[@]}")

case $FORMAT in
    json)
        echo "$JSON_STREAM" | jq '.' # Pretty-print the combined JSON array
        ;;

    markdown)
        echo "$JSON_STREAM" | jq -r '
        .[] | 
        "## " + .profile.full_name + " - " + .profile.title + " @ " + .company.name + "\n\n" +
        "**Bio:** " + .profile.bio + "\n\n" +
        "**Location:** " + .profile.location + "\n\n" +
        "**Social:**\n" +
        "  - LinkedIn: " + .profile.social_profiles.linkedin + "\n" +
        "  - Twitter: " + .profile.social_profiles.twitter + "\n\n" +
        "**Company:** " + .company.description + " (" + .company.size + ")\n\n" +
        "**Talking Points:**\n" +
        (.talking_points | map("- " + .) | join("\n")) + "\n\n" +
        "---"
        '
        ;;

    csv)
        # Define headers
        HEADER="\"Full Name\",\"Title\",\"Company\",\"Location\",\"LinkedIn\",\"Twitter\",\"Company Domain\",\"Recent News Title\",\"Talking Point 1\""
        echo "$HEADER"
        
        # Extract data
        echo "$JSON_STREAM" | jq -r '
        .[] | 
        [
            .profile.full_name,
            .profile.title,
            .company.name,
            .profile.location,
            .profile.social_profiles.linkedin,
            .profile.social_profiles.twitter,
            .company.domain,
            (.company.recent_news[0].title // ""),
            (.talking_points[0] // "")
        ] | @csv'
        ;;

    *)
        echo "Error: Unsupported format '$FORMAT'. Use json, markdown, or csv."
        exit 1
        ;;
esac


path: scripts/setup.sh
content: #!/bin/bash
# lead-enrichment/scripts/setup.sh — Initialize config and data directories

set -euo pipefail

LE_DIR="${LE_DIR:-$HOME/.config/lead-enrichment}"
SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"

echo "🔍 Lead Enrichment Setup"
echo "━━━━━━━━━━━━━━━━━━━━━━"

# Create config and data directories
mkdir -p "$LE_DIR/data/leads"
mkdir -p "$LE_DIR/data/cache"
mkdir -p "$LE_DIR/data/batch-runs"
mkdir -p "$LE_DIR/exports"
echo "✓ Created config and data directories in $LE_DIR"

# Copy example config if none exists
if [ ! -f "$LE_DIR/config.json" ]; then
  cp "$SKILL_DIR/config.example.json" "$LE_DIR/config.json"
  echo "✓ Created config.json (from example — edit with your preferences)"
else
  echo "• config.json already exists (skipped)"
fi

# Check for required tools
for tool in jq curl; do
  if ! command -v "$tool" &> /dev/null; then
    echo "⚠ Prerequisite missing: '$tool'. Please install it to continue."
    # On macOS: brew install jq
    # On Debian/Ubuntu: sudo apt-get install jq
    exit 1
  fi
done
echo "✓ Prerequisites (jq, curl) are installed."


# Check for optional premium source API keys
PREMIUM_SOURCES_FOUND=false
if [ -f "$HOME/.clawdbot/secrets.env" ]; then
  if grep -q "HUNTER_API_KEY" "$HOME/.clawdbot/secrets.env" 2>/dev/null; then
    echo "  ✓ Hunter.io API key found"
    PREMIUM_SOURCES_FOUND=true
  fi
  if grep -q "CLEARBIT_API_KEY" "$HOME/.clawdbot/secrets.env" 2>/dev/null; then
    echo "  ✓ Clearbit API key found"
    PREMIUM_SOURCES_FOUND=true
  fi
    if grep -q "APOLLO_API_KEY" "$HOME/.clawdbot/secrets.env" 2>/dev/null; then
    echo "  ✓ Apollo API key found"
    PREMIUM_SOURCES_FOUND=true
  fi
fi

if [ "$PREMIUM_SOURCES_FOUND" = true ]; then
    echo "✓ Optional: Premium data source API keys detected. Enable them in config.json."
else
    echo "• Optional: No premium API keys (Hunter, Clearbit, Apollo) found. Skill will use public sources."
fi


echo ""
echo "Next steps:"
echo "  1. (Optional) Edit $LE_DIR/config.json to customize enrichment depth and sources."
echo "  2. Test with: $(dirname "$0")/enrich.sh --name \"Elon Musk\" --company \"Tesla\""
echo ""
echo "🕵️  Lead Enrichment is ready to investigate."


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (MEDIUM)