Skip to content

The agent that grows with you

fix(bootstrap): recover a deleted working directory before PM activation

ethernet0a2b653b47fa
diff --git a/hermes_bootstrap.py b/hermes_bootstrap.py
index 30d8ff3ded9..5e47162c45c 100644
--- a/hermes_bootstrap.py
+++ b/hermes_bootstrap.py
@@ -326,12 +326,20 @@ suppress_platform_ver_console()
# Every entry point imports this module before its dependency graph.
from pathlib import Path
+
+_root = Path(__file__).resolve().parent
+try:
+ os.getcwd()
+except FileNotFoundError:
+ # Reaped workspaces leave children in a deleted cwd. PM resolves relative
+ # import paths before the CLI's guards, so recover before any PM work.
+ os.chdir(_root)
+
from pm.environments import activate_dependencies
from hermes_cli._early_recovery import recover_if_needed
from hermes_cli._parser import command_argv
-_root = Path(__file__).resolve().parent
# Repair needs only stdlib. Do not activate the damaged tree to reach it.
_pm_repair = command_argv(sys.argv[1:])[:2] == ["pm", "repair"]
if not _pm_repair:
diff --git a/tests/hermes_cli/test_startup_fast_guards.py b/tests/hermes_cli/test_startup_fast_guards.py
index 106b582cec0..c66b4e9a094 100644
--- a/tests/hermes_cli/test_startup_fast_guards.py
+++ b/tests/hermes_cli/test_startup_fast_guards.py
@@ -71,6 +71,32 @@ def test_cli_starts_from_a_deleted_cwd(tmp_path):
assert "FileNotFoundError" not in result.stderr
[email protected]("remove_cwd", [False, True], ids=["live", "deleted"])
+def test_bootstrap_preserves_live_cwd_and_recovers_deleted_cwd(tmp_path, remove_cwd):
+ cwd = tmp_path / "workspace"
+ cwd.mkdir()
+ probe = (
+ "import os, sys\n"
+ "os.chdir(sys.argv[1])\n"
+ "if sys.argv[2] == 'deleted':\n"
+ " os.rmdir(sys.argv[1])\n"
+ "import hermes_bootstrap\n"
+ "print(os.getcwd())\n"
+ )
+ env = {**os.environ, "HERMES_HOME": str(tmp_path / ".hermes"),
+ "PYTHONPATH": str(REPO_ROOT)}
+ env.pop("HERMES_DEV", None)
+ result = subprocess.run(
+ [sys.executable, "-c", probe, str(cwd), "deleted" if remove_cwd else "live"],
+ stdin=subprocess.DEVNULL, capture_output=True, text=True,
+ timeout=60, cwd=REPO_ROOT, env=env,
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == str(REPO_ROOT if remove_cwd else cwd)
+ assert "Traceback" not in result.stderr
+
+
def test_startup_fast_import_weight():
"""Importing _startup_fast must not drag in any heavy module."""
probe = (