fix(compat-fallout): module-restore also rebinds pkg.<child> attributes so 'from pkg import child' matches sys.modules after the wipe

This commit is contained in:
Teknium
2026-09-03 16:20:10 -07:00
parent 1bc3af0c05
commit eb2e96d657
2 changed files with 20 additions and 0 deletions
@@ -161,6 +161,13 @@ def agent_env():
# land on modules the app no longer imports.
sys.modules.clear()
sys.modules.update(saved_modules)
for _name, _mod in saved_modules.items():
_parent, _, _child = _name.rpartition(".")
if _parent and _parent in saved_modules:
try:
setattr(saved_modules[_parent], _child, _mod)
except Exception:
pass
if prev_home is None:
os.environ.pop("HERMES_HOME", None)
else:
@@ -27,8 +27,21 @@ def _restore_sys_modules():
the app no longer imports."""
saved = dict(sys.modules)
yield
_restore_modules(saved)
def _restore_modules(saved):
sys.modules.clear()
sys.modules.update(saved)
# Re-imports rebound ``pkg.<child>`` attributes to the fresh module objects; point them
# back so ``from pkg import child`` and ``sys.modules["pkg.child"]`` agree again.
for name, mod in saved.items():
parent, _, child = name.rpartition(".")
if parent and parent in saved:
try:
setattr(saved[parent], child, mod)
except Exception:
pass
def _fresh_run_agent(hermes_home):