hermes-agent/tests/tools/test_terminal_task_cwd.py
ethernet c80b244b52 refactor(terminal,file-tools): delete legacy env-side cwd tracking (step 4)
The per-session record store is now the ONLY cwd mechanism. Deleted:

- env.cwd_owner stamping + prev_owner threading (terminal_tool): the
  shared env no longer carries ownership metadata at all
- _resolve_command_cwd's env/prev_owner params: resolution is
  workdir > session record > config/override default
- file_tools._live_cwd_if_owned + _get_live_tracking_cwd: path
  resolution never consults the shared env's live cwd
- file_tools._last_known_cwd + _remember_last_known_cwd +
  _last_known_cwd_for: the #26211 preserved-anchor registry is
  subsumed by the session record, which never lived on the env and
  therefore cannot be lost to env cleanup. The _get_file_ops
  stale-cache rescue now writes the record instead.
- env recreation (both _get_file_ops and terminal_tool) seeds the
  fresh env from override > session record > config

Why no transition fallback: the legacy state was process-local and
in-memory exactly like the record store — after a restart both start
empty, and within a running process every legacy write site has been
dual-writing the record since step 1. There is no populated-legacy/
empty-record state to fall back for.

Tests updated to drive the record store instead of the deleted
mechanism; the cross-session isolation suite now asserts the same
behavior contracts (no leak, cd isolation, #26211 persistence)
against the new architecture, plus a new "session C inherits nothing"
case that the old ownership guard could not express.
2026-07-16 00:18:38 -07:00

335 lines
13 KiB
Python

"""Regression tests for task/session cwd propagation in terminal_tool."""
import json
from types import SimpleNamespace
import tools.terminal_tool as terminal_tool
def _minimal_terminal_config(cwd="/default"):
return {
"env_type": "local",
"cwd": cwd,
"timeout": 60,
"lifetime_seconds": 3600,
}
def test_foreground_command_uses_registered_task_cwd_for_existing_environment(monkeypatch):
"""ACP can update task cwd after the local env exists; foreground must honor it."""
calls = []
class FakeEnv:
env = {}
def execute(self, command, **kwargs):
calls.append((command, kwargs))
return {"output": "ok", "returncode": 0}
task_id = "acp-session-1"
monkeypatch.setattr(terminal_tool, "_active_environments", {task_id: FakeEnv()})
monkeypatch.setattr(terminal_tool, "_last_activity", {})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {task_id: {"cwd": "/workspace/acp"}})
monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: _minimal_terminal_config())
monkeypatch.setattr(
terminal_tool,
"_check_all_guards",
lambda command, env_type, **kwargs: {"approved": True},
)
result = json.loads(terminal_tool.terminal_tool(command="pwd", task_id=task_id))
assert result["exit_code"] == 0
assert calls == [("pwd", {"timeout": 60, "cwd": "/workspace/acp", "bounded_capture": True})]
def test_explicit_workdir_still_wins_over_registered_task_cwd(monkeypatch):
calls = []
class FakeEnv:
env = {}
def execute(self, command, **kwargs):
calls.append(kwargs)
return {"output": "ok", "returncode": 0}
task_id = "acp-session-1"
monkeypatch.setattr(terminal_tool, "_active_environments", {task_id: FakeEnv()})
monkeypatch.setattr(terminal_tool, "_last_activity", {})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {task_id: {"cwd": "/workspace/acp"}})
monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: _minimal_terminal_config())
monkeypatch.setattr(
terminal_tool,
"_check_all_guards",
lambda command, env_type, **kwargs: {"approved": True},
)
result = json.loads(
terminal_tool.terminal_tool(
command="pwd",
task_id=task_id,
workdir="/explicit/workdir",
)
)
assert result["exit_code"] == 0
assert calls == [{"timeout": 60, "cwd": "/explicit/workdir", "bounded_capture": True}]
def test_foreground_command_prefers_recorded_session_cwd_over_init_time_cwd(monkeypatch):
"""A prior `cd` records the session cwd; terminal_tool must honor it."""
calls = []
class FakeEnv:
env = {}
cwd = "/workspace/live"
def execute(self, command, **kwargs):
calls.append((command, kwargs))
return {"output": "ok", "returncode": 0}
task_id = "session-live-cwd"
monkeypatch.setattr(terminal_tool, "_active_environments", {task_id: FakeEnv()})
monkeypatch.setattr(terminal_tool, "_last_activity", {})
monkeypatch.setattr(terminal_tool, "_session_cwd", {})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {task_id: {"cwd": "/workspace/init"}})
monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: _minimal_terminal_config(cwd="/workspace/init"))
monkeypatch.setattr(terminal_tool, "_start_cleanup_thread", lambda: None)
monkeypatch.setattr(terminal_tool, "_resolve_container_task_id", lambda value: value or "default")
monkeypatch.setattr(
terminal_tool,
"_check_all_guards",
lambda command, env_type, **kwargs: {"approved": True},
)
# The prior command's completed `cd` recorded the session cwd.
terminal_tool.record_session_cwd(task_id, "/workspace/live")
result = json.loads(terminal_tool.terminal_tool(command="pwd", task_id=task_id))
assert result["exit_code"] == 0
assert calls == [("pwd", {"timeout": 60, "cwd": "/workspace/live", "bounded_capture": True})]
def test_background_command_prefers_recorded_session_cwd_over_init_time_cwd(monkeypatch):
"""Background process launches must also use the recorded session cwd."""
class FakeEnv:
env = {}
cwd = "/workspace/live"
class FakeRegistry:
def __init__(self):
self.calls = []
self.pending_watchers = []
def spawn_local(self, **kwargs):
self.calls.append(kwargs)
return SimpleNamespace(id="proc_test", pid=1234)
import tools.process_registry as process_registry_mod
registry = FakeRegistry()
task_id = "session-live-cwd-bg"
monkeypatch.setattr(terminal_tool, "_active_environments", {task_id: FakeEnv()})
monkeypatch.setattr(terminal_tool, "_last_activity", {})
monkeypatch.setattr(terminal_tool, "_session_cwd", {})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {task_id: {"cwd": "/workspace/init"}})
monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: _minimal_terminal_config(cwd="/workspace/init"))
monkeypatch.setattr(terminal_tool, "_start_cleanup_thread", lambda: None)
monkeypatch.setattr(terminal_tool, "_resolve_container_task_id", lambda value: value or "default")
monkeypatch.setattr(
terminal_tool,
"_check_all_guards",
lambda command, env_type, **kwargs: {"approved": True},
)
monkeypatch.setattr(process_registry_mod, "process_registry", registry)
terminal_tool.record_session_cwd(task_id, "/workspace/live")
result = json.loads(
terminal_tool.terminal_tool(
command="sleep 1",
task_id=task_id,
background=True,
)
)
assert result["exit_code"] == 0
# session_key falls back to the raw task_id when no gateway contextvar is set
# (it doesn't propagate to tool-worker threads), so process.kill / stop can
# still find and terminate this background process.
assert registry.calls == [{
"command": "sleep 1",
"cwd": "/workspace/live",
"task_id": task_id,
"session_key": task_id,
"env_vars": {},
"use_pty": False,
}]
def test_registering_cwd_override_updates_session_record(monkeypatch):
"""An ACP ``update_cwd`` (re-)registered mid-session must win over a
previously ``cd``-ed session cwd.
Registration writes the session record directly, so an explicit ACP
project-root change takes effect on the next command, as the editor
client expects.
"""
class FakeEnv:
env = {}
cwd = "/workspace/old"
task_id = "acp-session-update"
fake_env = FakeEnv()
monkeypatch.setattr(terminal_tool, "_active_environments", {task_id: fake_env})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})
monkeypatch.setattr(terminal_tool, "_session_cwd", {})
# The session had cd'd somewhere before the editor switched project roots.
terminal_tool.record_session_cwd(task_id, "/workspace/old")
terminal_tool.register_task_env_overrides(task_id, {"cwd": "/workspace/new"})
# The live env mirror still updates (legacy env seeding) …
assert fake_env.cwd == "/workspace/new"
# … and the session record — what commands actually resolve against — too.
assert terminal_tool.get_session_cwd(task_id) == "/workspace/new"
assert terminal_tool._resolve_command_cwd(
workdir=None, default_cwd="/workspace/config", session_key=task_id
) == "/workspace/new"
def test_registering_cwd_override_noop_when_no_live_env(monkeypatch):
"""Registering an override before the env exists must not crash; the cwd
is applied at env creation time instead."""
monkeypatch.setattr(terminal_tool, "_active_environments", {})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})
# Should not raise even though no env is cached yet.
terminal_tool.register_task_env_overrides("acp-session-pending", {"cwd": "/workspace/new"})
assert terminal_tool._task_env_overrides["acp-session-pending"] == {"cwd": "/workspace/new"}
def test_registering_non_cwd_override_leaves_live_env_cwd_untouched(monkeypatch):
"""A non-cwd override (e.g. a per-task Modal image) must not disturb the
live env's cwd."""
class FakeEnv:
env = {}
cwd = "/workspace/keep"
task_id = "rl-rollout-1"
fake_env = FakeEnv()
monkeypatch.setattr(terminal_tool, "_active_environments", {task_id: fake_env})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})
terminal_tool.register_task_env_overrides(task_id, {"modal_image": "custom:latest"})
assert fake_env.cwd == "/workspace/keep"
def test_stale_env_cwd_from_different_session_is_ignored(monkeypatch):
"""A different session's `cd` left env.cwd pointing at its checkout.
The terminal env is shared (collapsed to "default"), so env.cwd tracks the
LAST session that ran a command. When session B claims the env after
session A left it in A's worktree, the first command must NOT run in A's
leftover cwd — it must fall through to the config/override cwd (this
session's own workspace).
"""
calls = []
class FakeEnv:
env = {}
cwd = "/home/user/src/hermes-desktop-tipc/apps/desktop"
cwd_owner = "session-A-key"
def execute(self, command, **kwargs):
calls.append((command, kwargs))
return {"output": "ok", "returncode": 0}
task_id = "session-B"
monkeypatch.setattr(terminal_tool, "_active_environments", {"default": FakeEnv()})
monkeypatch.setattr(terminal_tool, "_last_activity", {})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})
monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: _minimal_terminal_config(cwd="/home/user/src/hermes-agent"))
monkeypatch.setattr(terminal_tool, "_start_cleanup_thread", lambda: None)
monkeypatch.setattr(terminal_tool, "_resolve_container_task_id", lambda value: "default")
monkeypatch.setattr(
terminal_tool,
"_check_all_guards",
lambda command, env_type, **kwargs: {"approved": True},
)
result = json.loads(terminal_tool.terminal_tool(command="pwd", task_id=task_id))
assert result["exit_code"] == 0
# The command must run in the config cwd (hermes-agent), NOT the stale
# env.cwd left by session A (hermes-desktop-tipc).
assert calls == [("pwd", {"timeout": 60, "cwd": "/home/user/src/hermes-agent", "bounded_capture": True})]
def test_same_session_recorded_cwd_survives_across_commands(monkeypatch):
"""In-session `cd` state survives: the record written by one command is
used by the next command in the same session."""
calls = []
class FakeEnv:
env = {}
cwd = "/workspace/deep"
def execute(self, command, **kwargs):
calls.append((command, kwargs))
return {"output": "ok", "returncode": 0}
env = FakeEnv()
task_id = "session-X"
monkeypatch.setattr(terminal_tool, "_active_environments", {"default": env})
monkeypatch.setattr(terminal_tool, "_last_activity", {})
monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})
monkeypatch.setattr(terminal_tool, "_session_cwd", {})
monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: _minimal_terminal_config(cwd="/workspace/config"))
monkeypatch.setattr(terminal_tool, "_start_cleanup_thread", lambda: None)
monkeypatch.setattr(terminal_tool, "_resolve_container_task_id", lambda value: "default")
monkeypatch.setattr(
terminal_tool,
"_check_all_guards",
lambda command, env_type, **kwargs: {"approved": True},
)
# First command runs in the config cwd (no record yet) and afterwards
# mirrors the env's post-command cwd into the session record.
result = json.loads(terminal_tool.terminal_tool(command="pwd", task_id=task_id))
assert result["exit_code"] == 0
assert calls[0] == ("pwd", {"timeout": 60, "cwd": "/workspace/config", "bounded_capture": True})
assert terminal_tool.get_session_cwd(task_id) == "/workspace/deep"
# Second command in the same session trusts the record.
result = json.loads(terminal_tool.terminal_tool(command="pwd", task_id=task_id))
assert result["exit_code"] == 0
assert calls[1] == ("pwd", {"timeout": 60, "cwd": "/workspace/deep", "bounded_capture": True})
def test_safe_getcwd_returns_real_cwd(monkeypatch):
monkeypatch.setattr(terminal_tool.os, "getcwd", lambda: "/home/user/project")
assert terminal_tool._safe_getcwd() == "/home/user/project"
def test_safe_getcwd_falls_back_to_terminal_cwd_when_cwd_deleted(monkeypatch):
def _boom():
raise FileNotFoundError("[Errno 2] No such file or directory")
monkeypatch.setattr(terminal_tool.os, "getcwd", _boom)
monkeypatch.setenv("TERMINAL_CWD", "/srv/work")
assert terminal_tool._safe_getcwd() == "/srv/work"
def test_safe_getcwd_falls_back_to_home_when_no_terminal_cwd(monkeypatch):
def _boom():
raise FileNotFoundError()
monkeypatch.setattr(terminal_tool.os, "getcwd", _boom)
monkeypatch.delenv("TERMINAL_CWD", raising=False)
monkeypatch.setattr(terminal_tool.os.path, "expanduser", lambda p: "/home/me")
assert terminal_tool._safe_getcwd() == "/home/me"