The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): preserve configured context cwd on desktop compaction
JoaoMarcos44c6f964f6d4b0
diff --git a/agent/context_file_sources.py b/agent/context_file_sources.pyindex b4deb7b4101..1b784652c6f 100644--- a/agent/context_file_sources.py+++ b/agent/context_file_sources.py@@ -104,7 +104,7 @@ def context_file_sources_for_agent(agent: Any) -> List[Dict[str, Any]]:from agent.runtime_cwd import resolve_context_cwdfrom agent.system_prompt import _agent_homelaunch_artifact = getattr(agent, "_context_cwd_is_launch_artifact", False)- cwd = None if launch_artifact else resolve_context_cwd()+ cwd = resolve_context_cwd(include_session_override=not launch_artifact)ctx_len = getattr(getattr(agent, "context_compressor", None), "context_length", None)return list_context_file_sources(cwd=str(cwd) if cwd is not None else None, context_length=ctx_len if isinstance(ctx_len, int) else None,diff --git a/agent/runtime_cwd.py b/agent/runtime_cwd.pyindex 21f32e2581b..a17044f7345 100644--- a/agent/runtime_cwd.py+++ b/agent/runtime_cwd.py@@ -81,18 +81,23 @@ def _existing_dir(raw: str, label: str) -> Path | None:return None-def _resolve_configured_cwd(*, override_is_final: bool) -> Path | None:+def _resolve_configured_cwd(+ *, override_is_final: bool, include_session_override: bool = True,+) -> Path | None:"""Session override, then TERMINAL_CWD; each validated as a real directory.``override_is_final``: a set-but-missing session override yields Noneinstead of falling through to TERMINAL_CWD.+ ``include_session_override``: skip a session cwd known to be a launch artifact+ while still consulting the active profile's TERMINAL_CWD."""- override = _SESSION_CWD.get()- override = "" if override is _UNSET else str(override).strip()- if override:- p = _existing_dir(override, "configured working directory")- if p is not None or override_is_final:- return p+ if include_session_override:+ override = _SESSION_CWD.get()+ override = "" if override is _UNSET else str(override).strip()+ if override:+ p = _existing_dir(override, "configured working directory")+ if p is not None or override_is_final:+ return praw = scope_terminal_cwd().strip()return _existing_dir(raw, "TERMINAL_CWD") if raw else None@@ -102,8 +107,14 @@ def resolve_agent_cwd() -> Path:return _resolve_configured_cwd(override_is_final=False) or Path(os.getcwd())-def resolve_context_cwd() -> Path | None:+def resolve_context_cwd(*, include_session_override: bool = True) -> Path | None:"""Configured cwd for context-file discovery, or None (build_context_files_prompt then falls back to thelaunch dir). An existing configured path is honored verbatim — including the Hermes source tree, a- legitimate workspace when developing Hermes; fallback-directory policy lives in the caller."""- return _resolve_configured_cwd(override_is_final=True)+ legitimate workspace when developing Hermes; fallback-directory policy lives in the caller.++ Launch-artifact callers can skip the session override while still honoring the active profile's+ TERMINAL_CWD.+ """+ return _resolve_configured_cwd(+ override_is_final=True, include_session_override=include_session_override,+ )diff --git a/agent/system_prompt.py b/agent/system_prompt.pyindex 3b2290e6d80..f8e7a3c789a 100644--- a/agent/system_prompt.py+++ b/agent/system_prompt.py@@ -714,13 +714,15 @@ def _context_files_part(agent: Any, ctx_len: Optional[int], soul_loaded: bool) -"""Project context files (AGENTS.md etc.) for the context tier. TERMINAL_CWDwhen set (gateway); None lets discovery fall back to the launch dir. Theinstall-tree fallback is only legitimate for cli/tui where the launch dir- IS the user's shell cwd; desktop-pinned launch dirs are treated as the- fallback they really are so the guard can reject Hermes's bundled AGENTS.md."""+ IS the user's shell cwd. Desktop launch artifacts skip the session cwd but+ still honor the profile-scoped TERMINAL_CWD; without one, the fallback guard+ can reject Hermes's bundled AGENTS.md."""if agent.skip_context_files:return []launch_artifact = getattr(agent, "_context_cwd_is_launch_artifact", False)+ cwd = resolve_context_cwd(include_session_override=not launch_artifact)return [_pb.build_context_files_prompt(- cwd=None if launch_artifact else resolve_context_cwd(), skip_soul=soul_loaded, context_length=ctx_len,+ cwd=cwd, skip_soul=soul_loaded, context_length=ctx_len,allow_install_tree_fallback=agent.platform in ("cli", "tui"), home_override=_agent_home(agent))]diff --git a/tests/agent/test_runtime_cwd.py b/tests/agent/test_runtime_cwd.pyindex 3c9f98a90f6..c463c2d707e 100644--- a/tests/agent/test_runtime_cwd.py+++ b/tests/agent/test_runtime_cwd.py@@ -64,6 +64,7 @@ class TestSessionCwdOverride:try:assert resolve_agent_cwd() == otherassert resolve_context_cwd() == other+ assert resolve_context_cwd(include_session_override=False) == tmp_pathfinally:rt._SESSION_CWD.reset(token)diff --git a/tests/agent/test_system_prompt.py b/tests/agent/test_system_prompt.pyindex d65583ce990..3b15d19c9fd 100644--- a/tests/agent/test_system_prompt.py+++ b/tests/agent/test_system_prompt.py@@ -153,12 +153,44 @@ class TestContextFileCwd:with (patch("agent.prompt_builder.load_soul_md", return_value=""),patch("agent.prompt_builder.build_environment_hints", return_value=""),- patch("agent.system_prompt.resolve_context_cwd", return_value=tmp_path),+ patch("agent.system_prompt.resolve_context_cwd", return_value=None),):context = build_system_prompt_parts(agent)["context"]assert "bundled contributor instructions" not in context+ def test_desktop_launch_artifact_uses_profile_configured_cwd(+ self, monkeypatch, tmp_path+ ):+ import agent.runtime_cwd as runtime_cwd++ launch = tmp_path / "launch"+ workspace = tmp_path / "workspace"+ launch.mkdir()+ workspace.mkdir()+ monkeypatch.setattr(runtime_cwd, "_PACKAGE_ROOT", launch.resolve())+ monkeypatch.chdir(launch)+ monkeypatch.setenv("TERMINAL_CWD", str(workspace))+ (launch / "AGENTS.md").write_text("bundled contributor instructions")+ (workspace / "AGENTS.md").write_text("operator workspace rules")++ token = runtime_cwd.set_session_cwd(str(launch))+ try:+ agent = _make_agent(+ platform="desktop",+ _context_cwd_is_launch_artifact=True,+ )+ with (+ patch("agent.prompt_builder.load_soul_md", return_value=""),+ patch("agent.prompt_builder.build_environment_hints", return_value=""),+ ):+ context = build_system_prompt_parts(agent)["context"]+ finally:+ runtime_cwd.reset_session_cwd(token)++ assert "operator workspace rules" in context+ assert "bundled contributor instructions" not in context+def test_desktop_explicit_install_tree_workspace_still_loads_agents_md(self, monkeypatch, tmp_path):diff --git a/tests/tools/test_multiplex_turn_parity.py b/tests/tools/test_multiplex_turn_parity.pyindex f10fec067b0..1d75f7ac0d6 100644--- a/tests/tools/test_multiplex_turn_parity.py+++ b/tests/tools/test_multiplex_turn_parity.py@@ -62,6 +62,28 @@ def test_routed_local_profile_cwd_matches_standalone_gateway(tmp_path, two_homesassert "TERMINAL_CWD" not in build_profile_terminal_scope(two_homes[1])+def test_launch_artifact_context_cwd_follows_routed_profile(two_homes, tmp_path):+ """Ignoring a Desktop launch cwd must still resolve terminal.cwd from the profile whose turn is active."""+ from agent.runtime_cwd import resolve_context_cwd, reset_session_cwd, set_session_cwd+ from tools.terminal_scope import install_and_reset_profile_terminal_scope++ a, b = two_homes+ workspaces = {"a": tmp_path / "workspace-a", "b": tmp_path / "workspace-b"}+ for name, home in (("a", a), ("b", b)):+ workspaces[name].mkdir()+ cfg = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8")) or {}+ cfg["terminal"] = {"backend": "local", "cwd": str(workspaces[name])}+ (home / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")++ token = set_session_cwd(str(tmp_path))+ try:+ for home, expected in ((a, workspaces["a"]), (b, workspaces["b"]), (a, workspaces["a"])):+ with install_and_reset_profile_terminal_scope(home):+ assert resolve_context_cwd(include_session_override=False) == expected+ finally:+ reset_session_cwd(token)++def test_terminal_backend_consumers_read_the_routed_scope(two_homes):"""Every ``TERMINAL_ENV`` reader that shapes a turn (image-source locality, credential-file pathtranslation, image-gen cache base, skill readiness) resolves the ROUTED profile's backend."""