Autonomous AI sales agent powered by Claude Code or Codex. Finds prospects, writes cold emails, sends campaigns, handles replies, books meetings. No API keys needed — runs on your Claude or Codex subscriptions.
Keep the operator's settings when harvey train rewrites the config
Ethana4f8b75244b8
diff --git a/README.md b/README.mdindex 8bfdb05..19d2732 100644--- a/README.md+++ b/README.md@@ -131,7 +131,8 @@ python3.13 -m venv .venv && source .venv/bin/activate && pip install -e .# 2. Configure — every variable is documented inline with where to get itcp .env.example .env && $EDITOR .env-# 3. Learn your product from your website+# 3. Learn your product from your website (writes harvey.local.yaml; re-running+# it updates the product, targeting and company and keeps your other settings)harvey train https://your-company.com# 4. Choose what makes a good prospect (see below — this one matters)diff --git a/harvey/trainer.py b/harvey/trainer.pyindex 354be9c..fa4bcff 100644--- a/harvey/trainer.py+++ b/harvey/trainer.py@@ -5,6 +5,7 @@ Falls back to manual scraping if no Cloudflare credentials are configured."""import asyncio+import copyimport loggingimport osimport time@@ -17,7 +18,7 @@ from bs4 import BeautifulSoupfrom dotenv import load_dotenvfrom harvey.brain import Brain-from harvey.config import BrainConfig, load_brain_config+from harvey.config import BrainConfig, ConfigError, _find_config_file, load_brain_configfrom harvey.state import StateManagerlogger = logging.getLogger("harvey.trainer")@@ -320,6 +321,83 @@ def brain_section(brain_config: BrainConfig) -> dict:return section+# What training learns from a website. Retraining replaces exactly these and+# keeps everything else in the existing config (email provider, quiet hours,+# send limits, compliance, offer, ...), which are the operator's choices.+LEARNED_FIELDS = {+ "persona": ("company", "tone"),+ "product": ("name", "description", "pricing", "key_benefits", "objection_responses"),+ "icp": ("industries", "company_size", "titles", "geography"),+}+# The shipped template's placeholder company: a persona still carrying it+# was never set up, so training fills in the whole persona.+UNTRAINED_COMPANY = "Your Company"+++def merge_trained_config(learned: dict, existing: dict | None) -> dict:+ """``existing`` with what training learned laid over it.++ Sections the existing config lacks come from ``learned`` (its defaults).+ The brain selection always comes from the trainer, which already starts+ from the existing choice unless ``--provider`` overrode it.+ """+ if not isinstance(existing, dict):+ return learned+ merged = copy.deepcopy(existing)+ persona = existing.get("persona")+ untrained = not isinstance(persona, dict) or persona.get("company") in ("", None, UNTRAINED_COMPANY)+ for section, value in learned.items():+ if not isinstance(merged.get(section), dict):+ merged[section] = copy.deepcopy(value)+ for section, keys in LEARNED_FIELDS.items():+ for key in keys:+ if key in learned.get(section, {}):+ merged[section][key] = copy.deepcopy(learned[section][key])+ if untrained:+ merged["persona"].update(copy.deepcopy(learned.get("persona", {})))+ if "brain" in learned:+ merged["brain"] = copy.deepcopy(learned["brain"])+ return merged+++def write_trained_config(learned: dict, path: Path, base_path: Path | None = None) -> dict:+ """Write a trained config to ``path`` without losing the operator's settings.++ The base is ``path`` itself when it exists, else ``base_path`` (the+ config Harvey runs on today, usually the harvey.yaml template). A base+ that can't be read as YAML is copied to ``<path>.bak`` before it is+ replaced, so nothing is lost. Returns what was written.+ """+ path = Path(path)+ source = path if path.exists() else base_path+ existing = None+ if source is not None and Path(source).exists():+ raw = Path(source).read_text(encoding="utf-8")+ try:+ existing = yaml.safe_load(raw)+ except yaml.YAMLError:+ existing = None+ if not isinstance(existing, dict) and source == path:+ backup = path.with_name(path.name + ".bak")+ backup.write_text(raw, encoding="utf-8")+ print(f" Couldn't read the existing {path.name}; saved it as {backup.name}.")+ config = merge_trained_config(learned, existing)+ if isinstance(existing, dict):+ print(f" Kept your settings from {Path(source).name} (email provider, schedule,")+ print(" limits, compliance); updated the product, targeting and company.")+ with open(path, "w", encoding="utf-8") as f:+ yaml.dump(config, f, default_flow_style=False, sort_keys=False)+ return config+++def _current_config_path() -> Path | None:+ """The config Harvey loads today, or None if there isn't one."""+ try:+ return Path(_find_config_file())+ except ConfigError:+ return None++class Trainer:def __init__(self, brain_config: BrainConfig | None = None):# Without an explicit choice, train with whatever provider the@@ -414,8 +492,7 @@ class Trainer:config_path = Path(output_path)if not config_path.is_absolute():config_path = PROJECT_ROOT / config_path- with open(config_path, "w") as f:- yaml.dump(config, f, default_flow_style=False, sort_keys=False)+ config = write_trained_config(config, config_path, base_path=_current_config_path())# Generate product knowledge skillawait self._generate_product_knowledge(product_info, icp_info, competitive_intel)diff --git a/tests/test_trainer_config.py b/tests/test_trainer_config.pynew file mode 100644index 0000000..86864e2--- /dev/null+++ b/tests/test_trainer_config.py@@ -0,0 +1,148 @@+"""Retraining replaces what training learns and keeps every other setting.++`harvey train` used to rewrite the config from scratch, so retraining reset+the email provider to instantly, quiet hours to New York and turned the+Precleared check off. These tests pin down what training owns.+"""++import yaml++from harvey.config import HarveyConfig+from harvey.paths import PROJECT_ROOT+from harvey.trainer import write_trained_config++LEARNED = {+ "persona": {+ "name": "Harvey", "company": "Acme Roofing", "role": "Business Development",+ "email": "[email protected]", "linkedin": "linkedin.com/in/harvey-acme-com",+ "tone": "warm, direct",+ },+ "product": {+ "name": "RoofBot", "description": "Answers roofing calls",+ "pricing": "$99/mo", "key_benefits": ["Never miss a call"],+ "objection_responses": {"too expensive": "One job pays for a year."},+ },+ "icp": {+ "industries": ["Roofing"], "company_size": "1-20 employees",+ "titles": ["Owner"], "geography": ["United States"],+ },+ "channels": {+ "email": {"enabled": True, "provider": "instantly", "max_daily_sends": 50},+ "linkedin": {"enabled": True, "max_daily_connections": 20, "max_daily_messages": 10},+ },+ "usage": {+ "max_daily_claude_percent": 80, "heartbeat_interval_minutes": 15,+ "quiet_hours": {"start": "22:00", "end": "07:00", "timezone": "America/New_York"},+ },+ "brain": {"provider": "claude"},+}++# A config someone trained before and then tuned by hand.+TUNED = {+ "persona": {+ "name": "Ethan", "company": "Old Co", "role": "Founder",+ "email": "[email protected]", "linkedin": "linkedin.com/in/ethan", "tone": "casual",+ },+ "product": {+ "name": "OldBot", "description": "Old", "pricing": "$1",+ "key_benefits": ["old"], "objection_responses": {},+ "offer": {"goal": "book_call", "booking_url": "https://cal.com/ethan"},+ },+ "icp": {+ "industries": ["SaaS"], "company_size": "10-50", "titles": ["CEO"],+ "geography": ["UK"], "hiring_signals": ["SDR"],+ "geo_coordinates": {"London": "51.5,-0.12,50"},+ },+ "channels": {+ "email": {+ "enabled": True, "provider": "gmail", "max_daily_sends": 20,+ "require_approval": False, "send_to_risky": True, "max_bounce_rate": 0.02,+ },+ "linkedin": {"enabled": False, "max_daily_connections": 5, "max_daily_messages": 2},+ },+ "usage": {+ "max_daily_claude_percent": 40, "heartbeat_interval_minutes": 30,+ "quiet_hours": {"start": "20:00", "end": "08:00", "timezone": "Europe/London"},+ },+ "brain": {"provider": "claude"},+ "compliance": {"precleared": {+ "enabled": True, "sender_country": "GB", "address_source": "published",+ "prospect_country": "GB",+ }},+ "writer": {"humanizer": True},+}+++def write(path, data):+ path.write_text(yaml.safe_dump(data, sort_keys=False))+++def read(path):+ return yaml.safe_load(path.read_text())+++def test_retraining_keeps_every_setting_training_does_not_learn(tmp_path):+ path = tmp_path / "harvey.local.yaml"+ write(path, TUNED)+ out = write_trained_config(LEARNED, path)++ assert read(path) == out+ # Settings the user chose survive.+ assert out["channels"] == TUNED["channels"]+ assert out["usage"] == TUNED["usage"]+ assert out["compliance"] == TUNED["compliance"]+ assert out["writer"] == TUNED["writer"]+ assert out["product"]["offer"] == TUNED["product"]["offer"]+ assert out["icp"]["hiring_signals"] == ["SDR"]+ assert out["icp"]["geo_coordinates"] == {"London": "51.5,-0.12,50"}+ # The sender identity is the user's, not a training placeholder.+ for key in ("name", "role", "email", "linkedin"):+ assert out["persona"][key] == TUNED["persona"][key]+ # What training learns is replaced.+ assert out["persona"]["company"] == "Acme Roofing"+ assert out["persona"]["tone"] == "warm, direct"+ for key in ("name", "description", "pricing", "key_benefits", "objection_responses"):+ assert out["product"][key] == LEARNED["product"][key]+ for key in ("industries", "company_size", "titles", "geography"):+ assert out["icp"][key] == LEARNED["icp"][key]+ HarveyConfig(**out) # still a valid config+++def test_brain_selection_comes_from_the_trainer(tmp_path):+ # `harvey train --provider codex` must win over the file's old choice.+ path = tmp_path / "harvey.local.yaml"+ write(path, TUNED)+ learned = {**LEARNED, "brain": {"provider": "codex", "model": "gpt-5.5"}}+ assert write_trained_config(learned, path)["brain"] == {"provider": "codex", "model": "gpt-5.5"}+++def test_first_training_keeps_the_template_settings(tmp_path):+ # No harvey.local.yaml yet: the settings in harvey.yaml (gmail, the+ # Precleared block) carry over, and the untrained placeholder persona+ # is replaced with what training learned.+ template = tmp_path / "harvey.yaml"+ shipped = (PROJECT_ROOT / "harvey.yaml").read_text()+ template.write_text(shipped)+ path = tmp_path / "harvey.local.yaml"+ out = write_trained_config(LEARNED, path, base_path=template)++ assert out["channels"]["email"]["provider"] == "gmail"+ assert out["compliance"]["precleared"]["enabled"] is False+ assert out["persona"] == LEARNED["persona"]+ assert out["product"]["offer"]["goal"] == "book_call"+ assert template.read_text() == shipped # the template itself is untouched+ HarveyConfig(**out)+++def test_no_existing_config_writes_what_training_built(tmp_path):+ path = tmp_path / "harvey.local.yaml"+ assert write_trained_config(LEARNED, path) == LEARNED+ assert read(path) == LEARNED+++def test_unreadable_config_is_backed_up_not_lost(tmp_path):+ path = tmp_path / "harvey.local.yaml"+ path.write_text("channels: [unclosed\n")+ out = write_trained_config(LEARNED, path)+ assert out == LEARNED+ assert (tmp_path / "harvey.local.yaml.bak").read_text() == "channels: [unclosed\n"