diff --git a/README.md b/README.md index 770a260..008d216 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,17 @@ small and honest: | "Drop your site → learn who buys it", fit scoring, reply triage | AutoGTM tools (`explee.com` & co) | `icp build` + `leads score`, reply classification, `stats --by template` — local and editable | | Answer-engine visibility, keyword-cluster → article generation | `babylovegrowth.ai` | `geo check` asks the engines directly; `content plan`/`draft` write the articles — no fake backlink network, no dashboard | +## Company prospecting pipeline + +`discover` imports free OSM or CSV company lists; `signals confirm free` then +`signals profile` records only explicitly approved, evidenced website observations. +`people find` looks only at public pages on the company's own domain, while +`cohort` and `export --csv` build explainable, send-free lists. Scheduled mail +stays in `outbox` until it passes the deterministic compliance gate and is +approved; `tick` sends approved messages only unless `--auto-approve` is supplied. +Paid discovery sources, LinkedIn, a web dashboard, autonomous heartbeats and +Gmail/Microsoft transports are intentionally left as possible future work. + ## Responsible use coldforge is a precision tool, not a spam cannon: low daily caps, send windows, diff --git a/coldforge/cli.py b/coldforge/cli.py index abc5642..184d8b7 100644 --- a/coldforge/cli.py +++ b/coldforge/cli.py @@ -63,6 +63,9 @@ no_args_is_help=True) content_app = typer.Typer(help="SEO/GEO content: cluster the ICP's keyword gaps into " "article briefs, then draft them.", no_args_is_help=True) +signals_app = typer.Typer(help="Confirm and collect free website signals.", no_args_is_help=True) +people_app = typer.Typer(help="Find public company decision makers.", no_args_is_help=True) +outbox_app = typer.Typer(help="Review and approve scheduled messages.", no_args_is_help=True) app.add_typer(templates_app, name="templates") app.add_typer(leads_app, name="leads") app.add_typer(campaign_app, name="campaign") @@ -72,6 +75,9 @@ app.add_typer(stage_app, name="stage") app.add_typer(geo_app, name="geo") app.add_typer(content_app, name="content") +app.add_typer(signals_app, name="signals") +app.add_typer(people_app, name="people") +app.add_typer(outbox_app, name="outbox") def _make_console() -> Console: @@ -626,6 +632,7 @@ def campaign_list() -> None: def tick( dry_run: bool = typer.Option(False, "--dry-run", help="Show what would send; send nothing."), scan: bool = typer.Option(False, "--scan-replies", help="Poll IMAP for replies first."), + auto_approve: bool = typer.Option(False, "--auto-approve", help="Bypass manual approval."), ) -> None: """Send all due messages, honouring guardrails and the reply→cancel rule.""" from .sender import make_sender, scan_replies @@ -638,7 +645,10 @@ def tick( console.print(f"[dim]reply scan: {n} new[/]") sender = make_sender(settings, dry_run=dry_run) is_dry = dry_run or not settings.can_send - result = run_tick(store, settings, sender, dry_run=is_dry) + result = run_tick( + store, settings, sender, dry_run=is_dry, auto_approve=auto_approve, + enforce_gate=True, + ) # Resolve recipients before the store closes. preview = [(store.get_lead(m.lead_id), m) for m in result.sent[:20]] @@ -658,6 +668,8 @@ def tick( console.print( f"[dim]Held {result.held_limit} for the daily limit ({settings.daily_limit}).[/]" ) + if result.held_gate: + console.print(f"[dim]Held {result.held_gate} by the approval gate.[/]") # ── replies ────────────────────────────────────────────────────────────────── @@ -1056,5 +1068,233 @@ def stats( ) +# ── company prospecting pipeline ─────────────────────────────────────────── +@app.command("discover") +def discover_cmd( + source: str = typer.Option("osm", "--source"), + category: str = typer.Option("", "--category"), + city: str = typer.Option("", "--city"), + estimate_only: bool = typer.Option(False, "--estimate"), + csv_path: Path | None = typer.Option(None, "--csv"), +) -> None: + """Discover companies, showing the source cost before doing any work.""" + import requests + + from .discover import discover_csv, discover_osm, estimate + + quote = estimate(source) + console.print(f"Estimated cost: [bold]{quote['label']}[/] ({source})") + if estimate_only: + return + if source == "osm": + if not category or not city: + _err("--category and --city are required for OSM discovery.") + + def fetch_json(url: str): + response = requests.get( + url, headers={"User-Agent": "coldforge/0.1 (company discovery)"}, timeout=30 + ) + response.raise_for_status() + return response.json() + + companies = discover_osm(category, city, fetch_json=fetch_json) + elif source == "csv" and csv_path: + companies = discover_csv(csv_path) + else: + _err("Use --source osm, or --source csv --csv PATH.") + with _store() as store: + for company in companies: + store.upsert_company(company) + console.print(f"[green]✓[/] Stored {len(companies)} companies.") + + +@signals_app.command("list") +def signals_list_cmd() -> None: + from .signals import CATALOG, confirmed_signals + + confirmed = confirmed_signals(get_settings().home) + table = Table("key", "label", "cost", "confirmed") + for key, definition in CATALOG.items(): + table.add_row(key, str(definition["label"]), str(definition["cost"]), + "yes" if key in confirmed else "no") + console.print(table) + + +@signals_app.command("confirm") +def signals_confirm_cmd(keys: list[str] = typer.Argument(...)) -> None: + from .signals import confirm + + try: + selected = confirm(keys, get_settings().home) + except ValueError as exc: + _err(str(exc)) + console.print(f"[green]✓[/] Confirmed {len(selected)} signals.") + + +@signals_app.command("profile") +def signals_profile_cmd(limit: int = typer.Option(0, "--limit", min=0)) -> None: + import requests + + from .signals import confirmed_signals, profile_company + + settings = get_settings() + confirmed = confirmed_signals(settings.home) + if not confirmed: + _err("No signals confirmed; run `coldforge signals confirm free` first.") + + def fetch(url: str) -> str | None: + try: + response = requests.get( + url, headers={"User-Agent": "coldforgebot/0.1 (+website profiling)"}, timeout=10 + ) + return response.text if response.ok else None + except requests.RequestException: + return None + + observations = 0 + with _store() as store: + companies = store.list_companies()[:limit or None] + for company in companies: + found = profile_company(company, fetch=fetch, confirmed=confirmed) + for key, value, evidence in found: + store.add_company_signal(company.id, key, value, evidence) # type: ignore[arg-type] + observations += len(found) + if not found: + console.print(f"[dim]{company.name}: no confirmed signal observed[/]") + console.print(f"[green]✓[/] Stored {observations} observations.") + + +@people_app.command("find") +def people_find_cmd(company: str = typer.Option("", "--company")) -> None: + import requests + + from .people import candidates, find_people, guess_email_pattern + from .verify import verify_email + + def fetch(url: str) -> str | None: + try: + response = requests.get( + url, headers={"User-Agent": "coldforgebot/0.1 (+public people search)"}, timeout=10 + ) + return response.text if response.ok else None + except requests.RequestException: + return None + + added = 0 + with _store() as store: + companies = store.list_companies() + if company: + companies = [c for c in companies if company.casefold() in c.name.casefold()] + for business in companies: + people = find_people(business, fetch=fetch) + if not people: + console.print( + f"[dim]{business.name}: no public team page or decision maker found[/]" + ) + continue + known = [ + lead.email for lead in store.list_leads() + if lead.email.endswith(f"@{business.domain}") + ] + pattern = guess_email_pattern(known, business.domain) + for person in people: + emails = candidates(person, pattern, business.domain) + if not emails: + console.print(f"[dim]{person.name}: found, but no honest email candidate[/]") + continue + verified = verify_email(emails[0]) + if verified.status != "ok": + console.print(f"[yellow]{emails[0]}: {verified.status}; not sendable[/]") + continue + lead = Lead( + email=verified.email, first_name=person.first_name, + last_name=person.last_name, company=business.name, title=person.title, + website=business.website, company_id=business.id, + custom={"source_url": person.source_url}, verify_status="ok", + ) + saved = store.upsert_lead(lead) + store.set_verify_status(saved.id, "ok") # type: ignore[arg-type] + added += 1 + console.print(f"[green]✓[/] Added {added} verified decision makers.") + + +@app.command("cohort") +def cohort_cmd( + must: list[str] = typer.Option([], "--must"), + none_of: list[str] = typer.Option([], "--none-of"), +) -> None: + from .cohort import cohort, inclusion_reasons + + with _store() as store: + selected = cohort(store, must=must, none_of=none_of) + console.print(f"[bold]{len(selected)}[/] companies") + for company in selected: + why = "; ".join(inclusion_reasons(store, company, must=must)) + console.print(f" {company.name} — {why}") + + +@app.command("export") +def export_cmd( + csv_path: Path = typer.Option(..., "--csv"), + cohort_only: bool = typer.Option(True, "--cohort/--all-companies"), + must: list[str] = typer.Option([], "--must"), + none_of: list[str] = typer.Option([], "--none-of"), +) -> None: + from .cohort import cohort, export_csv + + with _store() as store: + companies = ( + cohort(store, must=must, none_of=none_of) + if cohort_only else store.list_companies() + ) + total = export_csv(companies, csv_path) + console.print(f"[green]✓[/] Exported {total} companies to {csv_path}; nothing was sent.") + + +@outbox_app.command("list") +def outbox_list_cmd() -> None: + with _store() as store: + messages = store.list_outbox() + table = Table("id", "recipient", "subject", "approved") + for message in messages: + lead = store.get_lead(message.lead_id) + table.add_row(str(message.id), lead.email if lead else "?", message.subject, + "yes" if message.approved else "no") + console.print(table) + + +@outbox_app.command("approve") +def outbox_approve_cmd( + ids: list[int] | None = typer.Argument(None), + all_passing: bool = typer.Option(False, "--all-passing"), +) -> None: + from .gate import check_message + + settings = get_settings() + approved = 0 + with _store() as store: + messages = ( + store.list_outbox() + if all_passing else [store.get_message(i) for i in (ids or [])] + ) + for message in messages: + if message is None: + continue + result = check_message(store, settings, message, datetime.now().astimezone()) + if not result.ok: + console.print(f"[red]Message {message.id} refused:[/] {'; '.join(result.reasons)}") + continue + store.set_message_approval(message.id, True) # type: ignore[arg-type] + approved += 1 + console.print(f"[green]✓[/] Approved {approved} messages.") + + +@outbox_app.command("reject") +def outbox_reject_cmd(message_id: int = typer.Argument(...)) -> None: + with _store() as store: + store.reject_message(message_id) + console.print(f"[green]✓[/] Rejected message {message_id}.") + + if __name__ == "__main__": app() diff --git a/coldforge/cohort.py b/coldforge/cohort.py new file mode 100644 index 0000000..140744b --- /dev/null +++ b/coldforge/cohort.py @@ -0,0 +1,84 @@ +"""Select and export explainable company cohorts from stored signals.""" + +from __future__ import annotations + +import csv +from pathlib import Path + +from .companies import Company +from .db import Store + + +def cohort( + store: Store, + must: list[str] | None = None, + none_of: list[str] | None = None, + ranges: dict[str, tuple[float | None, float | None]] | None = None, +) -> list[Company]: + required = set(must or []) + forbidden = set(none_of or []) + bounded = ranges or {} + selected: list[Company] = [] + for company in store.list_companies(): + if company.id is None: + continue + signals = store.signals_of(company.id) + if not required.issubset(signals): + continue + if forbidden.intersection(signals): + continue + if not _within_ranges(signals, bounded): + continue + selected.append(company) + return selected + + +def count(store: Store, **criteria) -> int: + return len(cohort(store, **criteria)) + + +def inclusion_reasons( + store: Store, + company: Company, + must: list[str] | None = None, + ranges: dict[str, tuple[float | None, float | None]] | None = None, +) -> list[str]: + signals = store.signals_of(company.id) if company.id is not None else {} + reasons = [f"{key}={signals[key][0]}" for key in must or [] if key in signals] + reasons.extend( + f"{key}={signals[key][0]} in [{lo if lo is not None else '-∞'}, " + f"{hi if hi is not None else '∞'}]" + for key, (lo, hi) in (ranges or {}).items() if key in signals + ) + return reasons or ["matches cohort criteria"] + + +def export_csv(companies: list[Company], path: str | Path) -> int: + """Write a list-only sequencer input. This function never sends anything.""" + with Path(path).open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, + fieldnames=("name", "domain", "website", "city", "category", "phone", "source"), + ) + writer.writeheader() + for company in companies: + writer.writerow({key: getattr(company, key) for key in writer.fieldnames}) + return len(companies) + + +def _within_ranges( + signals: dict[str, tuple[str, str]], + ranges: dict[str, tuple[float | None, float | None]], +) -> bool: + for key, (lo, hi) in ranges.items(): + if key not in signals: + return False + try: + value = float(signals[key][0]) + except ValueError: + return False + if lo is not None and value < lo: + return False + if hi is not None and value > hi: + return False + return True diff --git a/coldforge/companies.py b/coldforge/companies.py new file mode 100644 index 0000000..03baa55 --- /dev/null +++ b/coldforge/companies.py @@ -0,0 +1,39 @@ +"""Company records shared by discovery, profiling and cohort selection.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timezone +from urllib.parse import urlparse + + +def _utcnow() -> datetime: + return datetime.now(timezone.utc) + + +def normalize_domain(website: str) -> str: + """Return a stable lower-case host, without a leading ``www``.""" + value = website.strip() + if not value: + return "" + parsed = urlparse(value if "://" in value else f"https://{value}") + host = (parsed.hostname or "").lower().rstrip(".") + return host.removeprefix("www.") + + +@dataclass +class Company: + name: str + domain: str = "" + website: str = "" + city: str = "" + category: str = "" + phone: str = "" + source: str = "" + created_at: datetime = field(default_factory=_utcnow) + id: int | None = None + + def __post_init__(self) -> None: + self.name = self.name.strip() + self.website = self.website.strip() + self.domain = normalize_domain(self.domain or self.website) diff --git a/coldforge/config.py b/coldforge/config.py index 77a83fd..76fad45 100644 --- a/coldforge/config.py +++ b/coldforge/config.py @@ -102,6 +102,8 @@ class Settings: perplexity_model: str = "sonar" gemini_api_key: str | None = None gemini_model: str = "gemini-2.0-flash" + postal_address: str = "" + gate_window: tuple[time, time] = (time(8, 0), time(19, 0)) @property def can_send(self) -> bool: @@ -164,4 +166,6 @@ def get_settings() -> Settings: perplexity_model=os.environ.get("COLDFORGE_PERPLEXITY_MODEL", "sonar"), gemini_api_key=os.environ.get("GEMINI_API_KEY") or None, gemini_model=os.environ.get("COLDFORGE_GEMINI_MODEL", "gemini-2.0-flash"), + postal_address=os.environ.get("COLDFORGE_POSTAL_ADDRESS", "").strip(), + gate_window=_parse_window(os.environ.get("COLDFORGE_GATE_WINDOW", "08:00-19:00")), ) diff --git a/coldforge/db.py b/coldforge/db.py index 6807468..adcd3a6 100644 --- a/coldforge/db.py +++ b/coldforge/db.py @@ -11,6 +11,7 @@ from datetime import datetime, timezone from pathlib import Path +from .companies import Company from .models import Campaign, Lead, Message, Signal, Stage SCHEMA = """ @@ -27,9 +28,37 @@ fit_score INTEGER, fit_reason TEXT DEFAULT '', verify_status TEXT DEFAULT '', + company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL, created_at TEXT NOT NULL ); +CREATE TABLE IF NOT EXISTS companies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + domain TEXT, + website TEXT DEFAULT '', + city TEXT DEFAULT '', + category TEXT DEFAULT '', + phone TEXT DEFAULT '', + source TEXT DEFAULT '', + created_at TEXT NOT NULL +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_companies_domain + ON companies(domain) WHERE domain IS NOT NULL AND domain != ''; +CREATE UNIQUE INDEX IF NOT EXISTS idx_companies_name_city_no_domain + ON companies(lower(name), lower(city)) WHERE domain IS NULL OR domain = ''; + +CREATE TABLE IF NOT EXISTS company_signals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + company_id INTEGER NOT NULL REFERENCES companies(id) ON DELETE CASCADE, + key TEXT NOT NULL, + value TEXT DEFAULT '', + evidence_url TEXT DEFAULT '', + created_at TEXT NOT NULL, + UNIQUE(company_id, key) +); + CREATE TABLE IF NOT EXISTS signals ( id INTEGER PRIMARY KEY AUTOINCREMENT, lead_id INTEGER NOT NULL REFERENCES leads(id) ON DELETE CASCADE, @@ -61,6 +90,7 @@ sent_at TEXT, variant TEXT DEFAULT '', error TEXT DEFAULT '', + approved INTEGER DEFAULT 0, UNIQUE(campaign_id, lead_id, step) ); @@ -92,6 +122,7 @@ ON messages(status, scheduled_at); CREATE INDEX IF NOT EXISTS idx_signals_lead ON signals(lead_id); CREATE INDEX IF NOT EXISTS idx_stages_lead ON stages(lead_id); +CREATE INDEX IF NOT EXISTS idx_company_signals_company ON company_signals(company_id); """ @@ -125,12 +156,83 @@ def _migrate(self) -> None: ("fit_score", "fit_score INTEGER"), ("fit_reason", "fit_reason TEXT DEFAULT ''"), ("verify_status", "verify_status TEXT DEFAULT ''"), + ("company_id", "company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL"), ): if name not in lead_cols: self.conn.execute(f"ALTER TABLE leads ADD COLUMN {ddl}") reply_cols = {r[1] for r in self.conn.execute("PRAGMA table_info(replies)")} if "category" not in reply_cols: self.conn.execute("ALTER TABLE replies ADD COLUMN category TEXT DEFAULT ''") + message_cols = {r[1] for r in self.conn.execute("PRAGMA table_info(messages)")} + if "approved" not in message_cols: + self.conn.execute("ALTER TABLE messages ADD COLUMN approved INTEGER DEFAULT 0") + + # ── companies ───────────────────────────────────────────────────────── + def upsert_company(self, company: Company) -> Company: + company.domain = company.domain.strip().lower() + if company.domain: + row = self.conn.execute( + "SELECT id FROM companies WHERE domain=?", (company.domain,) + ).fetchone() + else: + row = self.conn.execute( + "SELECT id FROM companies WHERE lower(name)=lower(?) AND lower(city)=lower(?) " + "AND (domain IS NULL OR domain='')", + (company.name, company.city), + ).fetchone() + values = ( + company.name, company.domain or None, company.website, company.city, + company.category, company.phone, company.source, + ) + if row: + company.id = int(row[0]) + self.conn.execute( + "UPDATE companies SET name=?,domain=?,website=?,city=?,category=?,phone=?,source=? " + "WHERE id=?", (*values, company.id), + ) + else: + cur = self.conn.execute( + "INSERT INTO companies(name,domain,website,city,category,phone,source,created_at) " + "VALUES(?,?,?,?,?,?,?,?) RETURNING id", (*values, _now()), + ) + company.id = int(cur.fetchone()[0]) + self.conn.commit() + return company + + def list_companies(self) -> list[Company]: + rows = self.conn.execute("SELECT * FROM companies ORDER BY id").fetchall() + return [self._row_to_company(row) for row in rows] + + def get_company(self, company_id: int) -> Company | None: + row = self.conn.execute("SELECT * FROM companies WHERE id=?", (company_id,)).fetchone() + return self._row_to_company(row) if row else None + + @staticmethod + def _row_to_company(row: sqlite3.Row) -> Company: + return Company( + id=row["id"], name=row["name"], domain=row["domain"] or "", + website=row["website"] or "", city=row["city"] or "", + category=row["category"] or "", phone=row["phone"] or "", + source=row["source"] or "", created_at=_dt(row["created_at"]), + ) + + def add_company_signal( + self, company_id: int, key: str, value: str, evidence_url: str = "" + ) -> None: + self.conn.execute( + "INSERT INTO company_signals(company_id,key,value,evidence_url,created_at) " + "VALUES(?,?,?,?,?) ON CONFLICT(company_id,key) DO UPDATE SET " + "value=excluded.value,evidence_url=excluded.evidence_url,created_at=excluded.created_at", + (company_id, key, str(value), evidence_url, _now()), + ) + self.conn.commit() + + def signals_of(self, company_id: int) -> dict[str, tuple[str, str]]: + rows = self.conn.execute( + "SELECT key,value,evidence_url FROM company_signals WHERE company_id=? ORDER BY key", + (company_id,), + ).fetchall() + return {r["key"]: (r["value"], r["evidence_url"]) for r in rows} def close(self) -> None: self.conn.close() @@ -146,18 +248,18 @@ def upsert_lead(self, lead: Lead) -> Lead: lead.email = lead.email.strip().lower() cur = self.conn.execute( """INSERT INTO leads(email,first_name,last_name,company,title,website, - linkedin,custom,created_at) - VALUES(?,?,?,?,?,?,?,?,?) + linkedin,custom,company_id,created_at) + VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(email) DO UPDATE SET first_name=excluded.first_name, last_name=excluded.last_name, company=excluded.company, title=excluded.title, website=excluded.website, linkedin=excluded.linkedin, - custom=excluded.custom + custom=excluded.custom, company_id=COALESCE(excluded.company_id,leads.company_id) RETURNING id""", ( lead.email, lead.first_name, lead.last_name, lead.company, lead.title, lead.website, lead.linkedin, - json.dumps(lead.custom), _now(), + json.dumps(lead.custom), lead.company_id, _now(), ), ) lead.id = cur.fetchone()[0] @@ -206,6 +308,7 @@ def _row_to_lead(row: sqlite3.Row) -> Lead: custom=json.loads(row["custom"] or "{}"), fit_score=row["fit_score"], fit_reason=row["fit_reason"] or "", verify_status=row["verify_status"] or "", + company_id=row["company_id"], ) # ── signals ──────────────────────────────────────────────────────────── @@ -276,10 +379,10 @@ def schedule_message(self, m: Message) -> Message | None: try: cur = self.conn.execute( """INSERT INTO messages(campaign_id,lead_id,step,scheduled_at,template_id, - subject,body,status,variant) - VALUES(?,?,?,?,?,?,?,?,?) RETURNING id""", + subject,body,status,variant,approved) + VALUES(?,?,?,?,?,?,?,?,?,?) RETURNING id""", (m.campaign_id, m.lead_id, m.step, m.scheduled_at.isoformat(timespec="seconds"), - m.template_id, m.subject, m.body, m.status, m.variant), + m.template_id, m.subject, m.body, m.status, m.variant, int(m.approved)), ) m.id = cur.fetchone()[0] self.conn.commit() @@ -295,6 +398,30 @@ def due_messages(self, now: datetime) -> list[Message]: ).fetchall() return [self._row_to_message(r) for r in rows] + def get_message(self, message_id: int) -> Message | None: + row = self.conn.execute("SELECT * FROM messages WHERE id=?", (message_id,)).fetchone() + return self._row_to_message(row) if row else None + + def list_outbox(self) -> list[Message]: + rows = self.conn.execute( + "SELECT * FROM messages WHERE status='scheduled' ORDER BY scheduled_at,id" + ).fetchall() + return [self._row_to_message(row) for row in rows] + + def set_message_approval(self, message_id: int, approved: bool) -> None: + self.conn.execute( + "UPDATE messages SET approved=? WHERE id=? AND status='scheduled'", + (int(approved), message_id), + ) + self.conn.commit() + + def reject_message(self, message_id: int) -> None: + self.conn.execute( + "UPDATE messages SET approved=0,status='rejected' WHERE id=? AND status='scheduled'", + (message_id,), + ) + self.conn.commit() + def messages_for_campaign(self, campaign_id: int) -> list[Message]: rows = self.conn.execute( "SELECT * FROM messages WHERE campaign_id=? ORDER BY scheduled_at", (campaign_id,) @@ -334,6 +461,7 @@ def _row_to_message(row: sqlite3.Row) -> Message: template_id=row["template_id"], subject=row["subject"], body=row["body"], status=row["status"], sent_at=_dt(row["sent_at"]), variant=row["variant"], error=row["error"], + approved=bool(row["approved"]), ) # ── replies ──────────────────────────────────────────────────────────── diff --git a/coldforge/discover.py b/coldforge/discover.py new file mode 100644 index 0000000..f66b61a --- /dev/null +++ b/coldforge/discover.py @@ -0,0 +1,84 @@ +"""Free company discovery from OpenStreetMap or a local CSV.""" + +from __future__ import annotations + +import csv +import json +from pathlib import Path +from urllib.parse import quote, urlencode + +from .companies import Company, normalize_domain + +OVERPASS_URL = "https://overpass-api.de/api/interpreter" + + +def estimate(source: str = "osm", **_: object) -> dict[str, object]: + """Return the price estimate before discovery starts.""" + if source.lower() not in {"osm", "csv"}: + raise ValueError(f"unknown discovery source: {source}") + return {"source": source.lower(), "cost_eur": 0.0, "label": "0 €"} + + +def discover_osm(category: str, city: str, *, fetch_json) -> list[Company]: + """Discover named businesses with Overpass; network access is injected.""" + query = ( + "[out:json][timeout:25];" + f'area["name"="{_escape(city)}"]->.searchArea;' + "(" + f'nwr["craft"="{_escape(category)}"](area.searchArea);' + f'nwr["shop"="{_escape(category)}"](area.searchArea);' + f'nwr["office"="{_escape(category)}"](area.searchArea);' + f'nwr["amenity"="{_escape(category)}"](area.searchArea);' + ");out tags center;" + ) + url = f"{OVERPASS_URL}?{urlencode({'data': query}, quote_via=quote)}" + payload = fetch_json(url) + if isinstance(payload, str): + payload = json.loads(payload) + elements = payload.get("elements", []) if isinstance(payload, dict) else [] + found: list[Company] = [] + seen: set[str] = set() + for item in elements: + tags = item.get("tags", {}) if isinstance(item, dict) else {} + name = str(tags.get("name", "")).strip() + if not name: + continue + website = str(tags.get("website") or tags.get("contact:website") or "").strip() + domain = normalize_domain(website) + dedupe = domain or f"{name.casefold()}|{city.casefold()}" + if dedupe in seen: + continue + seen.add(dedupe) + found.append(Company( + name=name, domain=domain, website=website, city=city, category=category, + phone=str(tags.get("phone") or tags.get("contact:phone") or ""), source="osm", + )) + return found + + +def discover_csv(path: str | Path) -> list[Company]: + """Load companies from a UTF-8 CSV with the documented five columns.""" + companies: list[Company] = [] + seen: set[str] = set() + with Path(path).open(newline="", encoding="utf-8-sig") as handle: + for row in csv.DictReader(handle): + name = (row.get("name") or "").strip() + if not name: + continue + website = (row.get("website") or "").strip() + domain = normalize_domain(website) + city = (row.get("city") or "").strip() + dedupe = domain or f"{name.casefold()}|{city.casefold()}" + if dedupe in seen: + continue + seen.add(dedupe) + companies.append(Company( + name=name, domain=domain, website=website, city=city, + category=(row.get("category") or "").strip(), + phone=(row.get("phone") or "").strip(), source="csv", + )) + return companies + + +def _escape(value: str) -> str: + return value.replace("\\", "\\\\").replace('"', '\\"') diff --git a/coldforge/gate.py b/coldforge/gate.py new file mode 100644 index 0000000..2f80f33 --- /dev/null +++ b/coldforge/gate.py @@ -0,0 +1,54 @@ +"""Deterministic approval gate applied immediately before a message is approved.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +from .config import Settings +from .db import Store +from .lint import compliance_issues, lint_draft +from .models import Message + + +@dataclass +class GateResult: + ok: bool + reasons: list[str] = field(default_factory=list) + + +def check_message( + store: Store, settings: Settings, message: Message, now: datetime +) -> GateResult: + """Evaluate every guard independently so a reviewer sees all defects at once.""" + reasons: list[str] = [] + lead = store.get_lead(message.lead_id) + if lead is None: + return GateResult(False, ["recipient missing"]) + if store.is_suppressed(lead.email): + reasons.append("recipient address is suppressed") + if lead.verify_status != "ok": + reasons.append(f"verify_status is {lead.verify_status or 'unset'}, expected ok") + if store.sent_today(now.date().isoformat()) >= settings.daily_limit: + reasons.append("daily sending limit reached") + local_now = _recipient_time(now, lead.custom.get("timezone", "")) + start, end = getattr(settings, "gate_window", settings.send_window) + if not start <= local_now.time().replace(tzinfo=None) <= end: + reasons.append("outside recipient quiet-hours window") + reasons.extend(compliance_issues(message.body, getattr(settings, "postal_address", ""))) + report = lint_draft(message.subject, message.body) + if any(issue.severity == "block" for issue in report.issues): + reasons.append("message lint has a blocking issue") + if store.has_replied(message.lead_id, message.campaign_id): + reasons.append("recipient already replied") + return GateResult(not reasons, reasons) + + +def _recipient_time(now: datetime, timezone_name: str) -> datetime: + if not timezone_name or now.tzinfo is None: + return now + try: + return now.astimezone(ZoneInfo(timezone_name)) + except ZoneInfoNotFoundError: + return now diff --git a/coldforge/lint.py b/coldforge/lint.py index e4fcf19..000416e 100644 --- a/coldforge/lint.py +++ b/coldforge/lint.py @@ -92,3 +92,18 @@ def lint_draft(subject: str, body: str) -> LintReport: report._add("block", "unfilled {{variables}} left in the email") return report + + +def compliance_issues(body: str, postal_address: str = "") -> list[str]: + """Return the two deterministic footer defects used by the send gate.""" + lower = body.casefold() + opt_out = ( + "unsubscribe", "désinscrire", "desinscrire", "ne plus recevoir", + "dites-moi non", "dites moi non", "say no", "opt out", + ) + issues: list[str] = [] + if not any(term in lower for term in opt_out): + issues.append("missing unsubscribe line") + if not postal_address or postal_address.casefold() not in lower: + issues.append("missing postal address") + return issues diff --git a/coldforge/models.py b/coldforge/models.py index 287944b..9045d27 100644 --- a/coldforge/models.py +++ b/coldforge/models.py @@ -27,6 +27,7 @@ class Lead: fit_score: int | None = None # 0–100 against the stored ICP (see icp.py) fit_reason: str = "" verify_status: str = "" # "" | ok | risky | invalid (see verify.py) + company_id: int | None = None id: int | None = None def as_vars(self) -> dict[str, str]: @@ -94,6 +95,7 @@ class Message: sent_at: datetime | None = None variant: str = "" # A/B label error: str = "" + approved: bool = False id: int | None = None diff --git a/coldforge/people.py b/coldforge/people.py new file mode 100644 index 0000000..0cfd758 --- /dev/null +++ b/coldforge/people.py @@ -0,0 +1,146 @@ +"""Find public company decision makers without social-network scraping.""" + +from __future__ import annotations + +import re +import unicodedata +from dataclasses import dataclass +from html import unescape +from urllib.parse import urljoin + +from .companies import Company + +PUBLIC_PATHS = ("/equipe", "/a-propos", "/about", "/team", "/mentions-legales") +TITLE_WORDS = ( + "gérant", "gérante", "gerant", "gerante", "dirigeant", "dirigeante", + "fondateur", "fondatrice", + "directeur", "directrice", "président", "president", "owner", "founder", + "chief executive officer", "ceo", "managing director", +) +_NAME = r"([A-ZÀ-ÖØ-Ý][A-Za-zÀ-ÖØ-öø-ÿ'’-]+(?:\s+[A-ZÀ-ÖØ-Ý][A-Za-zÀ-ÖØ-öø-ÿ'’-]+){1,3})" + + +@dataclass +class Person: + first_name: str + last_name: str + title: str + source_url: str + email: str = "" + + @property + def name(self) -> str: + return f"{self.first_name} {self.last_name}".strip() + + +class EmailPattern(str): + """A string-compatible pattern that also carries its inferred domain.""" + + domain: str + + def __new__(cls, value: str, domain: str): + instance = super().__new__(cls, value) + instance.domain = domain + return instance + + +def find_people(company: Company, *, fetch) -> list[Person]: + """Return at most two named decision makers from the company's own pages.""" + base = company.website or (f"https://{company.domain}" if company.domain else "") + if not base: + return [] + people: list[Person] = [] + seen: set[str] = set() + for path in PUBLIC_PATHS: + url = urljoin(base.rstrip("/") + "/", path.lstrip("/")) + html = fetch(url) + if not html: + continue + for person in extract_people(html, url): + identity = person.name.casefold() + if identity in seen: + continue + seen.add(identity) + people.append(person) + if len(people) == 2: + return people + return people + + +def extract_people(html: str, source_url: str) -> list[Person]: + # Keep an explicit boundary between HTML elements so one person's title + # cannot be greedily joined to the next person's name. + text = re.sub(r"<[^>]+>", " | ", unescape(html)) + text = re.sub(r"\s+", " ", text).strip() + title_re = "|".join(re.escape(word) for word in sorted(TITLE_WORDS, key=len, reverse=True)) + patterns = ( + rf"{_NAME}\s*[,–—|:-]+\s*({title_re})\b", + rf"\b({title_re})\s*[:–—|-]+\s*{_NAME}", + rf"\b({title_re})\s+(?:de\s+(?:la\s+)?société\s+)?{_NAME}", + ) + found: list[Person] = [] + for index, pattern in enumerate(patterns): + for match in re.finditer(pattern, text, re.IGNORECASE): + if index == 0: + full_name, title = match.group(1), match.group(2) + else: + title, full_name = match.group(1), match.group(2) + parts = full_name.strip().split() + if len(parts) < 2: + continue + nearby = text[max(0, match.start() - 100):match.end() + 100] + email_match = re.search(r"[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}", nearby) + found.append(Person( + first_name=parts[0], last_name=" ".join(parts[1:]), title=title, + source_url=source_url, email=email_match.group(0).lower() if email_match else "", + )) + unique: dict[str, Person] = {} + for person in found: + unique.setdefault(person.name.casefold(), person) + return list(unique.values())[:2] + + +def guess_email_pattern(known_emails: list[str], domain: str) -> EmailPattern | None: + """Infer a conservative pattern when local parts expose two name tokens.""" + domain = domain.strip().casefold().removeprefix("www.") + locals_ = [ + local.casefold() for email in known_emails + for local, separator, email_domain in [email.partition("@")] + if separator and email_domain.casefold() == domain + ] + if not locals_: + return None + patterns = { + "first.last": re.compile(r"^[a-z][a-z'-]+\.[a-z][a-z'-]+$"), + "first_last": re.compile(r"^[a-z][a-z'-]+_[a-z][a-z'-]+$"), + "first-last": re.compile(r"^[a-z][a-z'-]+-[a-z][a-z'-]+$"), + "flast": re.compile(r"^[a-z][a-z'-]{2,}$"), + } + for name, regex in patterns.items(): + if all(regex.fullmatch(local) for local in locals_): + return EmailPattern(name, domain) + return None + + +def candidates(person: Person, pattern: str | None, domain: str = "") -> list[str]: + """Build one candidate for a known pattern; never claim it is verified.""" + if person.email: + return [person.email] + domain = (domain or getattr(pattern, "domain", "")).strip().lower().removeprefix("www.") + if not pattern or not domain: + return [] + first = _slug(person.first_name) + last = _slug(person.last_name).replace("-", "") + local = { + "first.last": f"{first}.{last}", + "first_last": f"{first}_{last}", + "first-last": f"{first}-{last}", + "flast": f"{first[:1]}{last}", + "first": first, + }.get(pattern) + return [f"{local}@{domain}"] if local else [] + + +def _slug(value: str) -> str: + plain = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode() + return re.sub(r"[^a-z0-9-]", "", plain.casefold().replace("’", "-")) diff --git a/coldforge/sequence.py b/coldforge/sequence.py index d7bbca5..4dd1593 100644 --- a/coldforge/sequence.py +++ b/coldforge/sequence.py @@ -109,7 +109,7 @@ def schedule_campaign( if lead.id is None: continue # Never enroll someone who opted out or whose address can't receive mail. - if store.is_suppressed(lead.email) or lead.verify_status == "invalid": + if store.is_suppressed(lead.email) or lead.verify_status in {"risky", "invalid"}: continue signal = next(iter(store.signals_for(lead.id)), None) cumulative = 0 @@ -146,6 +146,7 @@ def __init__(self) -> None: self.canceled: int = 0 self.held_limit: int = 0 self.held_window: bool = False + self.held_gate: int = 0 def as_dict(self) -> dict: return { @@ -155,11 +156,13 @@ def as_dict(self) -> dict: "canceled": self.canceled, "held_for_daily_limit": self.held_limit, "outside_send_window": self.held_window, + "held_by_approval_gate": self.held_gate, } def tick(store: Store, settings: Settings, sender, *, now: datetime | None = None, - dry_run: bool = False) -> TickResult: + dry_run: bool = False, auto_approve: bool = True, + enforce_gate: bool = False) -> TickResult: """Process all due messages, honouring guardrails and the reply→cancel rule. *sender* is any object with ``send(to, subject, body) -> None`` (see @@ -178,6 +181,22 @@ def tick(store: Store, settings: Settings, sender, *, now: datetime | None = Non return result for msg in store.due_messages(now): + if enforce_gate: + if not msg.approved and not auto_approve: + result.held_gate += 1 + continue + from .gate import check_message + + gate_result = check_message(store, settings, msg, now) + if not gate_result.ok: + result.held_gate += 1 + continue + if auto_approve and not msg.approved: + store.set_message_approval(msg.id, True) # type: ignore[arg-type] + msg.approved = True + elif not auto_approve and not msg.approved: + result.held_gate += 1 + continue # reply → cancel: drop conditional follow-ups once the lead replied. step_condition = _condition_for(store, msg) if step_condition == "no_reply" and store.has_replied(msg.lead_id, msg.campaign_id): @@ -197,7 +216,7 @@ def tick(store: Store, settings: Settings, sender, *, now: datetime | None = Non # Suppression list and invalid addresses win over everything else — # cancel the lead's whole remaining sequence, not just this step. - if store.is_suppressed(lead.email) or lead.verify_status == "invalid": + if store.is_suppressed(lead.email) or lead.verify_status in {"risky", "invalid"}: store.mark_message(msg.id, "skipped") # type: ignore[arg-type] result.skipped_suppressed.append(msg) result.canceled += store.cancel_pending_for_lead(msg.campaign_id, msg.lead_id) diff --git a/coldforge/signals.py b/coldforge/signals.py new file mode 100644 index 0000000..8ea163a --- /dev/null +++ b/coldforge/signals.py @@ -0,0 +1,223 @@ +"""Deterministic, opt-in website signals with a strict three-request budget.""" + +from __future__ import annotations + +import re +from datetime import date, datetime, timezone +from html import unescape +from pathlib import Path +from urllib.parse import urljoin + +import yaml + +from .companies import Company + +BOOKING_WORDS = ( + "calendly", "doctolib", "planity", "prendre rendez-vous", "prendre-rendez-vous", + "réserver", "reservation", "booking", "book now", "appointment", +) +CAREER_WORDS = ("carrière", "carrieres", "carrières", "recrutement", "jobs", "careers", "hiring") +CONTACT_WORDS = ("contact", "contactez-nous", "get in touch", "nous contacter") + + +def _present(needles: tuple[str, ...], html: str) -> bool: + lower = unescape(html).casefold() + return any(word.casefold() in lower for word in needles) + + +def detect_no_website(html: str | None, site: str) -> tuple[str, str] | None: + return ("true", site or "no website supplied") if not site or html is None else None + + +def detect_no_booking(html: str, site: str) -> tuple[str, str] | None: + return None if _present(BOOKING_WORDS, html) else ("true", site) + + +def detect_no_schema(html: str, site: str) -> tuple[str, str] | None: + pattern = r' +
+Book an appointment + +