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
[mirror] openJiuwen-ai/jiuwenswarm#1717: fix(diff): include sub-agent file changes in parent session diff stats
d30029696cffc12001d68
diff --git a/jiuwenswarm/server/runtime/session/git_diff_status.py b/jiuwenswarm/server/runtime/session/git_diff_status.pyindex 48183bf6e4..afb659566c 100644--- a/jiuwenswarm/server/runtime/session/git_diff_status.py+++ b/jiuwenswarm/server/runtime/session/git_diff_status.py@@ -14,7 +14,7 @@ import reimport timefrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Any+from typing import Any, Callablefrom jiuwenswarm.server.runtime.session.project_git import GitError, GitOperationErrorfrom jiuwenswarm.server.utils.diff_service import get_diff_service@@ -291,7 +291,7 @@ def _convert_stats(raw_stats: dict[str, Any] | None) -> DiffStats:def get_session_extra_history_roots(session_id: str | None) -> list[str]:- """Return team/member/worktree roots recorded for file history monitoring."""+ """Return team/member/worktree/sub-agent roots for file history monitoring."""sid = str(session_id or "").strip()if not sid:return []@@ -343,8 +343,6 @@ def get_session_extra_history_roots(session_id: str | None) -> list[str]:try:path = Path(raw.strip()).expanduser()parts = path.parts- # 使用最后一次出现的位置,避免路径中 team_name 多次出现时- # 定位到错误的层级(深层路径更可能是实际 team 目录)。idx = -1for i in range(len(parts) - 1, -1, -1):if parts[i] == team_name:@@ -377,9 +375,44 @@ def get_session_extra_history_roots(session_id: str | None) -> list[str]:add_root(str(independent_member_workspace(member_name)))except Exception: # noqa: BLE001pass++ _discover_sub_agent_workspaces(sid, add_root)+return roots+def _discover_sub_agent_workspaces(session_id: str, add_root: Callable[[Any], None]) -> None:+ """Scan workspace/sub_agents for sub-agent dirs belonging to *session_id*.++ In single-agent mode the parent session has no ``team_name`` and no+ ``team_file_monitor_roots`` metadata, so the normal team-root inference+ in ``get_session_extra_history_roots`` produces nothing. Sub-agent+ workspaces live under ``<agent_workspace>/sub_agents/<sub_session_id>/``+ with ``sub_session_id = <session_id>_sub_<type>_<suffix>``. We enumerate+ matching directories here and add them as extra history roots so that+ ``_read_agent_history`` can pick up the sub-agent's ``.agent_history``+ entries.+ """+ from jiuwenswarm.common.utils import get_agent_workspace_dir++ sub_agents_dir = get_agent_workspace_dir() / "sub_agents"+ if not sub_agents_dir.is_dir():+ return+ prefix = f"{session_id}_sub_"+ try:+ children = list(sub_agents_dir.iterdir())+ except OSError:+ return+ for child in children:+ try:+ if not child.is_dir():+ continue+ except OSError:+ continue+ if child.name.startswith(prefix):+ add_root(str(child))++def _convert_hunks(raw_hunks: list[dict[str, Any]] | None) -> list[DiffHunk]:"""转换 camelCase hunk 列表 → snake_case DiffHunk 列表。"""if not raw_hunks or not isinstance(raw_hunks, list):diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.pyindex 5b0fc92ab5..330a14a2cd 100644--- a/jiuwenswarm/server/utils/diff_service.py+++ b/jiuwenswarm/server/utils/diff_service.py@@ -705,6 +705,10 @@ class DiffService:文件名约定: ``file_ops_{agent_id}_{session_id}.json``,其中 session_id始终是 ``.json`` 前的最后一段。使用 ``_{session_id}.json`` 后缀匹配替代子串匹配,避免短 session_id 误匹配其他 agent 的 file_ops 文件。++ 当 session_id 对应的是父会话时,也接受子 agent 会话(后缀形如+ ``_sub_{type}_{suffix}``)的 file_ops 文件,使 diff 统计能覆盖子 agent+ 的文件变更。"""if not name.startswith("file_ops_"):return False@@ -712,7 +716,15 @@ class DiffService:return Falseif not session_id:return not require_session- return name.endswith(f"_{session_id}.json")+ suffix = f"_{session_id}.json"+ if name.endswith(suffix):+ return True+ sub_marker = f"_{session_id}_sub_"+ marker_pos = name.find(sub_marker, len("file_ops_"))+ if marker_pos < 0:+ return False+ agent_id = name[len("file_ops_"):marker_pos]+ return bool(agent_id) and "_" not in agent_id@staticmethoddef _agent_history_dirs_for_roots(diff --git a/tests/unit_tests/server/test_turn_diff_history.py b/tests/unit_tests/server/test_turn_diff_history.pyindex 9de7fa65f9..0248027fa0 100644--- a/tests/unit_tests/server/test_turn_diff_history.py+++ b/tests/unit_tests/server/test_turn_diff_history.py@@ -1040,6 +1040,37 @@ def test_get_session_extra_history_roots_adds_spawned_member_workspaces(tmp_pathassert str(tmp_path / "independent" / "poet-song_workspace") in roots+def test_get_session_extra_history_roots_discovers_sub_agent_workspaces(tmp_path):+ """Single-agent mode (no team_name) should still find sub-agent dirs under workspace/sub_agents."""+ sub_agents_dir = tmp_path / "workspace" / "sub_agents"+ sub_agents_dir.mkdir(parents=True)+ (sub_agents_dir / "sess-1_sub_general-purpose_abc").mkdir()+ (sub_agents_dir / "sess-1_sub_general-purpose_def").mkdir()+ (sub_agents_dir / "sess-other_sub_general-purpose_xyz").mkdir()+ with (+ patch(+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",+ return_value={+ "team_name": "",+ "team_file_monitor_roots": None,+ },+ ),+ patch(+ "jiuwenswarm.common.utils.get_agent_workspace_dir",+ return_value=tmp_path / "workspace",+ ),+ ):+ from jiuwenswarm.server.runtime.session.git_diff_status import (+ get_session_extra_history_roots,+ )++ roots = get_session_extra_history_roots("sess-1")++ assert str(sub_agents_dir / "sess-1_sub_general-purpose_abc") in roots+ assert str(sub_agents_dir / "sess-1_sub_general-purpose_def") in roots+ assert str(sub_agents_dir / "sess-other_sub_general-purpose_xyz") not in roots++def test_is_valid_file_ops_file_uses_suffix_match():"""session_id 后缀匹配,避免子串误匹配其他 session 的 file_ops 文件。"""service = DiffService()@@ -1061,6 +1092,24 @@ def test_is_valid_file_ops_file_uses_suffix_match():assert service._is_valid_file_ops_file("file_ops_agent.json", None, require_session=False)+def test_is_valid_file_ops_file_matches_sub_agent_sessions():+ """父 session_id 也应匹配子 agent 会话的 file_ops 文件(后缀 _sub_{type}_{suffix})。"""+ service = DiffService()+ parent = "sess_19fa7d326c9_87aa9a3ff27a"+ sub_name = "file_ops_93eeae01a6bb439eb7e241a9c8d8d375_sess_19fa7d326c9_87aa9a3ff27a_sub_general-purpose_17a7bada.json"+ assert service._is_valid_file_ops_file(sub_name, parent)+ assert service._is_valid_file_ops_file(sub_name, parent, require_session=True)+ exact_name = "file_ops_jiuwenswarm_sess_19fa7d326c9_87aa9a3ff27a.json"+ assert service._is_valid_file_ops_file(exact_name, parent)+ other_parent = "sess_other"+ assert not service._is_valid_file_ops_file(sub_name, other_parent)+ assert not service._is_valid_file_ops_file("file_ops_agent_sess_10.json", "sess_1")+ spoofed = "file_ops_abc_sess-1_sub_def_sess-other.json"+ assert service._is_valid_file_ops_file(spoofed, "sess-1")+ empty_agent = "file_ops__sess-1_sub_general-purpose_abc.json"+ assert not service._is_valid_file_ops_file(empty_agent, "sess-1")++def test_multi_history_root_first_wins_for_duplicate_entries(tmp_path, monkeypatch):"""project_dir 的 file_ops 仅在重复 entry 冲突时优先。"""agent_ws = tmp_path / "agent-ws"