Skip to content

The agent that grows with you

fix(left-core): keep migration notices in the home until an agent in any process delivers them

Teknium190f4e9f57f8
diff --git a/hermes_cli/left_core_migration.py b/hermes_cli/left_core_migration.py
index da73c0e997e..217e6931172 100644
--- a/hermes_cli/left_core_migration.py
+++ b/hermes_cli/left_core_migration.py
@@ -591,7 +591,7 @@ def recover_for_provider(name: Optional[str]) -> None:
"""Runtime resolution of *name*, a provider a left-core plugin supplies, in a home that uses it and lacks
the plugin: run :func:`recover_at_startup` now. The CLI and Desktop resolve the provider before the agent
(whose start runs the migration) exists, so they would otherwise stop at "unknown provider" on a home no
- ``hermes update`` migrated. Outcomes are logged and wait for the home's first agent, as at gateway start."""
+ ``hermes update`` migrated. Outcomes print to an interactive terminal, else wait for the home's first agent."""
feature = _provider_feature(name or "")
if feature is None:
return
@@ -603,7 +603,9 @@ def recover_for_provider(name: Optional[str]) -> None:
if plugin_present(feature.plugin, home) or get_provider_profile(str(name).strip().lower()) is not None:
return
if feature_in_use(feature, home, process_env=True):
- recover_at_startup()
+ # A terminal user sees the outcome now; otherwise (Desktop, gateway, a detached turn) the home's
+ # first agent in any process delivers it.
+ recover_at_startup(say=(lambda message: print(message, file=sys.stderr)) if _interactive() else None)
def profile_env_names() -> frozenset[str]:
@@ -670,7 +672,6 @@ def moved_plugin_hint(name: str) -> str:
_attempted: set[str] = set()
-_undelivered: dict[str, list[str]] = {}
_installs_held: ContextVar[bool] = ContextVar("left_core_installs_held", default=False)
@@ -688,9 +689,52 @@ def installs_held():
def defer_startup_notice(message: str) -> None:
"""Hand *message* to the active home's first agent (its startup-warning sink, through
:func:`recover_at_startup`), once. For boot-path work that runs before any agent exists."""
- from hermes_constants import get_hermes_home, hermes_home_key
+ from hermes_constants import get_hermes_home
logger.warning(message)
- _undelivered.setdefault(hermes_home_key(Path(get_hermes_home())), []).append(message)
+ _queue_notice(Path(get_hermes_home()), message)
+
+
+def _notice_file(home: Path) -> Path:
+ return home / "cache" / "left-core-notices.jsonl"
+
+
+def _queue_notice(home: Path, message: str) -> None:
+ """Keep *message* for *home*'s first agent in ANY process (:func:`_claim_notices`): the process that
+ produced it (a CLI resolving the provider, a gateway start) often runs no agent for that home itself."""
+ import json
+ path = _notice_file(home)
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "a", encoding="utf-8") as fh: # one short append per line: concurrent writers interleave
+ fh.write(json.dumps(message) + "\n")
+ except OSError as exc:
+ logger.debug("left-core notice not kept for %s: %s", home, exc)
+
+
+def _claim_notices(home: Path) -> list[str]:
+ """Take every notice kept for *home*, exactly once across processes: the rename is the claim, so of
+ several agents starting at once only one gets (and delivers) them."""
+ import json
+ import threading
+ path = _notice_file(home)
+ claimed = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}")
+ try:
+ os.replace(path, claimed)
+ except OSError: # nothing kept, or another process claimed it first
+ return []
+ try:
+ lines = claimed.read_text(encoding="utf-8").splitlines()
+ except OSError:
+ lines = []
+ finally:
+ claimed.unlink(missing_ok=True)
+ messages = []
+ for line in lines:
+ try:
+ messages.append(str(json.loads(line)))
+ except ValueError: # a torn write: skip that line only
+ continue
+ return messages
def plugin_present(plugin: str, home: Path) -> bool:
@@ -1014,9 +1058,9 @@ def _gateway_serves(home: Path) -> bool:
def recover_at_startup(*, say: Optional[Callable[[str], None]] = None) -> list[str]:
"""Agent/gateway start hook for the active home: one attempt per process per home. With *say*
- (an agent's startup-warning sink) outcomes are delivered now, together with any a gateway-start
- attempt or boot maintenance (:func:`defer_startup_notice`) queued for this home; without it they are
- logged and queued for the home's first agent.
+ (an agent's startup-warning sink) outcomes are delivered now, together with any an earlier attempt or
+ boot maintenance (:func:`defer_startup_notice`) kept for this home in any process; without it they are
+ logged and kept in the home (:func:`_queue_notice`) for its first agent, in whichever process.
Returns installed plugin names."""
from agent.safe_worker_policy import worker_config_snapshot
if _installs_held.get():
@@ -1032,7 +1076,7 @@ def recover_at_startup(*, say: Optional[Callable[[str], None]] = None) -> list[s
def deliver(message: str) -> None:
if say is None:
- _undelivered.setdefault(key, []).append(message)
+ _queue_notice(home, message)
return
try:
say(message)
@@ -1040,7 +1084,7 @@ def recover_at_startup(*, say: Optional[Callable[[str], None]] = None) -> list[s
logger.debug("left-core migration notification failed", exc_info=True)
if say is not None:
- for message in _undelivered.pop(key, []):
+ for message in _claim_notices(home):
deliver(message)
if key in _attempted:
return []
diff --git a/tests/hermes_cli/test_agent_import_left_core.py b/tests/hermes_cli/test_agent_import_left_core.py
index 0f452f0c1f7..ff915b3d80d 100644
--- a/tests/hermes_cli/test_agent_import_left_core.py
+++ b/tests/hermes_cli/test_agent_import_left_core.py
@@ -17,7 +17,6 @@ import hermes_cli.left_core_migration as lcm
@pytest.fixture(autouse=True)
def _fresh(monkeypatch):
monkeypatch.setattr(lcm, "_attempted", set())
- monkeypatch.setattr(lcm, "_undelivered", {})
import hermes_cli.memory_provider_migration as mpm
monkeypatch.setattr(mpm, "catalog_source", lambda name: name)
diff --git a/tests/hermes_cli/test_config_migration_52_browser.py b/tests/hermes_cli/test_config_migration_52_browser.py
index b0883b8533f..8641f0c4577 100644
--- a/tests/hermes_cli/test_config_migration_52_browser.py
+++ b/tests/hermes_cli/test_config_migration_52_browser.py
@@ -85,7 +85,6 @@ def test_boot_migration_shows_the_off_notice_at_the_first_agent_start_once(tmp_p
agent's startup warnings once, and neither a second agent nor the next boot repeats it."""
import hermes_cli.left_core_migration as lcm
- monkeypatch.setattr(lcm, "_undelivered", {})
monkeypatch.delenv("CAMOFOX_URL", raising=False)
home = _home(tmp_path / "a", {"_config_version": 51, "browser": {"backend": "off"}})
said = _boot_agents(home, monkeypatch, starts=2)
@@ -194,7 +193,6 @@ def test_a_pinned_relative_profile_names_the_absolute_path_on_update_and_boot(tm
in: `hermes update` and the first agent after a boot migration both name the absolute path pinned."""
import hermes_cli.left_core_migration as lcm
- monkeypatch.setattr(lcm, "_undelivered", {})
monkeypatch.delenv("CAMOFOX_URL", raising=False)
cwd = tmp_path / "work"
cwd.mkdir()
diff --git a/tests/hermes_cli/test_left_core_camofox.py b/tests/hermes_cli/test_left_core_camofox.py
index 6ecc0eafd9b..bfb157f45f2 100644
--- a/tests/hermes_cli/test_left_core_camofox.py
+++ b/tests/hermes_cli/test_left_core_camofox.py
@@ -35,7 +35,6 @@ capabilities:
@pytest.fixture(autouse=True)
def _fresh(monkeypatch, tmp_path):
monkeypatch.setattr(lcm, "_attempted", set())
- monkeypatch.setattr(lcm, "_undelivered", {})
for name in ("CAMOFOX_URL", "BROWSER_CDP_URL"):
monkeypatch.delenv(name, raising=False)
managed = tmp_path / "managed"
diff --git a/tests/hermes_cli/test_left_core_migration.py b/tests/hermes_cli/test_left_core_migration.py
index 2e16714b3c7..189e71d7054 100644
--- a/tests/hermes_cli/test_left_core_migration.py
+++ b/tests/hermes_cli/test_left_core_migration.py
@@ -16,7 +16,6 @@ import hermes_cli.left_core_migration as lcm
@pytest.fixture(autouse=True)
def _fresh(monkeypatch):
monkeypatch.setattr(lcm, "_attempted", set())
- monkeypatch.setattr(lcm, "_undelivered", {})
monkeypatch.delenv("HASS_TOKEN", raising=False)
# A catalog that lists every left-core plugin; never the network.
import hermes_cli.memory_provider_migration as mpm
diff --git a/tests/hermes_cli/test_left_core_provider_rows.py b/tests/hermes_cli/test_left_core_provider_rows.py
index acc5bd9bc77..da2669d63e0 100644
--- a/tests/hermes_cli/test_left_core_provider_rows.py
+++ b/tests/hermes_cli/test_left_core_provider_rows.py
@@ -25,7 +25,6 @@ ACME = lcm.LeftCoreFeature(
@pytest.fixture(autouse=True)
def _fresh(monkeypatch):
monkeypatch.setattr(lcm, "_attempted", set())
- monkeypatch.setattr(lcm, "_undelivered", {})
for name in ("HERMES_INFERENCE_PROVIDER", "COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN", "ACME_CLI_PATH"):
monkeypatch.delenv(name, raising=False)
import hermes_cli.memory_provider_migration as mpm
@@ -198,7 +197,7 @@ def test_runtime_resolution_installs_the_plugin_first_for_a_home_using_it(acme_r
calls = []
monkeypatch.setattr(lcm, "recover_at_startup", lambda **kw: calls.append(kw) or [])
lcm.recover_for_provider("acme")
- assert calls == [{}]
+ assert len(calls) == 1
lcm.recover_for_provider("openrouter")
(acme_row / "config.yaml").write_text("model:\n provider: nous\n", encoding="utf-8")
lcm.recover_for_provider("acme") # requested, but this home never chose it: no install
diff --git a/tests/hermes_cli/test_left_core_provider_runtime.py b/tests/hermes_cli/test_left_core_provider_runtime.py
index 31f34d40e91..619d4425edc 100644
--- a/tests/hermes_cli/test_left_core_provider_runtime.py
+++ b/tests/hermes_cli/test_left_core_provider_runtime.py
@@ -17,7 +17,6 @@ import hermes_cli.left_core_migration as lcm
@pytest.fixture(autouse=True)
def _fresh(monkeypatch):
monkeypatch.setattr(lcm, "_attempted", set())
- monkeypatch.setattr(lcm, "_undelivered", {})
for name in ("HERMES_INFERENCE_PROVIDER", "COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"):
monkeypatch.delenv(name, raising=False)
import hermes_cli.memory_provider_migration as mpm
@@ -116,3 +115,55 @@ def test_doctor_installs_nothing_and_names_the_install(tmp_path, monkeypatch, in
assert installs == []
assert not (home / "plugins" / "github-copilot").exists()
assert "hermes plugins install github-copilot" in capsys.readouterr().out
+
+
+def installs_ok(monkeypatch):
+ calls = []
+
+ def fake_install(identifier, *, force, enable, catalog_name=None, assume_deps_consent=None, **kw):
+ from hermes_constants import get_hermes_home
+ calls.append(catalog_name)
+ (Path(get_hermes_home()) / "plugins" / catalog_name).mkdir(parents=True)
+ return {"ok": True}
+ import hermes_cli.plugins_cmd as pc
+ monkeypatch.setattr(pc, "dashboard_install_plugin", fake_install)
+ monkeypatch.delenv("HERMES_DISABLE_LAZY_INSTALLS", raising=False)
+ return calls
+
+
+def _agent_start_in_another_process() -> str:
+ """What a fresh process's agent start (its startup-warning sink) delivers for ``HERMES_HOME``."""
+ import os
+ import subprocess
+ import sys
+ code = ("import hermes_cli.left_core_migration as m; "
+ "m.recover_at_startup(say=lambda message: print('NOTICE', message))")
+ root = Path(__file__).resolve().parents[2]
+ out = subprocess.run([sys.executable, "-c", code], cwd=root, env={**os.environ, "PYTHONPATH": str(root)},
+ capture_output=True, text=True, timeout=120, check=True)
+ return "".join(line for line in out.stdout.splitlines(keepends=True) if line.startswith("NOTICE"))
+
+
+def test_a_resolution_outcome_reaches_the_first_agent_of_any_process_once(tmp_path, monkeypatch, installs_ok,
+ capsys):
+ """A detached turn: the CLI process resolves the provider (and installs), the agent runs in another
+ process. The outcome is kept in the home and the first agent anywhere delivers it, exactly once."""
+ _copilot_home(tmp_path, monkeypatch)
+ monkeypatch.setattr(lcm, "_interactive", lambda: False)
+ lcm.recover_for_provider("copilot") # process 1: no agent here
+ assert installs_ok == ["github-copilot"]
+ assert capsys.readouterr().err == ""
+ first, second = _agent_start_in_another_process(), _agent_start_in_another_process()
+ assert first.count("GitHub Copilot moved out of core") == 1
+ assert "run `hermes auth add copilot`" in first # no token the plugin reads: the gh-only hint rides along
+ assert "moved out of core" not in second
+
+
+def test_an_interactive_terminal_sees_the_resolution_outcome_now_and_only_there(tmp_path, monkeypatch, installs_ok,
+ capsys):
+ _copilot_home(tmp_path, monkeypatch)
+ monkeypatch.setattr(lcm, "_interactive", lambda: True)
+ lcm.recover_for_provider("copilot")
+ assert capsys.readouterr().err.count("GitHub Copilot moved out of core") == 1
+ assert "moved out of core" not in _agent_start_in_another_process()
diff --git a/tests/hermes_cli/test_left_core_singularity.py b/tests/hermes_cli/test_left_core_singularity.py
index 457498c43ff..d3a5c383757 100644
--- a/tests/hermes_cli/test_left_core_singularity.py
+++ b/tests/hermes_cli/test_left_core_singularity.py
@@ -17,7 +17,6 @@ import hermes_cli.left_core_migration as lcm
@pytest.fixture(autouse=True)
def _fresh(monkeypatch, tmp_path):
monkeypatch.setattr(lcm, "_attempted", set())
- monkeypatch.setattr(lcm, "_undelivered", {})
monkeypatch.delenv("TERMINAL_ENV", raising=False)
managed = tmp_path / "managed"
managed.mkdir()