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']+type=["\']application/ld\+json["\']' + has_json_ld = bool(re.search(pattern, html, re.IGNORECASE)) + return None if has_json_ld else ("true", site) + + +def detect_blog_stale(html: str, site: str) -> tuple[str, str] | None: + """Report an absent blog date, or the newest visible ISO date older than 12 months.""" + dates: list[date] = [] + pattern = r"\b(20\d{2})[-/](0?[1-9]|1[0-2])[-/](0?[1-9]|[12]\d|3[01])\b" + for year, month, day in re.findall(pattern, html): + try: + dates.append(date(int(year), int(month), int(day))) + except ValueError: + pass + if not dates: + return "absent", site + newest = max(dates) + today = datetime.now(timezone.utc).date() + months = (today.year - newest.year) * 12 + today.month - newest.month + return (newest.isoformat(), site) if months > 12 else None + + +def detect_tech_stack(html: str, site: str) -> tuple[str, str] | None: + signatures = { + "WordPress": ("wp-content", "wp-includes", "wordpress"), + "Wix": ("wixstatic.com", "wix.com"), + "Shopify": ("cdn.shopify.com", "shopify-section"), + "Webflow": ("webflow.css", "data-wf-page", "webflow.io"), + } + found = [name for name, marks in signatures.items() if _present(marks, html)] + return (", ".join(found), site) if found else None + + +def detect_blocks_ai(html: str, site: str) -> tuple[str, str] | None: + blocked: list[str] = [] + current_agents: list[str] = [] + wanted = {"gptbot": "GPTBot", "claudebot": "ClaudeBot", "perplexitybot": "PerplexityBot"} + for raw in html.splitlines(): + line = raw.split("#", 1)[0].strip() + key, sep, value = line.partition(":") + if not sep: + continue + if key.strip().casefold() == "user-agent": + current_agents = [value.strip().casefold()] + elif key.strip().casefold() == "disallow" and value.strip() and current_agents: + for agent in current_agents: + if agent in wanted and wanted[agent] not in blocked: + blocked.append(wanted[agent]) + return (", ".join(blocked), site) if blocked else None + + +def detect_google_ads(html: str, site: str) -> tuple[str, str] | None: + match = re.search(r"\bAW-\d+\b|googleadservices\.com", html, re.IGNORECASE) + return (match.group(0), site) if match else None + + +def detect_hiring(html: str, site: str) -> tuple[str, str] | None: + return ("true", site) if _present(CAREER_WORDS, html) else None + + +def detect_contact_form(html: str, site: str) -> tuple[str, str] | None: + for href, label in re.findall( + r']*href=["\']([^"\']+)["\'][^>]*>(.*?)', html, re.IGNORECASE | re.DOTALL + ): + text = re.sub(r"<[^>]+>", " ", label) + if _present(CONTACT_WORDS, f"{href} {text}"): + url = urljoin(site, href) + return url, url + if re.search(r" dict[str, object]: + return {"key": key, "label": label, "cost": "free", "detect": detector} + + +CATALOG: dict[str, dict[str, object]] = { + "NO_WEBSITE": _definition("NO_WEBSITE", "No website", detect_no_website), + "NO_ONLINE_BOOKING": _definition( + "NO_ONLINE_BOOKING", "No online booking", detect_no_booking + ), + "NO_SCHEMA_MARKUP": _definition( + "NO_SCHEMA_MARKUP", "No JSON-LD schema", detect_no_schema + ), + "BLOG_STALE": _definition("BLOG_STALE", "Blog stale or absent", detect_blog_stale), + "TECH_STACK": _definition("TECH_STACK", "Detected technology", detect_tech_stack), + "BLOCKS_AI_CRAWLERS": _definition( + "BLOCKS_AI_CRAWLERS", "Blocks AI crawlers", detect_blocks_ai + ), + "RUNNING_GOOGLE_ADS": _definition( + "RUNNING_GOOGLE_ADS", "Google Ads tag", detect_google_ads + ), + "HIRING_ROLE": _definition("HIRING_ROLE", "Hiring page or role", detect_hiring), + "CONTACT_FORM_URL": _definition( + "CONTACT_FORM_URL", "Contact form", detect_contact_form + ), +} +SIGNALS = CATALOG + + +def confirmation_path(home: Path | None = None) -> Path: + return (home or Path.home() / ".coldforge") / "signals.yaml" + + +def confirmed_signals(home: Path | None = None) -> set[str]: + path = confirmation_path(home) + if not path.exists(): + return set() + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + values = data.get("confirmed", []) if isinstance(data, dict) else data + return {str(value) for value in values if str(value) in CATALOG} + + +def confirm(keys: list[str], home: Path | None = None) -> set[str]: + selected = set(CATALOG) if any(key.casefold() == "free" for key in keys) else set(keys) + unknown = selected - CATALOG.keys() + if unknown: + raise ValueError("unknown signals: " + ", ".join(sorted(unknown))) + selected |= confirmed_signals(home) + path = confirmation_path(home) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(yaml.safe_dump({"confirmed": sorted(selected)}), encoding="utf-8") + return selected + + +def profile_company(company: Company, *, fetch, confirmed: set[str]) -> list[tuple[str, str, str]]: + """Collect confirmed signals using at most home, robots and one useful page.""" + active = confirmed & CATALOG.keys() + if not active: + return [] + site = _site_url(company) + if not site: + return [("NO_WEBSITE", "true", "no website supplied")] if "NO_WEBSITE" in active else [] + home_html = fetch(site) + if home_html is None: + return [("NO_WEBSITE", "true", site)] if "NO_WEBSITE" in active else [] + robots_url = urljoin(site.rstrip("/") + "/", "robots.txt") + robots = fetch(robots_url) or "" + useful_url = _useful_link(home_html, site) + useful_html = "" + if useful_url and _robots_allows(robots, useful_url): + useful_html = fetch(useful_url) or "" + combined = f"{home_html}\n{useful_html}" + observations: list[tuple[str, str, str]] = [] + for key in sorted(active): + detector = CATALOG[key]["detect"] + source = robots if key == "BLOCKS_AI_CRAWLERS" else combined + evidence_site = robots_url if key == "BLOCKS_AI_CRAWLERS" else site + result = detector(source, evidence_site) # type: ignore[operator] + if result: + observations.append((key, result[0], result[1])) + return observations + + +def _site_url(company: Company) -> str: + value = company.website or company.domain + if not value: + return "" + return value if "://" in value else f"https://{value}" + + +def _useful_link(html: str, site: str) -> str: + for href, label in re.findall( + r']*href=["\']([^"\']+)["\'][^>]*>(.*?)', html, re.IGNORECASE | re.DOTALL + ): + text = re.sub(r"<[^>]+>", " ", label) + useful_words = CAREER_WORDS + CONTACT_WORDS + ("blog", "actualités", "news") + if _present(useful_words, f"{href} {text}"): + return urljoin(site, href) + return "" + + +def _robots_allows(robots: str, url: str) -> bool: + path = "/" + url.split("/", 3)[3] if url.count("/") >= 3 else "/" + applies = False + for raw in robots.splitlines(): + key, sep, value = raw.split("#", 1)[0].partition(":") + if not sep: + continue + if key.strip().casefold() == "user-agent": + applies = value.strip() == "*" or value.strip().casefold() == "coldforgebot" + elif applies and key.strip().casefold() == "disallow": + rule = value.strip() + if rule and path.startswith(rule): + return False + return True diff --git a/docs/SPEC-sellbird-pipeline.md b/docs/SPEC-sellbird-pipeline.md new file mode 100644 index 0000000..170e464 --- /dev/null +++ b/docs/SPEC-sellbird-pipeline.md @@ -0,0 +1,61 @@ +# Spec — pipeline « prospection » dans coldforge (idées de Sellbird, code original) + +Licence : coldforge est MIT, Sellbird est AGPL-3.0. **Ne copier aucun code ni aucun prompt de Sellbird.** +On reprend des idées (un pipeline découvrir → profiler → décideur → vérifier → garde d'envoi), pas le texte. +Explee (icp build + leads score) et BabyLoveGrowth (geo check + content plan/draft) existent déjà : ne pas y toucher. + +## Contraintes dures +- Stdlib + `requests` + `typer` + `rich` + `pyyaml` seulement (dépendances actuelles). Aucun nouveau paquet obligatoire. +- Tout passe par `Store` (coldforge/db.py) ; migration additive dans `_migrate`, jamais de DROP. +- Zéro appel réseau dans les tests : injecter une fonction `fetch(url) -> str | None` ; fixtures HTML dans `tests/fixtures/`. +- Aucun envoi réel : l'existant `DryRunSender` reste le défaut. Rien n'est envoyé sans approbation. +- Chaque module a une fonction pure testable ; les 38 tests existants restent verts. +- Une règle d'honnêteté par module : un échec est une observation (« aucune page équipe trouvée »), jamais un silence. + +## Modules à créer (dans `coldforge/`) + +### 1. `companies.py` + tables `companies`, `company_signals` +`Company(id, name, domain, website, city, category, phone, source, created_at)`. Clé unique : `domain` (sinon `name+city`). +`Store.upsert_company`, `list_companies`, `add_company_signal(company_id, key, value, evidence_url)`, `signals_of(company_id)`. + +### 2. `discover.py` +- `discover_osm(category, city, *, fetch_json) -> list[Company]` : Overpass API (gratuit, sans clé). Filtre les entrées sans nom, dédoublonne par domaine. +- `discover_csv(path)` : import d'un CSV (name, website, city, category, phone). +- `estimate(...)` : toujours afficher le coût avant (0 € pour OSM) — le contrat `--estimate` existe pour de futures sources payantes. +- CLI : `coldforge discover --source osm --category plumber --city Lyon [--estimate]`. + +### 3. `signals.py` — profileur HTTP gratuit (aucun appel modèle) +Catalogue déclaratif (dict) de signaux, chacun avec `key`, `label`, `cost` (« free »), `detect(html, site) -> (value, evidence) | None` : +`NO_WEBSITE`, `NO_ONLINE_BOOKING` (pas de lien Calendly/Doctolib/Planity/formulaire de réservation), `NO_SCHEMA_MARKUP` (pas de JSON-LD), +`BLOG_STALE` (dernier article > 12 mois ou absent), `TECH_STACK` (WordPress/Wix/Shopify/Webflow par signatures), `BLOCKS_AI_CRAWLERS` (robots.txt : GPTBot/ClaudeBot/PerplexityBot), +`RUNNING_GOOGLE_ADS` (gtag AW-/googleadservices), `HIRING_ROLE` (page carrières), `CONTACT_FORM_URL`. +Mots-clés en **français et anglais**. +**Porte de confirmation** : aucun signal n'est collecté tant que l'utilisateur ne l'a pas confirmé (`~/.coldforge/signals.yaml`). +CLI : `coldforge signals list`, `signals confirm free|KEY…`, `signals profile [--limit N]`. +Budget réseau : 3 requêtes max par entreprise (home, robots.txt, une page utile), User-Agent déclaré, timeout 10 s, respecte robots.txt pour le crawl des pages. + +### 4. `people.py` — qui décide +`find_people(company, *, fetch) -> list[Person]`, **2 personnes max** par entreprise, uniquement depuis les pages publiques de l'entreprise +(`/equipe`, `/a-propos`, `/about`, `/team`, `/mentions-legales` — le dirigeant y est nommé en France). Titres décideurs FR+EN (gérant, dirigeant, fondateur, directeur, owner, CEO…). +Chaque personne porte `source_url`. Aucun scraping de réseaux sociaux. +`guess_email_pattern(known_emails, domain)` + `candidates(person, pattern)` ; la vérification réutilise `verify.verify_email`. +Seuls les statuts `ok` sont envoyables ; `risky`/`invalid` ne le sont jamais. Les personnes deviennent des `Lead` (table existante) liés à la `Company`. +CLI : `coldforge people find [--company X]`. + +### 5. `cohort.py` +`cohort(store, must=[…], none_of=[…], ranges={key:(lo,hi)}) -> list[Company]` et `count`. CLI : `coldforge cohort --must NO_ONLINE_BOOKING --must RUNNING_GOOGLE_ADS --none-of NO_WEBSITE` affiche le compte puis la liste avec la **raison** de chaque inclusion. +`coldforge export --cohort … --csv out.csv` : CSV prêt pour un séquenceur (liste seule, sans envoi). + +### 6. `gate.py` + file d'approbation +`check_message(store, settings, message, now) -> GateResult(ok, reasons[])`, déterministe, sans modèle : +adresse supprimée, `verify_status != ok`, plafond quotidien (`sent_today`), heures calmes (08h–19h locale du destinataire par défaut, configurable), ligne de désinscription et adresse postale présentes (réutiliser `lint.py`), réponse déjà reçue. +Nouvelle colonne `messages.approved INTEGER DEFAULT 0` (migration additive) ; `tick` n'envoie que `approved=1` sauf `--auto-approve`. +CLI : `coldforge outbox list`, `outbox approve `, `outbox reject `. Une approbation qui échoue la garde est refusée avec les raisons. + +## Tests (pytest, hors réseau) +Un fichier par module : `tests/test_companies.py`, `test_discover.py`, `test_signals.py`, `test_people.py`, `test_cohort.py`, `test_gate.py`. +Chaque détecteur de signal : un cas positif ET un cas négatif en fixture HTML (FR et EN). +`test_gate.py` : un test par raison de refus + un cas passant. Cible : toute la suite verte, `ruff check` propre. + +## Hors périmètre +Sources payantes (DataForSEO, Serper…), LinkedIn, tableau de bord web, boucle « heartbeat » autonome, envoi via Gmail/Microsoft. À noter dans le README comme suite possible. diff --git a/tests/fixtures/signals_negative_en.html b/tests/fixtures/signals_negative_en.html new file mode 100644 index 0000000..bf5c015 --- /dev/null +++ b/tests/fixtures/signals_negative_en.html @@ -0,0 +1,6 @@ + + + +Book an appointment +
+ diff --git a/tests/fixtures/signals_positive_fr.html b/tests/fixtures/signals_positive_fr.html new file mode 100644 index 0000000..e644410 --- /dev/null +++ b/tests/fixtures/signals_positive_fr.html @@ -0,0 +1,8 @@ + + + + +Nous recrutons — carrières +Contactez-nous +
+ diff --git a/tests/test_cohort.py b/tests/test_cohort.py new file mode 100644 index 0000000..0f9a814 --- /dev/null +++ b/tests/test_cohort.py @@ -0,0 +1,16 @@ +from coldforge.cohort import cohort, count, export_csv +from coldforge.companies import Company +from coldforge.db import Store + + +def test_cohort_filters_and_exports(tmp_path): + with Store(tmp_path / "db.sqlite") as store: + company = store.upsert_company(Company("A", website="a.fr")) + store.add_company_signal(company.id, "ADS", "1", "a.fr") + store.add_company_signal(company.id, "SIZE", "12", "a.fr") + selected = cohort(store, must=["ADS"], none_of=["NO_SITE"], ranges={"SIZE": (10, 20)}) + assert [item.id for item in selected] == [company.id] + assert count(store, must=["ADS"]) == 1 + path = tmp_path / "out.csv" + assert export_csv(selected, path) == 1 + assert "name,domain" in path.read_text(encoding="utf-8") diff --git a/tests/test_companies.py b/tests/test_companies.py new file mode 100644 index 0000000..6b848b2 --- /dev/null +++ b/tests/test_companies.py @@ -0,0 +1,18 @@ +from coldforge.companies import Company +from coldforge.db import Store + + +def test_company_upsert_and_signals(tmp_path): + with Store(tmp_path / "db.sqlite") as store: + first = store.upsert_company(Company("Acme", website="https://www.acme.fr", city="Lyon")) + second = store.upsert_company(Company("Acme SAS", website="https://acme.fr/about")) + assert first.id == second.id + store.add_company_signal(first.id, "SIZE", "12", "https://acme.fr") + assert store.signals_of(first.id)["SIZE"] == ("12", "https://acme.fr") + + +def test_company_without_domain_dedupes_on_name_city(tmp_path): + with Store(tmp_path / "db.sqlite") as store: + a = store.upsert_company(Company("Plomberie Rhône", city="Lyon")) + b = store.upsert_company(Company("plomberie rhône", city="LYON")) + assert a.id == b.id diff --git a/tests/test_discover.py b/tests/test_discover.py new file mode 100644 index 0000000..d6fcbb5 --- /dev/null +++ b/tests/test_discover.py @@ -0,0 +1,23 @@ +import csv + +from coldforge.discover import discover_csv, discover_osm, estimate + + +def test_discover_osm_filters_names_and_domains(): + payload = {"elements": [ + {"tags": {"name": "A", "website": "https://www.a.fr", "phone": "1"}}, + {"tags": {"name": "A duplicate", "website": "https://a.fr/about"}}, + {"tags": {"website": "https://unnamed.fr"}}, + ]} + companies = discover_osm("plumber", "Lyon", fetch_json=lambda _url: payload) + assert [company.name for company in companies] == ["A"] + assert estimate()["cost_eur"] == 0 + + +def test_discover_csv(tmp_path): + path = tmp_path / "companies.csv" + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=("name", "website", "city", "category", "phone")) + writer.writeheader() + writer.writerow({"name": "A", "website": "a.fr", "city": "Paris", "category": "x", "phone": "2"}) + assert discover_csv(path)[0].domain == "a.fr" diff --git a/tests/test_gate.py b/tests/test_gate.py new file mode 100644 index 0000000..221b795 --- /dev/null +++ b/tests/test_gate.py @@ -0,0 +1,46 @@ +from datetime import datetime, time + +from coldforge.config import Settings +from coldforge.db import Store +from coldforge.gate import check_message +from coldforge.models import Campaign, Lead, Message + + +def _settings(tmp_path): + return Settings( + home=tmp_path, db_path=tmp_path / "db.sqlite", anthropic_api_key=None, + model="x", tavily_api_key=None, from_name="A", from_email="a@x.fr", + smtp_host=None, smtp_port=587, smtp_user=None, smtp_password=None, + smtp_starttls=True, imap_host=None, imap_port=993, imap_user=None, + imap_password=None, daily_limit=40, send_window=(time(0), time(23, 59)), + send_days=set(range(7)), min_gap_seconds=0, postal_address="1 rue Exemple, Lyon", + ) + + +def _message(store): + lead = store.upsert_lead(Lead("person@x.fr", verify_status="ok")) + store.set_verify_status(lead.id, "ok") + campaign = store.create_campaign(Campaign("c")) + return Message(campaign.id, lead.id, 0, datetime(2030, 1, 1, 10), subject="Bonjour", + body="Bonjour. Pour vous désinscrire, répondez non.\n1 rue Exemple, Lyon") + + +def test_gate_passing_and_each_refusal(tmp_path): + settings = _settings(tmp_path) + with Store(settings.db_path) as store: + message = _message(store) + now = datetime(2030, 1, 1, 10) + assert check_message(store, settings, message, now).ok + store.suppress("person@x.fr") + assert "suppressed" in " ".join(check_message(store, settings, message, now).reasons) + store.unsuppress("person@x.fr") + store.set_verify_status(message.lead_id, "risky") + assert "verify_status" in " ".join(check_message(store, settings, message, now).reasons) + store.set_verify_status(message.lead_id, "ok") + message.body = "No footer" + reasons = check_message(store, settings, message, now).reasons + assert "missing unsubscribe line" in reasons and "missing postal address" in reasons + message.body = "Unsubscribe\n1 rue Exemple, Lyon" + assert "quiet-hours" in " ".join(check_message(store, settings, message, datetime(2030, 1, 1, 22)).reasons) + store.record_reply(message.lead_id, message.campaign_id) + assert "already replied" in " ".join(check_message(store, settings, message, now).reasons) diff --git a/tests/test_people.py b/tests/test_people.py new file mode 100644 index 0000000..4890ea8 --- /dev/null +++ b/tests/test_people.py @@ -0,0 +1,22 @@ +from coldforge.companies import Company +from coldforge.people import Person, candidates, find_people, guess_email_pattern + + +def test_find_people_public_pages_only_and_limit_two(): + seen = [] + + def fetch(url): + seen.append(url) + return "

Gérante : Alice Martin

Bob Durand — Founder

" + + people = find_people(Company("X", website="https://x.fr"), fetch=fetch) + assert len(people) == 2 + assert all(person.source_url.startswith("https://x.fr/") for person in people) + assert all("linkedin" not in url for url in seen) + + +def test_email_pattern_and_candidates(): + assert guess_email_pattern(["alice.martin@x.fr"], "x.fr") == "first.last" + person = Person("Élodie", "Le Brun", "Directrice", "https://x.fr/equipe") + pattern = guess_email_pattern(["alice.martin@x.fr"], "x.fr") + assert candidates(person, pattern) == ["elodie.lebrun@x.fr"] diff --git a/tests/test_signals.py b/tests/test_signals.py new file mode 100644 index 0000000..3da70d7 --- /dev/null +++ b/tests/test_signals.py @@ -0,0 +1,46 @@ +from pathlib import Path + +from coldforge.companies import Company +from coldforge.signals import CATALOG, confirm, confirmed_signals, profile_company + +FIXTURES = Path(__file__).parent / "fixtures" + + +def test_each_detector_has_positive_and_negative_fixture(): + positive = (FIXTURES / "signals_positive_fr.html").read_text(encoding="utf-8") + negative = (FIXTURES / "signals_negative_en.html").read_text(encoding="utf-8") + assert CATALOG["NO_ONLINE_BOOKING"]["detect"](positive, "https://x.fr") + assert not CATALOG["NO_ONLINE_BOOKING"]["detect"](negative, "https://x.fr") + assert CATALOG["NO_SCHEMA_MARKUP"]["detect"](positive, "https://x.fr") + assert not CATALOG["NO_SCHEMA_MARKUP"]["detect"](negative, "https://x.fr") + assert CATALOG["BLOG_STALE"]["detect"](positive, "https://x.fr") + assert not CATALOG["BLOG_STALE"]["detect"](negative, "https://x.fr") + assert CATALOG["TECH_STACK"]["detect"](positive, "https://x.fr") + assert not CATALOG["TECH_STACK"]["detect"](negative, "https://x.fr") + assert CATALOG["RUNNING_GOOGLE_ADS"]["detect"](positive, "https://x.fr") + assert not CATALOG["RUNNING_GOOGLE_ADS"]["detect"](negative, "https://x.fr") + assert CATALOG["HIRING_ROLE"]["detect"](positive, "https://x.fr") + assert not CATALOG["HIRING_ROLE"]["detect"](negative, "https://x.fr") + assert CATALOG["CONTACT_FORM_URL"]["detect"](positive, "https://x.fr") + assert not CATALOG["CONTACT_FORM_URL"]["detect"](negative, "https://x.fr") + robots = "User-agent: GPTBot\nDisallow: /\nUser-agent: ClaudeBot\nDisallow: /private" + assert CATALOG["BLOCKS_AI_CRAWLERS"]["detect"](robots, "https://x.fr/robots.txt") + assert not CATALOG["BLOCKS_AI_CRAWLERS"]["detect"]("User-agent: *\nDisallow:", "x") + assert CATALOG["NO_WEBSITE"]["detect"](None, "") + assert not CATALOG["NO_WEBSITE"]["detect"]("", "https://x.fr") + + +def test_confirmation_and_three_request_budget(tmp_path): + confirm(["free"], tmp_path) + assert confirmed_signals(tmp_path) == set(CATALOG) + calls = [] + + def fetch(url): + calls.append(url) + if url.endswith("robots.txt"): + return "User-agent: *\nDisallow:" + return 'Contact' + + found = profile_company(Company("X", website="https://x.fr"), fetch=fetch, confirmed=set(CATALOG)) + assert len(calls) <= 3 + assert found