Skip to content

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

feat(aipc): Ignore JiuwenSwarm agent history in git diffs

kdgmpw1ba6c22814b5
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 13d14e7d2b..ecd81b35a0 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -548,6 +548,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
initial_workspace = self._project_dir or str(
get_default_project_session_workspace_dir()
)
+ self._ensure_project_gitignore_agent_history(initial_workspace)
self._seed_runtime_cwd(initial_workspace, workspace=initial_workspace)
setattr(self._instance, "_jiuwenswarm_adapter_mode", "code")
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index a880a1b495..7b2ad1b345 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -4475,6 +4475,7 @@ class JiuWenSwarmDeepAdapter:
initial_runtime_workspace = self._project_dir or str(
get_default_project_session_workspace_dir()
)
+ self._ensure_project_gitignore_agent_history(initial_runtime_workspace)
self._seed_runtime_cwd(initial_runtime_workspace, workspace=initial_runtime_workspace)
setattr(self._instance, "_jiuwenswarm_project_dir", initial_runtime_workspace)
@@ -4492,6 +4493,86 @@ class JiuWenSwarmDeepAdapter:
# 动态加载用户自定义的 Rail 扩展
await self.load_user_rails()
+ @staticmethod
+ def _ensure_project_gitignore_agent_history(project_dir: str | None) -> None:
+ """Ensure JiuwenSwarm's file operation logs stay out of project git diffs."""
+ if not project_dir:
+ return
+ try:
+ repo_probe = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ cwd=project_dir,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return
+ if repo_probe.returncode != 0:
+ return
+
+ repo_root_text = repo_probe.stdout.strip()
+ if not repo_root_text:
+ return
+ gitignore_path = Path(repo_root_text) / ".gitignore"
+ try:
+ existing_bytes = gitignore_path.read_bytes() if gitignore_path.exists() else b""
+ except OSError as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] read .gitignore for agent history rule failed: %s",
+ exc,
+ )
+ return
+
+ if JiuWenSwarmDeepAdapter._gitignore_covers_agent_history(existing_bytes):
+ return
+
+ existing = existing_bytes.decode("utf-8", errors="replace")
+ prefix = "" if not existing else ("\n" if existing.endswith(("\n", "\r")) else "\n\n")
+ addition = (
+ f"{prefix}# JiuwenSwarm runtime file operation logs\n.agent_history/\n"
+ ).encode("utf-8")
+ try:
+ gitignore_path.write_bytes(existing_bytes + addition)
+ except OSError as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] ensure .agent_history gitignore failed: %s",
+ exc,
+ )
+
+ @staticmethod
+ def _gitignore_covers_agent_history(content: bytes) -> bool:
+ """Return True if .gitignore content already ignores .agent_history/.
+
+ Recognizes equivalent forms such as ``.agent_history``,
+ ``.agent_history/``, ``.agent_history/*``, ``.agent_history/**``,
+ ``.agent_history/**/*``, ``**/.agent_history`` and combinations
+ thereof, so that the rule is idempotent across pre-existing project
+ configurations.
+ """
+ text = content.decode("utf-8", errors="replace")
+ for raw_line in text.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
+ # Skip negation rules; they re-include paths rather than ignore
+ # the directory.
+ if line.startswith("!"):
+ continue
+ # Strip leading glob prefix like `**/`.
+ if line.startswith("**/"):
+ line = line[3:]
+ # Split into segments. The rule covers `.agent_history` if the
+ # first segment matches and any following segments are wildcards
+ # that target the directory contents.
+ segments = [seg for seg in line.split("/") if seg]
+ if not segments or segments[0] != ".agent_history":
+ continue
+ if all(seg in ("*", "**") for seg in segments[1:]):
+ return True
+ return False
+
async def _sync_prompt_attachments_for_request(self, session_id: str) -> None:
"""Hot-load prompt attachment files for the current request.
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index 440649a291..9a95d21007 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -20,6 +20,8 @@ from jiuwenswarm.server.runtime.session.session_history import load_history_reco
logger = logging.getLogger(__name__)
+INTERNAL_UNTRACKED_DIRS = {".agent_history"}
+
MAX_FILES = 50
MAX_DIFF_SIZE_BYTES = 1_000_000
@@ -1433,6 +1435,8 @@ class DiffService:
if not rel_path:
continue
rel_path = DiffService._unquote_git_path(rel_path)
+ if self._is_internal_untracked_path(rel_path):
+ continue
abs_path = str(Path(project_dir) / rel_path)
entry: dict[str, Any] = {
@@ -1495,6 +1499,11 @@ class DiffService:
return files
+ @staticmethod
+ def _is_internal_untracked_path(rel_path: str) -> bool:
+ parts = Path(rel_path).parts
+ return any(part in INTERNAL_UNTRACKED_DIRS for part in parts)
+
def get_git_diff(self, project_dir: str | None) -> dict[str, Any] | None:
"""获取工作区相对于 HEAD 的 git diff,含未跟踪文件行数.
diff --git a/tests/unit_tests/server/test_agent_history_gitignore.py b/tests/unit_tests/server/test_agent_history_gitignore.py
new file mode 100644
index 0000000000..49628ed2fd
--- /dev/null
+++ b/tests/unit_tests/server/test_agent_history_gitignore.py
@@ -0,0 +1,107 @@
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+from jiuwenswarm.server.utils.diff_service import DiffService
+
+
+def _git(repo: Path, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True)
+
+
+def test_ensure_project_gitignore_agent_history_updates_repo_root(tmp_path):
+ repo = tmp_path / "repo"
+ subdir = repo / "pkg"
+ subdir.mkdir(parents=True)
+ _git(repo, "init")
+
+ JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(subdir))
+ JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(subdir))
+
+ gitignore = repo / ".gitignore"
+ assert gitignore.exists()
+ content = gitignore.read_text(encoding="utf-8")
+ assert content.count(".agent_history/") == 1
+
+
+ "existing_rule",
+ [
+ ".agent_history",
+ ".agent_history/",
+ ".agent_history/*",
+ ".agent_history/**",
+ ".agent_history/**/*",
+ "**/.agent_history",
+ "**/.agent_history/",
+ "**/.agent_history/*",
+ ],
+)
+def test_ensure_project_gitignore_agent_history_idempotent_for_equivalent_rules(
+ tmp_path, existing_rule
+):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init")
+
+ gitignore = repo / ".gitignore"
+ gitignore.write_text(f"build/\n{existing_rule}\n", encoding="utf-8")
+
+ before = gitignore.read_bytes()
+
+ JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(repo))
+ JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(repo))
+
+ after = gitignore.read_bytes()
+ assert before == after, (
+ f".gitignore should remain unchanged for equivalent rule {existing_rule!r}"
+ )
+
+
+def test_ensure_project_gitignore_agent_history_preserves_crlf(tmp_path):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init")
+
+ gitignore = repo / ".gitignore"
+ original = b"build/\r\ndist/\r\n"
+ gitignore.write_bytes(original)
+
+ JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(repo))
+
+ after = gitignore.read_bytes()
+ # Original CRLF lines must be preserved verbatim.
+ assert after.startswith(original)
+ # Appended rule uses LF (consistent with the rest of the addition) and is
+ # separated from existing content by exactly one blank line.
+ assert after.endswith(b"# JiuwenSwarm runtime file operation logs\n.agent_history/\n")
+ assert after.count(b".agent_history/") == 1
+
+
+def test_git_diff_excludes_unignored_agent_history(tmp_path):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "Test User")
+
+ tracked = repo / "tracked.txt"
+ tracked.write_text("before\n", encoding="utf-8")
+ _git(repo, "add", "tracked.txt")
+ _git(repo, "commit", "-m", "initial")
+
+ tracked.write_text("after\n", encoding="utf-8")
+ history_dir = repo / ".agent_history"
+ history_dir.mkdir()
+ (history_dir / "file_ops_jiuwenswarm_sess.json").write_text(
+ "{\n \"file.txt\": []\n}\n",
+ encoding="utf-8",
+ )
+
+ diff = DiffService().get_git_diff(str(repo))
+
+ assert diff is not None
+ assert diff["stats"] == {"filesChanged": 1, "linesAdded": 1, "linesRemoved": 1}
+ assert str(history_dir / "file_ops_jiuwenswarm_sess.json") not in diff["files"]