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.
Prospecting rebuild, part 1: observation model + user-confirmed signals
Ethan99d0e48a7861
diff --git a/harvey/signals.py b/harvey/signals.pynew file mode 100644index 0000000..1b62eae--- /dev/null+++ b/harvey/signals.py@@ -0,0 +1,258 @@+"""The signal vocabulary Harvey proposes, and the user confirms.++Harvey never decides on its own what makes a good prospect. It proposes a+catalog of signals it knows how to collect — each with a plain-language+description, what it costs, and why it might matter — and the user confirms,+edits, or rejects them in the dashboard before any collection runs.++Only ``confirmed`` signals get collected. That keeps spend intentional and+keeps the resulting cohorts explainable: a prospect list is a query over+signals a human chose, not a black box.++Design note: every signal is recorded as an OBSERVATION (a row), never a+column. A new signal needs no migration, history comes free, and confidence+and provenance travel with the fact.+"""++# category: discovery | profile | people | verification+# value_type: num | text | bool+# cost_note: what collecting it actually costs, in plain language+SIGNAL_CATALOG: list[dict] = [+ # ── Discovery: who exists, and how visible are they ──+ {+ "code": "SERP_RANK",+ "label": "Search rank position",+ "description": (+ "Where the business ranks for its core '<service> <city>' search. "+ "The most useful prospecting signal there is: positions 11-30 are "+ "the sweet spot — visible enough to be trying, not winning yet. "+ "Top 10 are already winning (harder sell); 31+ are cheaper but "+ "less motivated."+ ),+ "category": "discovery",+ "value_type": "num",+ "collector": "discover",+ "cost_note": "~$0.0006 per search (paid SERP API, queued endpoint)",+ "confidence_floor": 0.0,+ },+ {+ "code": "FOUND_IN_SERP",+ "label": "Discovered via search",+ "description": "The business appeared in a target-market search — how Harvey found it at all.",+ "category": "discovery",+ "value_type": "text",+ "collector": "discover",+ "cost_note": "included in the search above",+ "confidence_floor": 0.0,+ },++ # ── Profile: what they are (free — HTML Harvey already fetches) ──+ {+ "code": "INCUMBENT_AGENCY",+ "label": "Has a marketing/web agency",+ "description": (+ "An agency credited in the site footer ('Website by X'). High-value: "+ "it tells you who you're displacing, and every detection builds a "+ "roster you can target as a whole book of business. Only recorded "+ "when the credit wording is explicit — a wrong incumbent is worse "+ "than none."+ ),+ "category": "profile",+ "value_type": "text",+ "collector": "profile",+ "cost_note": "free (homepage HTML)",+ "confidence_floor": 0.75,+ },+ {+ "code": "RUNNING_GOOGLE_ADS",+ "label": "Running Google Ads",+ "description": "Google Ads tag on the site — they are spending on acquisition TODAY. Strong budget signal.",+ "category": "profile",+ "value_type": "bool",+ "collector": "profile",+ "cost_note": "free (homepage HTML)",+ "confidence_floor": 0.0,+ },+ {+ "code": "RUNNING_META_ADS",+ "label": "Running Meta/Facebook Ads",+ "description": "Meta Pixel on the site — actively spending on paid social.",+ "category": "profile",+ "value_type": "bool",+ "collector": "profile",+ "cost_note": "free (homepage HTML)",+ "confidence_floor": 0.0,+ },+ {+ "code": "TECH_STACK",+ "label": "Website platform / tools",+ "description": "What the site is built on and which tools it runs (WordPress, Shopify, HubSpot, chat widgets, booking tools).",+ "category": "profile",+ "value_type": "text",+ "collector": "profile",+ "cost_note": "free (homepage HTML)",+ "confidence_floor": 0.0,+ },+ {+ "code": "NO_SCHEMA_MARKUP",+ "label": "Missing structured data",+ "description": "No JSON-LD schema markup — a concrete, checkable SEO gap you can name in an email.",+ "category": "profile",+ "value_type": "bool",+ "collector": "profile",+ "cost_note": "free (homepage HTML)",+ "confidence_floor": 0.0,+ },+ {+ "code": "NO_ONLINE_BOOKING",+ "label": "No online booking/scheduling",+ "description": "No booking or scheduling widget detected — leads have to phone in, so after-hours demand is lost.",+ "category": "profile",+ "value_type": "bool",+ "collector": "profile",+ "cost_note": "free (homepage HTML)",+ "confidence_floor": 0.0,+ },+ {+ "code": "SITE_PAGE_COUNT",+ "label": "Site size",+ "description": "Page count from sitemap.xml. A very thin site suggests little investment; a large stale one suggests neglect.",+ "category": "profile",+ "value_type": "num",+ "collector": "profile",+ "cost_note": "free (sitemap.xml)",+ "confidence_floor": 0.0,+ },+ {+ "code": "BLOG_STALE",+ "label": "Content gone stale",+ "description": "No new content in a long time — content marketing started and abandoned.",+ "category": "profile",+ "value_type": "num",+ "collector": "profile",+ "cost_note": "free (sitemap.xml)",+ "confidence_floor": 0.0,+ },+ {+ "code": "BLOCKS_AI_CRAWLERS",+ "label": "Blocks AI crawlers",+ "description": "robots.txt blocks AI crawlers — they'll be invisible in AI search answers.",+ "category": "profile",+ "value_type": "bool",+ "collector": "profile",+ "cost_note": "free (robots.txt)",+ "confidence_floor": 0.0,+ },+ {+ "code": "HIRING_ROLE",+ "label": "Hiring for a relevant role",+ "description": "An open role on their careers page that implies they're buying in your category right now.",+ "category": "profile",+ "value_type": "text",+ "collector": "profile",+ "cost_note": "free (careers page)",+ "confidence_floor": 0.0,+ },++ # ── People: who decides ──+ {+ "code": "CONTACT_FOUND",+ "label": "Named contact found",+ "description": "A named person scraped from the team/about page, with their title.",+ "category": "people",+ "value_type": "text",+ "collector": "people",+ "cost_note": "free (team page)",+ "confidence_floor": 0.0,+ },+ {+ "code": "DECISION_MAKER_TITLE",+ "label": "Decision-maker title",+ "description": "Title matches an owner/decision-maker pattern (Owner, President, Practice Manager, Marketing Director).",+ "category": "people",+ "value_type": "text",+ "collector": "people",+ "cost_note": "free (team page)",+ "confidence_floor": 0.0,+ },+ {+ "code": "REGISTRY_VERIFIED",+ "label": "Confirmed in a public registry",+ "description": (+ "The person was confirmed in an authoritative public registry "+ "(licensing board, professional registry). Also filters out "+ "scraping artifacts — a name that matches nothing usually wasn't a person."+ ),+ "category": "people",+ "value_type": "text",+ "collector": "people",+ "cost_note": "free (public registry API)",+ "confidence_floor": 0.0,+ },+ {+ "code": "LIKELY_OWNER",+ "label": "Likely the owner",+ "description": "Registry indicators suggest this person owns the business rather than working there.",+ "category": "people",+ "value_type": "bool",+ "collector": "people",+ "cost_note": "free (public registry API)",+ "confidence_floor": 0.0,+ },++ # ── Verification ──+ {+ "code": "EMAIL_PATTERN",+ "label": "Company email pattern",+ "description": "The domain's address format (first.last@, flast@). One real address cracks the whole company.",+ "category": "verification",+ "value_type": "text",+ "collector": "verify",+ "cost_note": "free, or ~1 lookup credit",+ "confidence_floor": 0.0,+ },+ {+ "code": "EMAIL_STATUS",+ "label": "Email deliverability",+ "description": "Whether the address is verified, catch-all/risky, an unverified guess, or invalid.",+ "category": "verification",+ "value_type": "text",+ "collector": "verify",+ "cost_note": "1 verification credit (free tiers available)",+ "confidence_floor": 0.0,+ },+ {+ "code": "CONTACT_FORM_URL",+ "label": "Contact form available",+ "description": (+ "A contact form on the site. Worth knowing because it reaches the "+ "business without needing an email address at all — and roughly "+ "half of domains can't be email-verified."+ ),+ "category": "verification",+ "value_type": "text",+ "collector": "profile",+ "cost_note": "free (site HTML)",+ "confidence_floor": 0.0,+ },+]+++async def seed_signal_catalog(state) -> int:+ """Register the catalog as PROPOSED signals awaiting user confirmation.++ Idempotent, and never overrides a decision the user already made: an+ existing signal keeps its confirmed/rejected status.+ """+ for sig in SIGNAL_CATALOG:+ await state.upsert_signal_code(+ sig["code"],+ label=sig["label"],+ description=sig["description"],+ category=sig["category"],+ value_type=sig["value_type"],+ collector=sig["collector"],+ cost_note=sig["cost_note"],+ confidence_floor=sig.get("confidence_floor", 0.0),+ )+ return len(SIGNAL_CATALOG)diff --git a/harvey/state.py b/harvey/state.pyindex d8c0d9a..9f3c6ed 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -290,6 +290,78 @@ MIGRATIONS: list[str] = [updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);""",+ # ── v7: observation model — every fact is a row, never a column ──+ """+ -- The governed vocabulary. A collector may only emit a code that exists+ -- here (enforced by the observations FK), so a typo fails loudly instead+ -- of quietly inventing a junk signal. `status` is the user-confirmation+ -- gate: Harvey PROPOSES signals, the user confirms which ones to+ -- prospect against, and only confirmed signals get collected.+ CREATE TABLE IF NOT EXISTS signal_codes (+ code TEXT PRIMARY KEY,+ label TEXT DEFAULT '',+ description TEXT DEFAULT '',+ category TEXT DEFAULT '',+ value_type TEXT DEFAULT 'text',+ collector TEXT DEFAULT '',+ cost_note TEXT DEFAULT '',+ status TEXT DEFAULT 'proposed',+ confidence_floor REAL DEFAULT 0.0,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ );++ -- One row per fact. Confidence and provenance travel WITH the fact, and+ -- re-observing the same signal over time is a free time series.+ CREATE TABLE IF NOT EXISTS observations (+ id TEXT PRIMARY KEY,+ company_id TEXT DEFAULT '',+ prospect_id TEXT DEFAULT '',+ signal_code TEXT NOT NULL,+ collector TEXT DEFAULT '',+ value_num REAL,+ value_text TEXT DEFAULT '',+ confidence REAL DEFAULT 1.0,+ evidence_url TEXT DEFAULT '',+ observed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ run_id TEXT DEFAULT ''+ );++ CREATE INDEX IF NOT EXISTS idx_obs_company ON observations(company_id);+ CREATE INDEX IF NOT EXISTS idx_obs_signal ON observations(signal_code);+ CREATE INDEX IF NOT EXISTS idx_obs_company_signal+ ON observations(company_id, signal_code, observed_at);+ CREATE INDEX IF NOT EXISTS idx_obs_run ON observations(run_id);++ -- The governed-vocabulary guarantee. A trigger (not a foreign key) so it+ -- holds regardless of the per-connection foreign_keys pragma, and applies+ -- only here: the legacy tables default several id columns to '' and would+ -- break under blanket FK enforcement.+ CREATE TRIGGER IF NOT EXISTS trg_observations_signal_known+ BEFORE INSERT ON observations+ FOR EACH ROW+ WHEN NEW.signal_code NOT IN (SELECT code FROM signal_codes)+ BEGIN+ SELECT RAISE(ABORT, 'unknown signal_code: not in signal_codes vocabulary');+ END;++ -- A log of what ran, when, how much it produced and cost. Purely a+ -- record: spend is capped inside the collector, never here.+ CREATE TABLE IF NOT EXISTS runs (+ id TEXT PRIMARY KEY,+ stage TEXT DEFAULT '',+ status TEXT DEFAULT 'running',+ provider TEXT DEFAULT '',+ records INTEGER DEFAULT 0,+ cost_usd REAL DEFAULT 0.0,+ params_json TEXT DEFAULT '{}',+ error TEXT DEFAULT '',+ started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ ended_at TIMESTAMP+ );++ CREATE INDEX IF NOT EXISTS idx_runs_stage_started ON runs(stage, started_at);+ """,]# Column whitelists for dynamic UPDATEs (prevents SQL injection via kwargs).@@ -787,6 +859,273 @@ class StateManager:row = await cursor.fetchone()return dict(row) if row else None+ # ── Signal vocabulary (governed; user-confirmed before collection) ──++ async def upsert_signal_code(+ self,+ code: str,+ *,+ label: str = "",+ description: str = "",+ category: str = "",+ value_type: str = "text",+ collector: str = "",+ cost_note: str = "",+ confidence_floor: float = 0.0,+ status: str | None = None,+ ):+ """Register a signal in the vocabulary. Never downgrades a user's+ decision: an existing row's ``status`` is preserved unless explicitly+ passed, so re-seeding can't silently re-enable a rejected signal."""+ async with self._connect() as db:+ await db.execute(+ """INSERT INTO signal_codes+ (code, label, description, category, value_type,+ collector, cost_note, confidence_floor, status)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, 'proposed'))+ ON CONFLICT(code) DO UPDATE SET+ label = excluded.label,+ description = excluded.description,+ category = excluded.category,+ value_type = excluded.value_type,+ collector = excluded.collector,+ cost_note = excluded.cost_note,+ confidence_floor = excluded.confidence_floor,+ status = COALESCE(?, signal_codes.status),+ updated_at = CURRENT_TIMESTAMP""",+ (code, label, description, category, value_type, collector,+ cost_note, float(confidence_floor), status, status),+ )+ await db.commit()++ async def get_signal_codes(self, status: str | None = None) -> list[dict]:+ sql = "SELECT * FROM signal_codes"+ params: list = []+ if status:+ sql += " WHERE status = ?"+ params.append(status)+ sql += " ORDER BY category, code"+ async with self._connect() as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(sql, params) as cursor:+ return [dict(r) for r in await cursor.fetchall()]++ async def set_signal_status(self, code: str, status: str) -> bool:+ """Confirm / reject a proposed signal. Only confirmed signals are+ collected — Harvey proposes, the user decides."""+ if status not in ("proposed", "confirmed", "rejected"):+ raise ValueError(f"invalid signal status: {status}")+ async with self._connect() as db:+ cursor = await db.execute(+ "UPDATE signal_codes SET status = ?, updated_at = CURRENT_TIMESTAMP "+ "WHERE code = ?",+ (status, code),+ )+ await db.commit()+ return cursor.rowcount > 0++ async def confirmed_signal_codes(self) -> set[str]:+ return {r["code"] for r in await self.get_signal_codes(status="confirmed")}++ # ── Observations (every fact is a row, never a column) ──++ async def add_observation(+ self,+ signal_code: str,+ *,+ company_id: str = "",+ prospect_id: str = "",+ collector: str = "",+ value_num: float | None = None,+ value_text: str = "",+ confidence: float = 1.0,+ evidence_url: str = "",+ run_id: str = "",+ observed_at: str | None = None,+ ) -> str:+ """Record one fact. Raises if signal_code isn't in the vocabulary —+ a typo must fail loudly rather than create a junk signal."""+ obs_id = _new_id()+ async with self._connect() as db:+ await db.execute(+ """INSERT INTO observations+ (id, company_id, prospect_id, signal_code, collector,+ value_num, value_text, confidence, evidence_url,+ observed_at, run_id)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,+ COALESCE(?, CURRENT_TIMESTAMP), ?)""",+ (obs_id, company_id, prospect_id, signal_code, collector,+ value_num, value_text, float(confidence), evidence_url,+ observed_at, run_id),+ )+ await db.commit()+ return obs_id++ async def add_observations(self, rows: list[dict], run_id: str = "") -> int:+ """Batch insert. Flushed per batch by callers — a long run that dies+ must not lose everything it observed."""+ if not rows:+ return 0+ payload = [+ (+ _new_id(), r.get("company_id", ""), r.get("prospect_id", ""),+ r["signal_code"], r.get("collector", ""), r.get("value_num"),+ r.get("value_text", ""), float(r.get("confidence", 1.0)),+ r.get("evidence_url", ""), r.get("observed_at"),+ r.get("run_id", run_id),+ )+ for r in rows+ ]+ async with self._connect() as db:+ await db.executemany(+ """INSERT INTO observations+ (id, company_id, prospect_id, signal_code, collector,+ value_num, value_text, confidence, evidence_url,+ observed_at, run_id)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,+ COALESCE(?, CURRENT_TIMESTAMP), ?)""",+ payload,+ )+ await db.commit()+ return len(payload)++ async def get_observations(+ self,+ company_id: str = "",+ signal_code: str = "",+ latest_only: bool = False,+ limit: int = 500,+ ) -> list[dict]:+ where, params = [], []+ if company_id:+ where.append("company_id = ?")+ params.append(company_id)+ if signal_code:+ where.append("signal_code = ?")+ params.append(signal_code)+ sql = "SELECT * FROM observations"+ if where:+ sql += " WHERE " + " AND ".join(where)+ if latest_only:+ # Newest observation per (company, signal) — the current view of+ # the world, with history still on disk underneath.+ sql = (+ "SELECT * FROM (" + sql + " ORDER BY observed_at DESC) "+ "GROUP BY company_id, signal_code"+ )+ else:+ sql += " ORDER BY observed_at DESC"+ sql += " LIMIT ?"+ params.append(int(limit))+ async with self._connect() as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(sql, params) as cursor:+ return [dict(r) for r in await cursor.fetchall()]++ async def signal_counts(self) -> list[dict]:+ """How many entities carry each signal — the cohort sizes."""+ async with self._connect() as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(+ """SELECT o.signal_code,+ COALESCE(sc.label, o.signal_code) AS label,+ sc.status AS status,+ COUNT(DISTINCT o.company_id) AS companies,+ COUNT(*) AS observations+ FROM observations o+ LEFT JOIN signal_codes sc ON sc.code = o.signal_code+ GROUP BY o.signal_code+ ORDER BY companies DESC"""+ ) as cursor:+ return [dict(r) for r in await cursor.fetchall()]++ async def cohort(+ self,+ require: list[str],+ exclude: list[str] | None = None,+ min_confidence: float = 0.0,+ limit: int = 500,+ ) -> list[str]:+ """Company IDs carrying ALL required signals and none excluded.++ Set intersection happens in SQL — doing it in application code over a+ capped SELECT silently returns the wrong cohort.+ """+ if not require:+ return []+ req_ph = ",".join("?" for _ in require)+ sql = (+ "SELECT company_id FROM observations "+ f"WHERE signal_code IN ({req_ph}) AND company_id != '' "+ "AND confidence >= ? "+ "GROUP BY company_id HAVING COUNT(DISTINCT signal_code) = ?"+ )+ params: list = [*require, float(min_confidence), len(set(require))]+ if exclude:+ exc_ph = ",".join("?" for _ in exclude)+ sql += (+ " AND company_id NOT IN ("+ f"SELECT company_id FROM observations WHERE signal_code IN ({exc_ph})"+ ")"+ )+ params.extend(exclude)+ sql += " LIMIT ?"+ params.append(int(limit))+ async with self._connect() as db:+ async with db.execute(sql, params) as cursor:+ return [row[0] for row in await cursor.fetchall()]++ # ── Run log (what ran, when, what it produced and cost) ──++ async def start_run(+ self, stage: str, provider: str = "", params: dict | None = None+ ) -> str:+ run_id = _new_id()+ async with self._connect() as db:+ await db.execute(+ "INSERT INTO runs (id, stage, provider, params_json, status) "+ "VALUES (?, ?, ?, ?, 'running')",+ (run_id, stage, provider, json.dumps(params or {})),+ )+ await db.commit()+ return run_id++ async def finish_run(+ self,+ run_id: str,+ status: str = "completed",+ records: int = 0,+ cost_usd: float = 0.0,+ error: str = "",+ ):+ async with self._connect() as db:+ await db.execute(+ "UPDATE runs SET status = ?, records = ?, cost_usd = ?, "+ "error = ?, ended_at = CURRENT_TIMESTAMP WHERE id = ?",+ (status, int(records), float(cost_usd), error[:500], run_id),+ )+ await db.commit()++ async def sweep_stale_runs(self, older_than_hours: int = 6) -> int:+ """A killed collector can't close its own run — never trust it to."""+ async with self._connect() as db:+ cursor = await db.execute(+ "UPDATE runs SET status = 'stale', ended_at = CURRENT_TIMESTAMP "+ "WHERE status = 'running' "+ "AND started_at < datetime('now', ?)",+ (f"-{int(older_than_hours)} hours",),+ )+ await db.commit()+ return cursor.rowcount++ async def get_runs(self, limit: int = 25) -> list[dict]:+ async with self._connect() as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(+ "SELECT * FROM runs ORDER BY started_at DESC LIMIT ?", (int(limit),)+ ) as cursor:+ return [dict(r) for r in await cursor.fetchall()]+# ── Settings (operational flags: kill switch, counters) ──async def get_setting(self, key: str, default: str = "") -> str: