Skip to content

Autonomous AI sales agent powered by Claude Code or Codex. Finds prospects, writes cold emails, sends campaigns, handles replies, books meetings. No API keys needed — runs on your Claude or Codex subscriptions.

Add buying signals (tech stack + hiring) and prospect-list CSV export

Ethan22fe88aa4225
diff --git a/CLAUDE.md b/CLAUDE.md
index dfa9cb0..ac384be 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -153,6 +153,7 @@ Users will come back with questions and tasks. Common ones:
- **"I want to change what Harvey says"** → Skills are in `skills/`, prompts are in `prompts/`. Both are plain markdown files. Edit them directly.
- **"Train Harvey on a different product"** → `harvey train <new-url>`
- **"How do I see the database?"** → It's at `data/harvey.db`. They can open it with any SQLite tool, or ask you to query it.
+- **"I just want the prospect list"** → `harvey export` writes a sequencer-ready CSV (verified/risky emails only; `--all` for everything). Also available as Export buttons on the dashboard's Contacts tab. Harvey is valuable purely as a list-builder even if the user never lets it send.
---
@@ -166,7 +167,7 @@ Users will come back with questions and tasks. Common ones:
- **Skills** (`skills/`): Markdown knowledge files injected into agent prompts
### Sub-Agents
-- **Scout**: Python does all web searching (DuckDuckGo → Bing → Google → Serper API) and email resolution (pattern-first: cache → scraped mailto → Hunter domain search → default, then verify one candidate via Reoon/ZeroBounce/Hunter/SMTP; catch-alls flagged `risky`). Claude only scores/personalizes found data.
+- **Scout**: Python does all web searching (DuckDuckGo → Bing → Google → Serper API) and email resolution (pattern-first: cache → scraped mailto → Hunter domain search → default, then verify one candidate via Reoon/ZeroBounce/Hunter/SMTP; catch-alls flagged `risky`). Claude only scores/personalizes found data. Scout also collects **buying signals**: tech stack detected on each company's site (HubSpot, Shopify, Intercom, ~35 tools — zero extra requests) and hiring signals from careers pages. With `pip install python-jobspy` (optional), a job-board strategy discovers companies actively hiring for roles in `icp.hiring_signals` (falls back to `icp.titles`) — the strongest in-market signal. Signals land in prospects' personalization notes and boost their score.
- **Writer**: Generates 3-email sequences (Email 1 < 75 words, Email 2 < 75, Email 3 < 40). Strict ban list on AI patterns.
- **Sender**: Deploys to Instantly API. Enforces daily send limits.
- **Handler**: Classifies reply intent, advances conversation stage, auto-responds. Has reply deduplication.
@@ -188,6 +189,8 @@ harvey train <url> # Train on a product website
harvey status # Pipeline summary
harvey usage # Claude quota gauges + per-agent token/cost report
harvey usage --reconcile # Also backfill usage from Claude Code transcripts
+harvey export # Deliverable prospects → sequencer-ready CSV (prospects.csv)
+harvey export --all # Full raw list, no filters
```
### Common Issues
diff --git a/harvey.yaml b/harvey.yaml
index ef28c0e..ad7b488 100644
--- a/harvey.yaml
+++ b/harvey.yaml
@@ -39,6 +39,10 @@ icp:
- "Director of Marketing"
geography:
- "United States"
+ # Roles that signal a company is in-market RIGHT NOW (a company hiring a
+ # "Head of Growth" is shopping for growth tooling). Used for careers-page
+ # scanning and job-board discovery. Empty = fall back to titles above.
+ hiring_signals: []
channels:
email:
diff --git a/harvey/agents/scout.py b/harvey/agents/scout.py
index e922f98..dfbf45d 100644
--- a/harvey/agents/scout.py
+++ b/harvey/agents/scout.py
@@ -29,6 +29,7 @@ import json
import logging
import random
import re
+from datetime import datetime, timezone
from urllib.parse import parse_qs, quote_plus, urlparse
import httpx
@@ -125,6 +126,9 @@ class Scout:
strategies = []
if self.config.channels.linkedin.enabled and self.env.linkedin_email:
strategies.append(("linkedin", self._prospect_via_linkedin))
+ # Job boards first: hiring is the strongest intent signal, and the
+ # strategy self-skips when python-jobspy isn't installed.
+ strategies.append(("hiring_boards", self._prospect_via_hiring_boards))
strategies.append(("profile_search", self._prospect_via_profile_search))
strategies.append(("company_discovery", self._prospect_via_company_discovery))
@@ -655,48 +659,26 @@ class Scout:
source_url=company.get("source_url", ""),
)
+ # Buying signals: what they run, and whether they're hiring for
+ # roles that suggest they're in-market. Signals are gold for
+ # personalization — reference something true and current.
+ signal_note = ""
try:
- team_members = await self._scrape_team_page(domain)
- except Exception as e:
- logger.debug(f"Team scrape failed for {domain}: {e}")
- team_members = []
-
- for member in team_members:
- title = member.get("title", "")
- if not self._title_matches_icp(title):
- continue
-
- first_name = member.get("first_name", "")
- last_name = member.get("last_name", "")
- if not first_name or not last_name:
- continue
-
- email, email_status = await self._resolve_email(
- first_name, last_name, domain
+ signal_note = await self._enrich_company_signals(
+ company_id, domain, homepage_html=company.get("_homepage_html", "")
)
+ except Exception as e:
+ logger.debug(f"Signal enrichment failed for {domain}: {e}")
- prospect = Prospect(
- first_name=first_name,
- last_name=last_name,
- email=email,
- email_status=email_status,
- email_verified=(email_status == "verified"),
- company=company.get("name") or self._domain_to_name(domain),
- company_id=company_id,
- title=title,
- seniority=self._infer_seniority(title),
- industry=company.get("industry", default_industry),
- source="company_website",
- source_url=f"https://{domain}",
- )
-
- if not prospect.is_valid():
- continue
- if await self._is_duplicate_prospect(prospect):
- continue
-
- self._remember_prospect(prospect)
- all_contacts.append(prospect)
+ contacts = await self._contacts_from_company(
+ company_id=company_id,
+ domain=domain,
+ company_name=company.get("name") or self._domain_to_name(domain),
+ industry=company.get("industry", default_industry),
+ signal_note=signal_note,
+ source="company_website",
+ )
+ all_contacts.extend(contacts)
if not all_contacts:
logger.info("Scout: No ICP-matching contacts found on team pages.")
@@ -1047,6 +1029,11 @@ Respond ONLY with the JSON array."""
elif contact.email:
score += 1
+ # Timely buying signals (hiring for a relevant role right now)
+ # outperform static fit — reward them strongly.
+ if "Signal: hiring" in (contact.personalization_notes or ""):
+ score += 10
+
return max(1, min(100, score))
# ── Shared utilities ──
@@ -1092,6 +1079,9 @@ Respond ONLY with the JSON array."""
if resp is None:
return info
+ # Keep the raw HTML so signal detection reuses this fetch.
+ info["_homepage_html"] = resp.text
+
soup = self._safe_soup(resp.text)
if soup is None:
return info
@@ -1198,6 +1188,298 @@ Respond ONLY with the JSON array."""
unique.append(m)
return unique
+ async def _contacts_from_company(
+ self,
+ company_id: str,
+ domain: str,
+ company_name: str,
+ industry: str,
+ signal_note: str = "",
+ source: str = "company_website",
+ ) -> list[Prospect]:
+ """Team-page scrape → ICP-matched, email-resolved, deduped prospects."""
+ try:
+ team_members = await self._scrape_team_page(domain)
+ except Exception as e:
+ logger.debug(f"Team scrape failed for {domain}: {e}")
+ return []
+
+ contacts: list[Prospect] = []
+ for member in team_members:
+ title = member.get("title", "")
+ if not self._title_matches_icp(title):
+ continue
+
+ first_name = member.get("first_name", "")
+ last_name = member.get("last_name", "")
+ if not first_name or not last_name:
+ continue
+
+ email, email_status = await self._resolve_email(
+ first_name, last_name, domain
+ )
+
+ prospect = Prospect(
+ first_name=first_name,
+ last_name=last_name,
+ email=email,
+ email_status=email_status,
+ email_verified=(email_status == "verified"),
+ company=company_name,
+ company_id=company_id,
+ title=title,
+ seniority=self._infer_seniority(title),
+ industry=industry,
+ source=source,
+ source_url=f"https://{domain}",
+ personalization_notes=signal_note,
+ )
+
+ if not prospect.is_valid():
+ continue
+ if await self._is_duplicate_prospect(prospect):
+ continue
+
+ self._remember_prospect(prospect)
+ contacts.append(prospect)
+ return contacts
+
+ # ── Strategy 4: Job boards — companies hiring for signal roles ──
+
+ async def _prospect_via_hiring_boards(self) -> int:
+ """Discover companies via job postings — the strongest intent signal.
+
+ A company actively hiring a relevant role is in-market *right now*.
+ Uses python-jobspy when installed (optional dependency:
+ `pip install python-jobspy`); silently skipped otherwise.
+ """
+ try:
+ from jobspy import scrape_jobs
+ except ImportError:
+ logger.debug("Scout: python-jobspy not installed; skipping job boards.")
+ return 0
+
+ keywords = self._signal_role_keywords()
+ if not keywords:
+ return 0
+ search_term = keywords[0]
+ geo = self.config.icp.geography[0] if self.config.icp.geography else ""
+
+ logger.info(f"Scout: Searching job boards for '{search_term}' roles...")
+ loop = asyncio.get_event_loop()
+
+ def _search():
+ return scrape_jobs(
+ site_name=["indeed"],
+ search_term=search_term,
+ location=geo,
+ results_wanted=15,
+ hours_old=24 * 14, # fresh signal only: last two weeks
+ )
+
+ try:
+ df = await asyncio.wait_for(
+ loop.run_in_executor(None, _search), timeout=120
+ )
+ except Exception as e:
+ logger.warning(f"Scout: job-board search failed: {e}")
+ return 0
+ if df is None or getattr(df, "empty", True):
+ return 0
+
+ default_industry = (
+ self.config.icp.industries[0] if self.config.icp.industries else ""
+ )
+ today = datetime.now(timezone.utc).date().isoformat()
+ all_contacts: list[Prospect] = []
+ companies_used = 0
+
+ try:
+ rows = df.to_dict("records")
+ except Exception:
+ return 0
+
+ seen_names: set[str] = set()
+ for row in rows:
+ if companies_used >= 5:
+ break
+ company_name = str(row.get("company") or "").strip()
+ job_title = str(row.get("title") or "").strip()[:80]
+ if not company_name or company_name.lower() in seen_names:
+ continue
+ seen_names.add(company_name.lower())
+
+ try:
+ domain = await self._guess_domain(company_name)
+ except Exception:
+ domain = ""
+ if not self._is_candidate_domain(domain):
+ continue
+ if await self.state.company_exists(domain):
+ self._seen_domains.add(domain)
+ continue
+ self._seen_domains.add(domain)
+ companies_used += 1
+
+ info = await self._scrape_company_info(domain)
+ company_id = await self._ensure_company(
+ name=info.get("name") or company_name,
+ domain=domain,
+ website=info.get("website", f"https://{domain}"),
+ description=info.get("description", ""),
+ industry=default_industry,
+ source="job_board",
+ source_url=str(row.get("job_url") or ""),
+ )
+
+ signal = {"type": "hiring", "detail": job_title, "found_at": today}
+ try:
+ await self.state.update_company_signals(
+ company_id, new_signals=[signal]
+ )
+ except Exception as e:
+ logger.debug(f"update_company_signals failed: {e}")
+
+ signal_note = f"Signal: hiring {job_title} (posted on job board)"
+ from harvey.integrations.tech_detect import detect_tech
+ tech = detect_tech(info.get("_homepage_html", ""))
+ if tech:
+ await self.state.update_company_signals(company_id, tech_stack=tech)
+ signal_note += ". Tech on site: " + ", ".join(tech[:5])
+
+ contacts = await self._contacts_from_company(
+ company_id=company_id,
+ domain=domain,
+ company_name=info.get("name") or company_name,
+ industry=default_industry,
+ signal_note=signal_note[:400],
+ source="job_board",
+ )
+ all_contacts.extend(contacts)
+
+ if not all_contacts:
+ logger.info("Scout: job-board sweep found no ICP-matching contacts.")
+ return 0
+
+ scored = await self._score_contacts(all_contacts)
+ count = 0
+ for prospect in scored:
+ await self.state.add_prospect(prospect)
+ count += 1
+ logger.info(
+ f"Scout: Added {prospect.full_name()} ({prospect.title}) "
+ f"at {prospect.company} via job-board signal [score: {prospect.score}]"
+ )
+ if count >= MAX_PROSPECTS_PER_CYCLE:
+ break
+ return count
+
+ # ── Buying signals (tech stack + hiring) ──
+
+ def _signal_role_keywords(self) -> list[str]:
+ """Role keywords that indicate in-market intent (config or ICP titles)."""
+ keywords = [
+ k.strip().lower()
+ for k in (getattr(self.config.icp, "hiring_signals", None) or [])
+ if k.strip()
+ ]
+ if keywords:
+ return keywords
+ return [t.strip().lower() for t in self.config.icp.titles if t.strip()]
+
+ async def _enrich_company_signals(
+ self, company_id: str, domain: str, homepage_html: str = ""
+ ) -> str:
+ """Detect tech stack + hiring signals, persist them, return a note.
+
+ The returned note seeds prospects' personalization_notes so the
+ Writer references something true and current instead of flattery.
+ """
+ from harvey.integrations.tech_detect import detect_tech
+
+ if not homepage_html:
+ resp = await self._fetch(
+ f"https://{domain}", timeout=SCRAPE_TIMEOUT, retries=1
+ )
+ homepage_html = resp.text if resp is not None else ""
+
+ tech = detect_tech(homepage_html)
+
+ signals: list[dict] = []
+ try:
+ hiring_roles = await self._scrape_hiring_signals(domain)
+ except Exception as e:
+ logger.debug(f"Hiring scan failed for {domain}: {e}")
+ hiring_roles = []
+ today = datetime.now(timezone.utc).date().isoformat()
+ for role in hiring_roles:
+ signals.append({"type": "hiring", "detail": role, "found_at": today})
+
+ if tech or signals:
+ try:
+ await self.state.update_company_signals(
+ company_id, tech_stack=tech, new_signals=signals
+ )
+ except Exception as e:
+ logger.debug(f"update_company_signals failed for {domain}: {e}")
+
+ notes = []
+ if hiring_roles:
+ notes.append("Signal: hiring " + ", ".join(hiring_roles[:2]))
+ if tech:
+ notes.append("Tech on site: " + ", ".join(tech[:5]))
+ note = ". ".join(notes)
+ if note:
+ logger.info(f"Scout: signals for {domain} — {note}")
+ return note[:400]
+
+ _CAREERS_PATHS = ("/careers", "/jobs", "/careers/", "/join-us", "/join",
+ "/about/careers", "/company/careers", "/work-with-us")
+
+ async def _scrape_hiring_signals(self, domain: str) -> list[str]:
+ """Scan the company's careers page for open roles matching our
+ signal keywords. Returns matched role titles (deduped, capped)."""
+ keywords = self._signal_role_keywords()
+ if not keywords:
+ return []
+
+ for path in self._CAREERS_PATHS:
+ resp = await self._fetch(
+ f"https://{domain}{path}", timeout=SCRAPE_TIMEOUT, retries=1
+ )
+ if resp is None:
+ continue
+ soup = self._safe_soup(resp.text)
+ if soup is None:
+ continue
+
+ roles: list[str] = []
+ seen = set()
+ try:
+ elements = soup.select("a, h2, h3, h4, li")
+ except Exception:
+ elements = []
+ for el in elements[:400]:
+ text = re.sub(r"\s+", " ", el.get_text()).strip()
+ if not (4 <= len(text) <= 80):
+ continue
+ low = text.lower()
+ if not any(k in low for k in keywords):
+ continue
+ key = low[:60]
+ if key in seen:
+ continue
+ seen.add(key)
+ roles.append(text[:80])
+ if len(roles) >= 3:
+ return roles
+ if roles:
+ return roles
+ # A reachable careers page with no keyword hits still means we
+ # checked — don't try more paths for this domain.
+ return []
+ return []
+
async def _learn_pattern_from_page(self, soup, html: str, domain: str):
"""Find a real on-domain email on a page and cache the derived pattern.
diff --git a/harvey/cli.py b/harvey/cli.py
index 56b7c44..813c73e 100644
--- a/harvey/cli.py
+++ b/harvey/cli.py
@@ -217,6 +217,44 @@ def cmd_usage(args):
asyncio.run(_usage())
+def cmd_export(args):
+ """Export the prospect list as a sequencer-ready CSV."""
+ from harvey.state import StateManager
+ from harvey.export import export_prospects_csv
+
+ async def _export():
+ state = StateManager()
+ await state.init_db()
+
+ email_statuses = None
+ if args.email_status:
+ email_statuses = [s.strip() for s in args.email_status.split(",") if s.strip()]
+ statuses = None
+ if args.status:
+ statuses = [s.strip() for s in args.status.split(",") if s.strip()]
+
+ count, _ = await export_prospects_csv(
+ state,
+ out_path=args.out,
+ email_statuses=email_statuses,
+ min_score=args.min_score,
+ statuses=statuses,
+ include_all=args.all,
+ )
+ scope = "all prospects" if args.all else (
+ f"email status {email_statuses or ['verified', 'risky']}"
+ + (f", score >= {args.min_score}" if args.min_score else "")
+ )
+ print(f"\n Exported {count} prospect(s) to {args.out} ({scope})")
+ if count == 0 and not args.all:
+ print(" Tip: no deliverable emails yet? Add a REOON_API_KEY to .env so")
+ print(" Harvey can verify addresses, or use --all for the raw list.\n")
+ else:
+ print(" The CSV imports directly into Instantly, Smartlead, or any sequencer.\n")
+
+ asyncio.run(_export())
+
+
def main():
from harvey.paths import PROJECT_ROOT
project_root = str(PROJECT_ROOT)
@@ -261,6 +299,20 @@ def main():
sub = subparsers.add_parser("status", help="Show pipeline status")
sub.set_defaults(func=cmd_status)
+ # harvey export
+ sub = subparsers.add_parser(
+ "export", help="Export prospects as a sequencer-ready CSV"
+ )
+ sub.add_argument("--out", default="prospects.csv", help="Output file (default: prospects.csv)")
+ sub.add_argument(
+ "--email-status", default="",
+ help="Comma-separated statuses to include (default: verified,risky)",
+ )
+ sub.add_argument("--min-score", type=int, default=0, help="Minimum ICP score")
+ sub.add_argument("--status", default="", help="Comma-separated pipeline statuses (e.g. new,queued)")
+ sub.add_argument("--all", action="store_true", help="Export everything, no filters")
+ sub.set_defaults(func=cmd_export)
+
# harvey usage
sub = subparsers.add_parser("usage", help="Show Claude usage and quota")
sub.add_argument("--days", type=int, default=30, help="Breakdown window (default: 30)")
diff --git a/harvey/config.py b/harvey/config.py
index e9c437b..ca85b0a 100644
--- a/harvey/config.py
+++ b/harvey/config.py
@@ -56,6 +56,10 @@ class ICPConfig(BaseModel):
company_size: str
titles: list[str]
geography: list[str]
+ # Role keywords that indicate a company is in-market right now (a company
+ # hiring a "Head of Growth" is buying growth tooling). Empty → falls back
+ # to `titles`. Used for careers-page scanning and job-board discovery.
+ hiring_signals: list[str] = []
class EmailChannelConfig(BaseModel):
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index 74b3021..6885eb3 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -572,6 +572,30 @@ async def get_prospects():
return rows
[email protected]("/api/export/prospects.csv")
+async def export_prospects(all: bool = False, min_score: int = 0, email_status: str = ""):
+ """Sequencer-ready CSV download of the prospect list."""
+ from fastapi.responses import PlainTextResponse
+ from harvey.state import StateManager
+ from harvey.export import export_prospects_csv
+
+ state = StateManager(db_path=str(DB_PATH))
+ try:
+ await state.init_db()
+ statuses = [s.strip() for s in email_status.split(",") if s.strip()] or None
+ _, text = await export_prospects_csv(
+ state, email_statuses=statuses, min_score=min_score, include_all=all,
+ )
+ except Exception as e:
+ logger.warning("Prospect export failed: %s", e)
+ text = ""
+ return PlainTextResponse(
+ text,
+ media_type="text/csv",
+ headers={"Content-Disposition": 'attachment; filename="prospects.csv"'},
+ )
+
+
@app.get("/api/campaigns")
async def get_campaigns():
rows = await query_db("SELECT * FROM campaigns ORDER BY created_at DESC LIMIT 100")
@@ -1106,7 +1130,13 @@ DASHBOARD_HTML = r"""<!DOCTYPE html>
<!-- Contacts -->
<div id="prospects" class="section">
- <div class="section-head"><h2>Contacts</h2><p>People Harvey has found and verified.</p></div>
+ <div class="section-head" style="display:flex;align-items:flex-end;justify-content:space-between;gap:16px">
+ <div><h2>Contacts</h2><p>People Harvey has found and verified.</p></div>
+ <div style="display:flex;gap:8px;flex-shrink:0">
+ <a class="btn btn-secondary btn-sm" href="/api/export/prospects.csv" download>Export deliverable CSV</a>
+ <a class="btn btn-secondary btn-sm" href="/api/export/prospects.csv?all=true" download>Export all</a>
+ </div>
+ </div>
<div id="prospects-table"></div>
</div>
diff --git a/harvey/export.py b/harvey/export.py
new file mode 100644
index 0000000..1013787
--- /dev/null
+++ b/harvey/export.py
@@ -0,0 +1,123 @@
+"""Prospect-list export — the list itself is the product.
+
+Produces a CSV that drops straight into Instantly, Smartlead, or any
+sequencer (email / first_name / last_name / company_name / personalization
+columns), plus Harvey's own quality columns (score, email_status, signals)
+so a human can eyeball what they're getting.
+"""
+
+import csv
+import io
+import logging
+
+from harvey.state import StateManager
+
+logger = logging.getLogger("harvey.export")
+
+# Column order chosen so the file imports cleanly into cold-email tools
+# without remapping; extra columns are simply available as custom variables.
+CSV_COLUMNS = [
+ "email", "first_name", "last_name", "company_name", "title",
+ "website", "linkedin_url", "industry", "personalization",
+ "email_status", "score", "seniority", "source", "status", "created_at",
+]
+
+DEFAULT_EMAIL_STATUSES = ["verified", "risky"]
+
+
+async def collect_prospects(
+ state: StateManager,
+ email_statuses: list[str] | None = None,
+ min_score: int = 0,
+ statuses: list[str] | None = None,
+ include_all: bool = False,
+) -> list[dict]:
+ """Fetch prospects matching the filters as export-ready dicts.
+
+ Default view is the *deliverable* list (verified + risky emails).
+ ``include_all`` disables every filter for a full dump.
+ """
+ import aiosqlite
+
+ where = []
+ params: list = []
+ if not include_all:
+ wanted = email_statuses if email_statuses is not None else DEFAULT_EMAIL_STATUSES
+ if wanted:
+ placeholders = ",".join("?" for _ in wanted)
+ where.append(f"email != '' AND email_status IN ({placeholders})")
+ params.extend(wanted)
+ if min_score > 0:
+ where.append("score >= ?")
+ params.append(min_score)
+ if statuses:
+ placeholders = ",".join("?" for _ in statuses)
+ where.append(f"status IN ({placeholders})")
+ params.extend(statuses)
+
+ sql = "SELECT * FROM prospects"
+ if where:
+ sql += " WHERE " + " AND ".join(where)
+ sql += " ORDER BY score DESC, created_at DESC"
+
+ async with aiosqlite.connect(state.db_path) as db:
+ db.row_factory = aiosqlite.Row
+ async with db.execute(sql, params) as cursor:
+ rows = [dict(r) for r in await cursor.fetchall()]
+
+ out = []
+ for r in rows:
+ out.append({
+ "email": r.get("email", ""),
+ "first_name": r.get("first_name", ""),
+ "last_name": r.get("last_name", ""),
+ "company_name": r.get("company", ""),
+ "title": r.get("title", ""),
+ "website": r.get("source_url", ""),
+ "linkedin_url": r.get("linkedin_url", ""),
+ "industry": r.get("industry", ""),
+ "personalization": r.get("personalization_notes", ""),
+ "email_status": r.get("email_status", ""),
+ "score": r.get("score", 0),
+ "seniority": r.get("seniority", ""),
+ "source": r.get("source", ""),
+ "status": r.get("status", ""),
+ "created_at": r.get("created_at", ""),
+ })
+ return out
+
+
+def to_csv(rows: list[dict]) -> str:
+ buf = io.StringIO()
+ writer = csv.DictWriter(buf, fieldnames=CSV_COLUMNS, extrasaction="ignore")
+ writer.writeheader()
+ for row in rows:
+ writer.writerow(row)
+ return buf.getvalue()
+
+
+async def export_prospects_csv(
+ state: StateManager,
+ out_path: str | None = None,
+ email_statuses: list[str] | None = None,
+ min_score: int = 0,
+ statuses: list[str] | None = None,
+ include_all: bool = False,
+) -> tuple[int, str]:
+ """Export prospects to CSV. Returns (row_count, csv_text).
+
+ Writes to ``out_path`` when given; caller handles printing/serving.
+ """
+ rows = await collect_prospects(
+ state,
+ email_statuses=email_statuses,
+ min_score=min_score,
+ statuses=statuses,
+ include_all=include_all,
+ )
+ text = to_csv(rows)
+ if out_path:
+ with open(out_path, "w", newline="") as f:
+ f.write(text)
+ logger.info(f"Exported {len(rows)} prospects to {out_path}")
+ return len(rows), text
diff --git a/harvey/integrations/tech_detect.py b/harvey/integrations/tech_detect.py
new file mode 100644
index 0000000..f40fbdb
--- /dev/null
+++ b/harvey/integrations/tech_detect.py
@@ -0,0 +1,92 @@
+"""Tech-stack detection — what tools a company's website reveals.
+
+A curated subset of Wappalyzer-style fingerprints matched against HTML
+Harvey already downloads while researching a company. Zero extra network
+requests, zero dependencies. Knowing a prospect runs Shopify / HubSpot /
+Intercom (or conspicuously lacks something) is a concrete, verifiable
+personalization hook — the kind that actually earns replies.
+
+Patterns are intentionally conservative: match distinctive script hosts,
+cookie names, or generator tags — not generic words — so false positives
+stay rare.
+"""
+
+import re
+
+# name -> list of regexes; any match counts. Compiled lazily, matched
+# case-insensitively against the raw HTML.
+FINGERPRINTS: dict[str, list[str]] = {
+ # CMS / site builders
+ "WordPress": [r"wp-content/", r"wp-includes/", r'<meta name="generator" content="WordPress'],
+ "Shopify": [r"cdn\.shopify\.com", r"myshopify\.com"],
+ "Wix": [r"static\.parastorage\.com", r"wix\.com/website-builder"],
+ "Squarespace": [r"static1\.squarespace\.com", r'<!-- This is Squarespace'],
+ "Webflow": [r"assets\.website-files\.com", r'data-wf-domain'],
+ "Framer": [r"framerusercontent\.com"],
+ "Drupal": [r'<meta name="generator" content="Drupal', r"sites/default/files"],
+ "Ghost": [r'<meta name="generator" content="Ghost'],
+ "Next.js": [r"/_next/static/"],
+ "Gatsby": [r"/page-data/app-data\.json", r"id=\"___gatsby\""],
+
+ # Analytics / tracking
+ "Google Analytics": [r"googletagmanager\.com/gtag", r"google-analytics\.com/analytics\.js"],
+ "Google Tag Manager": [r"googletagmanager\.com/gtm\.js"],
+ "Segment": [r"cdn\.segment\.com/analytics\.js"],
+ "Mixpanel": [r"cdn\.mxpnl\.com"],
+ "Hotjar": [r"static\.hotjar\.com"],
+ "Plausible": [r"plausible\.io/js"],
+ "Meta Pixel": [r"connect\.facebook\.net/[^\"']*fbevents\.js"],
+
+ # Marketing / CRM
+ "HubSpot": [r"js\.hs-scripts\.com", r"js\.hsforms\.net", r"hubspot\.com/api"],
+ "Marketo": [r"munchkin\.marketo\.net"],
+ "Mailchimp": [r"chimpstatic\.com", r"list-manage\.com/subscribe"],
+ "Klaviyo": [r"static\.klaviyo\.com"],
+ "ActiveCampaign": [r"trackcmp\.net"],
+ "Salesforce": [r"force\.com", r"salesforce\.com/embeddedservice"],
+
+ # Chat / support
+ "Intercom": [r"widget\.intercom\.io", r"js\.intercomcdn\.com"],
+ "Drift": [r"js\.driftt\.com"],
+ "Zendesk": [r"static\.zdassets\.com", r"zendesk\.com/embeddable"],
+ "Crisp": [r"client\.crisp\.chat"],
+ "Tidio": [r"code\.tidio\.co"],
+ "LiveChat": [r"cdn\.livechatinc\.com"],
+
+ # Scheduling / payments
+ "Calendly": [r"assets\.calendly\.com", r"calendly\.com/[\w\-]+/"],
+ "Stripe": [r"js\.stripe\.com"],
+ "Typeform": [r"embed\.typeform\.com"],
+
+ # E-commerce (non-Shopify)
+ "WooCommerce": [r"woocommerce", r"wc-ajax"],
+ "BigCommerce": [r"cdn\d*\.bigcommerce\.com"],
+
+ # Hosting/infra hints
+ "Cloudflare": [r"/cdn-cgi/"],
+ "Vercel": [r"vercel\.app", r"x-vercel"],
+}
+
+_compiled: dict[str, list[re.Pattern]] | None = None
+
+
+def _get_compiled() -> dict[str, list[re.Pattern]]:
+ global _compiled
+ if _compiled is None:
+ _compiled = {
+ name: [re.compile(p, re.IGNORECASE) for p in patterns]
+ for name, patterns in FINGERPRINTS.items()
+ }
+ return _compiled
+
+
+def detect_tech(html: str, max_bytes: int = 300_000) -> list[str]:
+ """Return the tools detectable in a page's HTML, alphabetized."""
+ if not html:
+ return []
+ sample = html[:max_bytes]
+ found = []
+ for name, patterns in _get_compiled().items():
+ if any(p.search(sample) for p in patterns):
+ found.append(name)
+ return sorted(found)
diff --git a/harvey/models/company.py b/harvey/models/company.py
index 86e2f27..c3f29d6 100644
--- a/harvey/models/company.py
+++ b/harvey/models/company.py
@@ -22,6 +22,10 @@ class Company(BaseModel):
source: str = "" # how we found them: google_dork, linkedin, company_scrape
source_url: str = "" # specific URL where we found the info
notes: str = ""
+ # Buying signals: detected tools on their site, and timely triggers
+ # (hiring, funding, ...) as [{"type": ..., "detail": ..., "found_at": ...}]
+ tech_stack: list[str] = Field(default_factory=list)
+ signals: list[dict] = Field(default_factory=list)
created_at: datetime = Field(default_factory=_utcnow)
updated_at: datetime = Field(default_factory=_utcnow)
diff --git a/harvey/state.py b/harvey/state.py
index e670c81..c9eacbe 100644
--- a/harvey/state.py
+++ b/harvey/state.py
@@ -242,6 +242,11 @@ MIGRATIONS: list[str] = [
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""",
+ # ── v5: buying signals on companies (tech stack, hiring, etc.) ──
+ """
+ ALTER TABLE companies ADD COLUMN tech_stack_json TEXT DEFAULT '[]';
+ ALTER TABLE companies ADD COLUMN signals_json TEXT DEFAULT '[]';
+ """,
]
# Column whitelists for dynamic UPDATEs (prevents SQL injection via kwargs).
@@ -292,6 +297,18 @@ class StateManager:
# ── Companies ──
+ @staticmethod
+ def _company_from_row(row: aiosqlite.Row) -> Company:
+ d = dict(row)
+ for json_col, field in (("tech_stack_json", "tech_stack"), ("signals_json", "signals")):
+ raw = d.pop(json_col, None)
+ try:
+ parsed = json.loads(raw) if raw else []
+ except (json.JSONDecodeError, TypeError):
+ parsed = []
+ d[field] = parsed if isinstance(parsed, list) else []
+ return Company(**d)
+
async def add_company(self, company: Company) -> str:
"""Insert a company. If one with the same domain exists, return its id."""
if not company.id:
@@ -302,13 +319,14 @@ class StateManager:
"""INSERT OR IGNORE INTO companies
(id, name, domain, website, description, industry,
company_size, location, source, source_url, notes,
- created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ tech_stack_json, signals_json, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
company.id, company.name, company.domain, company.website,
company.description, company.industry, company.company_size,
company.location, company.source, company.source_url,
company.notes,
+ json.dumps(company.tech_stack), json.dumps(company.signals),
company.created_at.isoformat(),
company.updated_at.isoformat(),
),
@@ -324,6 +342,57 @@ class StateManager:
company.id = row[0]
return company.id
+ async def update_company_signals(
+ self,
+ company_id: str,
+ tech_stack: list[str] | None = None,
+ new_signals: list[dict] | None = None,
+ ):
+ """Merge freshly-detected tech + signals into a company record.
+
+ Signals are appended with dedup on (type, detail) so re-scans
+ don't multiply the same finding.
+ """
+ async with self._connect() as db:
+ db.row_factory = aiosqlite.Row
+ async with db.execute(
+ "SELECT tech_stack_json, signals_json FROM companies WHERE id = ?",
+ (company_id,),
+ ) as cursor:
+ row = await cursor.fetchone()
+ if not row:
+ return
+
+ def _load(raw):
+ try:
+ parsed = json.loads(raw) if raw else []
+ except (json.JSONDecodeError, TypeError):
+ parsed = []
+ return parsed if isinstance(parsed, list) else []
+
+ tech = _load(row["tech_stack_json"])
+ signals = _load(row["signals_json"])
+
+ for t in tech_stack or []:
+ if t not in tech:
+ tech.append(t)
+ seen = {(s.get("type"), s.get("detail")) for s in signals if isinstance(s, dict)}
+ for s in new_signals or []:
+ if not isinstance(s, dict):
+ continue
+ if (s.get("type"), s.get("detail")) in seen:
+ continue
+ signals.append(s)
+ seen.add((s.get("type"), s.get("detail")))
+
+ await db.execute(
+ "UPDATE companies SET tech_stack_json = ?, signals_json = ?, "
+ "updated_at = ? WHERE id = ?",
+ (json.dumps(tech), json.dumps(signals),
+ _utcnow().isoformat(), company_id),
+ )
+ await db.commit()
+
async def get_company(self, company_id: str) -> Company | None:
async with self._connect() as db:
db.row_factory = aiosqlite.Row
@@ -331,7 +400,7 @@ class StateManager:
"SELECT * FROM companies WHERE id = ?", (company_id,)
) as cursor:
row = await cursor.fetchone()
- return Company(**dict(row)) if row else None
+ return self._company_from_row(row) if row else None
async def get_company_by_domain(self, domain: str) -> Company | None:
async with self._connect() as db:
@@ -340,7 +409,7 @@ class StateManager:
"SELECT * FROM companies WHERE domain = ?", (_norm(domain),)
) as cursor:
row = await cursor.fetchone()
- return Company(**dict(row)) if row else None
+ return self._company_from_row(row) if row else None
async def get_contacts_for_company(self, company_id: str) -> list[Prospect]:
async with self._connect() as db:
diff --git a/tests/test_signals_export.py b/tests/test_signals_export.py
new file mode 100644
index 0000000..1f66781
--- /dev/null
+++ b/tests/test_signals_export.py
@@ -0,0 +1,157 @@
+"""Tests for tech detection, company signals storage, and prospect export."""
+
+import os
+import tempfile
+
+import pytest
+import pytest_asyncio
+
+from harvey.state import StateManager
+from harvey.models.company import Company
+from harvey.models.prospect import Prospect
+from harvey.integrations.tech_detect import detect_tech
+from harvey.export import collect_prospects, export_prospects_csv, to_csv, CSV_COLUMNS
+
+
+@pytest_asyncio.fixture
+async def state():
+ with tempfile.TemporaryDirectory() as tmpdir:
+ sm = StateManager(os.path.join(tmpdir, "test.db"))
+ await sm.init_db()
+ yield sm
+
+
+# ── tech detection ──
+
+
+def test_detect_tech_matches_known_fingerprints():
+ html = """
+ <html><head>
+ <script src="https://js.hs-scripts.com/12345.js"></script>
+ <script src="https://widget.intercom.io/widget/abc"></script>
+ <link href="https://cdn.shopify.com/s/files/theme.css">
+ <script src="https://www.googletagmanager.com/gtag/js?id=G-1"></script>
+ </head><body>wp-content/themes/foo</body></html>
+ """
+ found = detect_tech(html)
+ assert "HubSpot" in found
+ assert "Intercom" in found
+ assert "Shopify" in found
+ assert "Google Analytics" in found
+ assert "WordPress" in found
+ assert found == sorted(found)
+
+
+def test_detect_tech_no_false_positives_on_plain_page():
+ html = "<html><body><h1>Welcome to Acme Plumbing</h1><p>Call us.</p></body></html>"
+ assert detect_tech(html) == []
+ assert detect_tech("") == []
+
+
+# ── company signals storage ──
+
+
+async def test_company_signals_roundtrip_and_merge(state):
+ cid = await state.add_company(Company(
+ name="Acme", domain="acme.com",
+ tech_stack=["Shopify"], signals=[{"type": "hiring", "detail": "Head of Growth"}],
+ ))
+ fetched = await state.get_company(cid)
+ assert fetched.tech_stack == ["Shopify"]
+ assert fetched.signals[0]["detail"] == "Head of Growth"
+
+ # Merge: new tech appends, duplicate signal is ignored
+ await state.update_company_signals(
+ cid,
+ tech_stack=["Shopify", "Intercom"],
+ new_signals=[
+ {"type": "hiring", "detail": "Head of Growth"}, # dup
+ {"type": "hiring", "detail": "Growth Marketer"}, # new
+ ],
+ )
+ fetched = await state.get_company(cid)
+ assert fetched.tech_stack == ["Shopify", "Intercom"]
+ assert len(fetched.signals) == 2
+
+
+async def test_legacy_company_rows_parse(state):
+ """Rows written before v5 (empty JSON columns) must still load."""
+ import aiosqlite
+ async with aiosqlite.connect(state.db_path) as db:
+ await db.execute(
+ "INSERT INTO companies (id, name, domain, tech_stack_json, signals_json) "
+ "VALUES ('c1', 'Old Co', 'old.com', '', 'not-json')"
+ )
+ await db.commit()
+ company = await state.get_company("c1")
+ assert company.tech_stack == []
+ assert company.signals == []
+
+
+# ── export ──
+
+
+async def _seed_prospects(state):
+ specs = [
+ ("Ada", "verified", 85, "new"),
+ ("Bob", "risky", 70, "new"),
+ ("Cal", "guess", 90, "new"),
+ ("Dee", "verified", 40, "contacted"),
+ ("Eve", "", 0, "new"), # no email
+ ]
+ for name, estatus, score, status in specs:
+ await state.add_prospect(Prospect(
+ first_name=name, last_name="Test", title="VP Marketing",
+ email=(f"{name.lower()}@acme.com" if estatus else ""),
+ email_status=estatus, email_verified=(estatus == "verified"),
+ score=score, status=status, company="Acme",
+ personalization_notes="Signal: hiring Growth Lead",
+ ))
+
+
+async def test_collect_prospects_default_deliverable_only(state):
+ await _seed_prospects(state)
+ rows = await collect_prospects(state)
+ names = {r["first_name"] for r in rows}
+ # verified + risky only; guess/no-email excluded
+ assert names == {"Ada", "Bob", "Dee"}
+ # sorted by score desc
+ assert rows[0]["first_name"] == "Ada"
+
+
+async def test_collect_prospects_filters(state):
+ await _seed_prospects(state)
+ rows = await collect_prospects(state, min_score=60, statuses=["new"])
+ assert {r["first_name"] for r in rows} == {"Ada", "Bob"}
+
+ rows = await collect_prospects(state, email_statuses=["verified"])
+ assert {r["first_name"] for r in rows} == {"Ada", "Dee"}
+
+ rows = await collect_prospects(state, include_all=True)
+ assert len(rows) == 5
+
+
+async def test_export_csv_shape(state, tmp_path):
+ await _seed_prospects(state)
+ out = str(tmp_path / "prospects.csv")
+ count, text = await export_prospects_csv(state, out_path=out)
+ assert count == 3
+ assert os.path.exists(out)
+
+ lines = text.strip().splitlines()
+ header = lines[0].split(",")
+ assert header == CSV_COLUMNS
+ assert any("[email protected]" in line for line in lines[1:])
+ # Personalization/signal text survives export
+ assert any("Signal: hiring Growth Lead" in line for line in lines[1:])
+
+
+def test_to_csv_ignores_extra_keys():
+ text = to_csv([{**{c: "" for c in CSV_COLUMNS}, "email": "[email protected]", "junk": "x"}])
+ assert "junk" not in text.splitlines()[0]
+ assert "[email protected]" in text