JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(team): constrain manual git worktree creation to project .worktrees dir
openJiuwen-botd36e7467038f
diff --git a/jiuwenswarm/agents/harness/common/tools/bash_tool_safety.py b/jiuwenswarm/agents/harness/common/tools/bash_tool_safety.pyindex ce3a116ba5..58738a7c29 100644--- a/jiuwenswarm/agents/harness/common/tools/bash_tool_safety.py+++ b/jiuwenswarm/agents/harness/common/tools/bash_tool_safety.py@@ -22,12 +22,16 @@ def _pre_execute_shell_command(command: str) -> str | None:from jiuwenswarm.agents.harness.common.tools.command_tools import (_check_command_safety,+ _check_worktree_path_safety,_enforce_tui_spawn_budget,)blocked = _check_command_safety(command)if blocked:return f"[ERROR]: command rejected for safety ({blocked})."+ worktree_block = _check_worktree_path_safety(command)+ if worktree_block:+ return f"[ERROR]: {worktree_block}"spawn_block = _enforce_tui_spawn_budget(command, resolve_shell_session_id() or "")if spawn_block:return f"[ERROR]: {spawn_block}"diff --git a/jiuwenswarm/agents/harness/common/tools/command_tools.py b/jiuwenswarm/agents/harness/common/tools/command_tools.pyindex 7b6bc11bf7..f26bf157b1 100644--- a/jiuwenswarm/agents/harness/common/tools/command_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/command_tools.py@@ -222,6 +222,97 @@ def _check_command_safety(command: str) -> str | None:return None+# Options of `git worktree add` that consume the following token as a value.+_WORKTREE_ADD_VALUE_OPTS = frozenset({"-b", "-B", "--branch", "--no-track"})++# Cheap prescreen: only commands mentioning `worktree add` are worth the full+# shlex parse. This runs on every bash command, so it must be O(regex) for the+# common (non-worktree) case.+_WORKTREE_ADD_PRESCREEN = re.compile(r"\bworktree\s+add\b", re.IGNORECASE)+++def _parse_worktree_add_target(command: str) -> str | None:+ """Return the target path token of a `git worktree add` command, else None.++ The target is the first non-option positional after `add`. Handles+ `-b <branch>` / `-B <branch>` / `--branch=<branch>` (value-bearing) and+ boolean options like `-f`/`--detach`/`--no-checkout`. Returns None if the+ command is not a worktree-add or no positional target is present.+ """+ if not _WORKTREE_ADD_PRESCREEN.search(command):+ return None+ try:+ tokens = shlex.split(command)+ except ValueError:+ return None+ # Find `worktree add` (allow a leading `git` and `sudo git` etc.).+ try:+ add_idx = _find_worktree_add_index(tokens)+ except ValueError:+ return None+ i = add_idx + 1+ while i < len(tokens):+ tok = tokens[i]+ if tok.startswith("--") and "=" in tok:+ i += 1+ continue+ if tok in _WORKTREE_ADD_VALUE_OPTS:+ i += 2 # skip opt + its value+ continue+ if tok.startswith("-"):+ i += 1 # boolean option+ continue+ return tok # first positional = worktree target path+ return None+++def _find_worktree_add_index(tokens: list[str]) -> int:+ """Return the index of the `add` token in a `... worktree add` chain.++ Matches the positional `worktree add` pair regardless of a leading+ `git`/`sudo` prefix. Raises ValueError if not found.+ """+ lowered = [t.lower() for t in tokens]+ for i in range(len(lowered) - 1):+ if lowered[i] == "worktree" and lowered[i + 1] == "add":+ return i + 1+ raise ValueError("not a git worktree add command")+++def _check_worktree_path_safety(command: str) -> str | None:+ """Block `git worktree add` whose target lands outside the project dir.++ team.code does not mount the `enter_worktree` tool, so the LLM may hand-run+ `git worktree add`. Without a constraint it tends to target the project's+ sibling directory (../). This refuses out-of-project targets and points the+ model at `.worktrees/<name>`. Self-gating: only triggers on a manual+ `git worktree add`; when the `enter_worktree` tool is mounted the LLM does+ not hand-run the command, so this never fires.+ """+ target = _parse_worktree_add_target(command)+ if target is None:+ return None+ try:+ project_root = _context_project_root()+ except Exception:+ return None # no project context → do not risk false positives+ try:+ target_path = Path(target)+ if not target_path.is_absolute():+ target_path = project_root / target_path+ target_path = target_path.resolve()+ except Exception:+ return None+ if _is_relative_to(target_path, project_root):+ return None # inside the project (e.g. .worktrees/<name>) → allow+ return (+ f"worktree target must live under the project dir at "+ f".worktrees/<name> (e.g. `git worktree add .worktrees/<name> "+ f"-b <branch> HEAD`); refused path outside the project: {target}. "+ f"Do NOT use `../` or sibling directories."+ )++def _context_cwd() -> Path:try:from openjiuwen.core.sys_operation.cwd import get_cwddiff --git a/tests/unit_tests/agents/test_command_safety.py b/tests/unit_tests/agents/test_command_safety.pyindex 84313c53eb..6125be0b06 100644--- a/tests/unit_tests/agents/test_command_safety.py+++ b/tests/unit_tests/agents/test_command_safety.py@@ -133,3 +133,90 @@ def test_enforce_tui_spawn_budget_global_bucket_for_empty_session() -> None:for _ in range(TUI_SPAWN_LIMIT):assert _enforce_tui_spawn_budget("jiuwenswarm-tui", "") is Noneassert _enforce_tui_spawn_budget("jiuwenswarm-tui", "") is not None+++# ── git worktree add 路径护栏 ────────────────────────────────++from jiuwenswarm.agents.harness.common.tools import command_tools # noqa: E402+++def _project_root(tmp_path, monkeypatch):+ """Pin the project root to a tmp dir so path bounds are deterministic."""+ root = tmp_path / "project"+ root.mkdir()+ monkeypatch.setattr(command_tools, "_context_project_root", lambda: root)+ return root+++def test_worktree_add_sibling_dir_blocked(_project_root) -> None:+ from jiuwenswarm.agents.harness.common.tools.command_tools import (+ _check_worktree_path_safety,+ )++ msg = _check_worktree_path_safety("git worktree add ../foo main")+ assert msg is not None+ assert ".worktrees/" in msg+ assert "../" in msg+++def test_worktree_add_outside_abs_path_blocked(_project_root) -> None:+ from jiuwenswarm.agents.harness.common.tools.command_tools import (+ _check_worktree_path_safety,+ )++ msg = _check_worktree_path_safety("git worktree add /tmp/outside-wt")+ assert msg is not None+ assert ".worktrees/" in msg+++def test_worktree_add_inside_dot_worktrees_allowed(_project_root) -> None:+ from jiuwenswarm.agents.harness.common.tools.command_tools import (+ _check_worktree_path_safety,+ )++ # Target under the project's .worktrees/ → inside project → allow.+ assert (+ _check_worktree_path_safety(+ "git worktree add -b feature-x .worktrees/feature-x HEAD"+ )+ is None+ )+ # Absolute path inside the project → allow.+ assert (+ _check_worktree_path_safety(+ f"git worktree add {_project_root / '.worktrees' / 'foo'}"+ )+ is None+ )+++def test_worktree_add_with_branch_value_correctly_skips_target(_project_root) -> None:+ """`-b <branch>` consumes the branch name; the next token is the path."""+ from jiuwenswarm.agents.harness.common.tools.command_tools import (+ _check_worktree_path_safety,+ )++ # `-b ../escape` would wrongly look like a path if -b didn't eat its value;+ # here the real target is .worktrees/x (inside) so it must be allowed.+ assert (+ _check_worktree_path_safety(+ "git worktree add -b ../escape .worktrees/x HEAD"+ )+ is None+ )+ # And the inverse: -b <name> then a sibling path → blocked.+ msg = _check_worktree_path_safety("git worktree add -b feature ../sibling")+ assert msg is not None+++def test_worktree_check_ignores_non_worktree_commands(_project_root) -> None:+ from jiuwenswarm.agents.harness.common.tools.command_tools import (+ _check_worktree_path_safety,+ )++ assert _check_worktree_path_safety("git status") is None+ assert _check_worktree_path_safety("git worktree list") is None+ assert _check_worktree_path_safety("ls -la ../somewhere") is None+ assert _check_worktree_path_safety("git branch feature-x") is None+diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.pyindex 4da2586a89..6a7be72699 100644--- a/tests/unit_tests/agentserver/test_team_helpers.py+++ b/tests/unit_tests/agentserver/test_team_helpers.py@@ -1404,9 +1404,7 @@ async def test_process_team_message_stream_routes_evolution_interrupt_to_active_{"answers": {"approve": True}},)- class _FakeManager:- active_session_id = "sess-team-evolution-resume"- pending_session_id = None+ class _FakeManager(_InactiveTeamRuntimeManagerMixin):interact_calls: list[tuple[str, Any]] = []@staticmethod