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.
Address review: Harvey's own template as base, safe backups and writes
Ethane9886964bf03
diff --git a/harvey/trainer.py b/harvey/trainer.pyindex fa4bcff..be6b3db 100644--- a/harvey/trainer.py+++ b/harvey/trainer.py@@ -18,7 +18,7 @@ from bs4 import BeautifulSoupfrom dotenv import load_dotenvfrom harvey.brain import Brain-from harvey.config import BrainConfig, ConfigError, _find_config_file, load_brain_config+from harvey.config import BrainConfig, load_brain_configfrom harvey.state import StateManagerlogger = logging.getLogger("harvey.trainer")@@ -323,9 +323,10 @@ def brain_section(brain_config: BrainConfig) -> dict:# 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.+# send limits, compliance, offer, the sender's name, email and tone, ...),+# which are the operator's choices.LEARNED_FIELDS = {- "persona": ("company", "tone"),+ "persona": ("company",),"product": ("name", "description", "pricing", "key_benefits", "objection_responses"),"icp": ("industries", "company_size", "titles", "geography"),}@@ -334,6 +335,14 @@ LEARNED_FIELDS = {UNTRAINED_COMPANY = "Your Company"+def _persona_untrained(persona) -> bool:+ return (+ not isinstance(persona, dict)+ or persona.get("company") == UNTRAINED_COMPANY+ or not persona.get("email")+ )++def merge_trained_config(learned: dict, existing: dict | None) -> dict:"""``existing`` with what training learned laid over it.@@ -341,11 +350,10 @@ def merge_trained_config(learned: dict, existing: dict | None) -> dict:The brain selection always comes from the trainer, which already startsfrom the existing choice unless ``--provider`` overrode it."""- if not isinstance(existing, dict):+ if not isinstance(existing, dict) or not existing:return learnedmerged = copy.deepcopy(existing)- persona = existing.get("persona")- untrained = not isinstance(persona, dict) or persona.get("company") in ("", None, UNTRAINED_COMPANY)+ untrained = _persona_untrained(existing.get("persona"))for section, value in learned.items():if not isinstance(merged.get(section), dict):merged[section] = copy.deepcopy(value)@@ -360,44 +368,50 @@ def merge_trained_config(learned: dict, existing: dict | None) -> dict:return merged-def write_trained_config(learned: dict, path: Path, base_path: Path | None = None) -> dict:+def _backup(path: Path, raw: str) -> Path:+ """Save ``raw`` next to ``path`` without overwriting an earlier backup."""+ backup = path.with_name(path.name + ".bak")+ if backup.exists():+ stamp = time.strftime("%Y%m%d-%H%M%S")+ backup = path.with_name(f"{path.name}.{stamp}.bak")+ backup.write_text(raw, encoding="utf-8")+ return backup+++def write_trained_config(learned: dict, path: Path) -> 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.+ The base is ``path`` itself when it exists. On a first training it is the+ harvey.yaml next to it (the template Harvey ships, with the provider and+ compliance blocks), never a config found elsewhere on disk. A base that+ has content but can't be read as YAML is backed up before it is+ replaced. The new file is swapped in whole, so a failed write never+ leaves a half-written config. Returns what was written."""path = Path(path)- source = path if path.exists() else base_path+ source = path if path.exists() else path.with_name("harvey.yaml")existing = None- if source is not None and Path(source).exists():- raw = Path(source).read_text(encoding="utf-8")+ if source.exists():+ raw = 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")+ if not isinstance(existing, dict) and source == path and raw.strip():+ backup = _backup(path, raw)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)+ if config is not learned and source == path:+ print(f" Kept your settings from {path.name} (email provider, schedule, limits,")+ print(" compliance, sender identity); updated the product, targeting and company.")++ tmp = path.with_name(path.name + ".tmp")+ with open(tmp, "w", encoding="utf-8") as f:+ yaml.safe_dump(config, f, default_flow_style=False, sort_keys=False)+ os.replace(tmp, path)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@@ -492,7 +506,8 @@ class Trainer:config_path = Path(output_path)if not config_path.is_absolute():config_path = PROJECT_ROOT / config_path- config = write_trained_config(config, config_path, base_path=_current_config_path())+ guessed_email = config["persona"]["email"]+ config = write_trained_config(config, config_path)# Generate product knowledge skillawait self._generate_product_knowledge(product_info, icp_info, competitive_intel)@@ -514,8 +529,12 @@ class Trainer:print(f" - skills/product_knowledge.md")if competitive_intel.get("competitors"):print(f" - skills/competitive_intel.md")- print(f"\n Review {config_path} and adjust as needed — especially the")- print(f" persona name/email, which I guessed from your domain.")+ if config["persona"].get("email") == guessed_email:+ print(f"\n Review {config_path} and adjust as needed — especially the")+ print(f" persona name/email, which I guessed from your domain.")+ else:+ print(f"\n Review {config_path} and adjust as needed. Emails still go out as")+ print(f" {config['persona'].get('name', '')} <{config['persona']['email']}>.")print(f" Then run: harvey run\n")return configdiff --git a/tests/test_trainer_config.py b/tests/test_trainer_config.pyindex 86864e2..fa8f84d 100644--- a/tests/test_trainer_config.py+++ b/tests/test_trainer_config.py@@ -95,12 +95,11 @@ def test_retraining_keeps_every_setting_training_does_not_learn(tmp_path):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"):+ # The sender identity and voice are the user's, not training guesses.+ for key in ("name", "role", "email", "linkedin", "tone"):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"):@@ -124,7 +123,7 @@ def test_first_training_keeps_the_template_settings(tmp_path):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)+ out = write_trained_config(LEARNED, path)assert out["channels"]["email"]["provider"] == "gmail"assert out["compliance"]["precleared"]["enabled"] is False@@ -145,4 +144,43 @@ def test_unreadable_config_is_backed_up_not_lost(tmp_path):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"+ backups = list(tmp_path.glob("harvey.local.yaml*.bak"))+ assert [b.read_text() for b in backups] == ["channels: [unclosed\n"]+++def test_an_earlier_backup_is_never_overwritten(tmp_path):+ path = tmp_path / "harvey.local.yaml"+ (tmp_path / "harvey.local.yaml.bak").write_text("precious")+ path.write_text("channels: [unclosed\n")+ write_trained_config(LEARNED, path)+ assert (tmp_path / "harvey.local.yaml.bak").read_text() == "precious"+ assert sorted(b.read_text() for b in tmp_path.glob("harvey.local.yaml*.bak")) == [+ "channels: [unclosed\n", "precious",+ ]+++def test_an_empty_config_needs_no_backup(tmp_path):+ path = tmp_path / "harvey.local.yaml"+ path.write_text("\n")+ assert write_trained_config(LEARNED, path) == LEARNED+ assert list(tmp_path.glob("*.bak")) == []+++def test_first_training_ignores_configs_outside_harveys_folder(tmp_path, monkeypatch):+ # Running `harvey train` from another project's folder must not copy that+ # project's provider or sender identity into Harvey.+ elsewhere = tmp_path / "other-project"+ elsewhere.mkdir()+ write(elsewhere / "harvey.local.yaml", TUNED)+ monkeypatch.chdir(elsewhere)+ home = tmp_path / "harvey"+ home.mkdir()+ assert write_trained_config(LEARNED, home / "harvey.local.yaml") == LEARNED+++def test_a_real_sender_with_a_blank_company_is_kept(tmp_path):+ path = tmp_path / "harvey.local.yaml"+ write(path, {**TUNED, "persona": {**TUNED["persona"], "company": ""}})+ out = write_trained_config(LEARNED, path)+ assert out["persona"]["email"] == "[email protected]"+ assert out["persona"]["company"] == "Acme Roofing"