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(server): re-take the git snapshot when the checkout moves
alan_chenge907fa4b0433
diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex 77699d3051..cbf35f1d44 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -447,7 +447,9 @@ class RuntimePromptRail(DeepAgentRail):git_lines = ["This is the git status at the start of the conversation. "- "Note that this status is a snapshot in time, and will not update during the conversation.",+ "Note that this status is a snapshot in time, and will not update during the conversation. "+ "Run git yourself when you need the current state — for example before staging or "+ "committing, or after anything may have changed the working tree.",f"Current branch: {git_branch}",]if git_main_branch:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 322f12cf91..90ebd87690 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -493,16 +493,45 @@ class _GitSnapshot:"""Git state as of a conversation's first turn, held for its whole life.Attributes:+ head: Raw ``HEAD`` file contents when the snapshot was taken. Checking+ it costs a file read rather than a subprocess, which is what makes+ it affordable to verify on every turn.branch: Current branch name, or "HEAD" when detached.status: ``git status --short`` output, capped at 50 lines.recent_commits: ``git log --oneline -5`` output."""+ head: strbranch: strstatus: strrecent_commits: str+def _read_git_head(head_file: str) -> str:+ """Read the HEAD pointer directly, without spawning git.++ Changes whenever the checkout moves — switching branches rewrites the+ symbolic ref, and a detached checkout writes a different commit id — while+ staying untouched by ordinary edits to the working tree. That makes it a+ cheap way to tell "the conversation moved to a different checkout" apart+ from "the user edited a file", which need opposite treatment: the former+ must invalidate the snapshot, the latter must not.++ Args:+ head_file: Absolute path to the git directory's HEAD file.++ Returns:+ Stripped file contents, or an empty string when it cannot be read —+ in which case the caller degrades to holding the snapshot as-is.+ """+ if not head_file:+ return ""+ try:+ return Path(head_file).read_text(encoding="utf-8").strip()+ except OSError:+ return ""++@dataclass(frozen=True)class _StableGitFacts:"""Git facts about a project that do not change between turns of a chat.@@ -512,11 +541,15 @@ class _StableGitFacts:user_name: ``user.name`` from git config; empty when unset.main_branch: First of origin/main, origin/master, main, master thatresolves; empty when none do.+ head_file: Absolute path to the git directory's HEAD file. Resolved via+ git so it is correct for a subdirectory, a worktree or a submodule,+ where it is nowhere near ``<project_dir>/.git/HEAD``."""is_repo: booluser_name: strmain_branch: str+ head_file: str_STABLE_GIT_FACTS: dict[str, _StableGitFacts] = {}@@ -557,14 +590,23 @@ def _resolve_stable_git_facts(is_repo = run_git(["rev-parse", "--is-inside-work-tree"]) == "true"user_name = ""main_branch = ""+ head_file = ""if is_repo:user_name = run_git(["config", "user.name"])for candidate in ("origin/main", "origin/master", "main", "master"):if run_git(["rev-parse", "--verify", "--quiet", candidate]):main_branch = candidatebreak-- facts = _StableGitFacts(is_repo=is_repo, user_name=user_name, main_branch=main_branch)+ git_dir = run_git(["rev-parse", "--absolute-git-dir"])+ if git_dir:+ head_file = str(Path(git_dir) / "HEAD")++ facts = _StableGitFacts(+ is_repo=is_repo,+ user_name=user_name,+ main_branch=main_branch,+ head_file=head_file,+ )with _STABLE_GIT_FACTS_LOCK:_STABLE_GIT_FACTS[cache_key] = factsreturn facts@@ -1912,9 +1954,10 @@ class JiuWenSwarmDeepAdapter:self,project_dir: str,session_id: str | None,+ head_file: str,run_git: Callable[[list[str]], str],) -> _GitSnapshot:- """Return this conversation's git snapshot, taking it on the first turn.+ """Return this conversation's git snapshot, re-taking it if HEAD moved.The prompt these values feed states plainly that it is "the git statusat the start of the conversation" which "will not update during the@@ -1923,23 +1966,34 @@ class JiuWenSwarmDeepAdapter:prompt's own contract and, because the text sits in the cached prefix,invalidates the model's KV cache for every later turn.+ Working-tree edits therefore do not refresh it: the agent either made+ them itself (and has them in its history) or can run git on demand.+ Moving the checkout is different — a branch switch changes which+ branch a commit would land on, and invalidates status and recent+ commits wholesale — so HEAD is checked each turn and a move re-takes+ the snapshot. That check is a file read, not a subprocess, which is why+ it can run on the hot path at all.+Args:project_dir: Directory the git commands run in.session_id: Conversation the snapshot belongs to; a new sessiontakes a fresh one.+ head_file: Absolute path to the git directory's HEAD file.run_git: Callable running git in ``project_dir`` and returningstripped stdout, or an empty string on failure.Returns:- The snapshot for this conversation.+ The snapshot for this conversation and checkout."""cache_key = f"{project_dir}\0{session_id or ''}"+ head = _read_git_head(head_file)cached = self._session_git_snapshots.get(cache_key)- if cached is not None:+ if cached is not None and cached.head == head:return cachedstatus_lines = run_git(["status", "--short"]).splitlines()snapshot = _GitSnapshot(+ head=head,branch=run_git(["rev-parse", "--abbrev-ref", "HEAD"]) or "HEAD",status="\n".join(status_lines[:50]),recent_commits=run_git(["log", "--oneline", "-5"]),@@ -1985,6 +2039,7 @@ class JiuWenSwarmDeepAdapter:snapshot = self._resolve_session_git_snapshot(project_dir,session_id,+ stable_facts.head_file,_run_git,)git_branch = snapshot.branch@@ -6082,7 +6137,11 @@ class JiuWenSwarmDeepAdapter:stage_timer = StageTimer()try:- await self._apply_runtime_config_stages(runtime_config, stage_timer, bind_request)+ await self._apply_runtime_config_stages(+ runtime_config,+ stage_timer,+ bind_request=bind_request,+ )finally:total_ms = stage_timer.total_ms()log_runtime_config_stages = _stage_breakdown_logger(diff --git a/tests/unit_tests/agentserver/test_session_git_snapshot.py b/tests/unit_tests/agentserver/test_session_git_snapshot.pyindex fb2236ab9a..4ed88f74b1 100644--- a/tests/unit_tests/agentserver/test_session_git_snapshot.py+++ b/tests/unit_tests/agentserver/test_session_git_snapshot.py@@ -4,9 +4,22 @@from __future__ import annotations+from pathlib import Path+import pytest-from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+ _read_git_head,+)++[email protected](name="head_file")+def _head_file(tmp_path: Path) -> Path:+ """Create a git HEAD file standing in for a real checkout."""+ path = tmp_path / "HEAD"+ path.write_text("ref: refs/heads/dev/feature\n", encoding="utf-8")+ return pathdef _make_adapter() -> JiuWenSwarmDeepAdapter:@@ -17,13 +30,13 @@ def _make_adapter() -> JiuWenSwarmDeepAdapter:def _make_runner(calls: list[list[str]], status: str = " M a.py") -> callable:- """Return a git runner double recording commands and serving mutable status."""- state = {"status": status}+ """Return a git runner double recording commands and serving mutable output."""+ state = {"status": status, "branch": "dev/feature"}def _run(args: list[str]) -> str:calls.append(args)if args[:2] == ["rev-parse", "--abbrev-ref"]:- return "dev/branch"+ return state["branch"]if args[0] == "status":return state["status"]if args[0] == "log":@@ -34,24 +47,24 @@ def _make_runner(calls: list[list[str]], status: str = " M a.py") -> callable:return _run-def test_snapshot_is_taken_once_per_conversation() -> None:+def test_snapshot_is_taken_once_per_conversation(head_file: Path) -> None:"""Later turns reuse the first turn's snapshot instead of re-running git."""adapter = _make_adapter()calls: list[list[str]] = []runner = _make_runner(calls)- first = adapter._resolve_session_git_snapshot("/repo", "sess_a", runner)+ first = adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)for _ in range(4):- adapter._resolve_session_git_snapshot("/repo", "sess_a", runner)+ adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)- assert first.branch == "dev/branch"+ assert first.branch == "dev/feature"assert first.status == " M a.py"assert first.recent_commits == "abc123 first"- # branch + status + log on the first turn, nothing after.+ # status + branch + log on the first turn, nothing after.assert len(calls) == 3-def test_edits_during_the_conversation_do_not_change_the_snapshot() -> None:+def test_edits_during_the_conversation_do_not_change_the_snapshot(head_file: Path) -> None:"""The injected prompt promises a start-of-conversation snapshot.Re-reading it per turn is what rewrote the system prompt mid-conversation@@ -60,68 +73,127 @@ def test_edits_during_the_conversation_do_not_change_the_snapshot() -> None:adapter = _make_adapter()calls: list[list[str]] = []runner = _make_runner(calls)- adapter._resolve_session_git_snapshot("/repo", "sess_a", runner)+ adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)runner.state["status"] = " M a.py\n M b.py\n?? c.py"- later = adapter._resolve_session_git_snapshot("/repo", "sess_a", runner)+ later = adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)assert later.status == " M a.py"-def test_a_new_conversation_takes_a_fresh_snapshot() -> None:+def test_branch_switch_retakes_the_snapshot(head_file: Path) -> None:+ """Moving the checkout invalidates everything the snapshot describes.++ Which branch a commit lands on is not something the agent may be stale+ about, and a switch changes status and recent commits wholesale.+ """+ adapter = _make_adapter()+ calls: list[list[str]] = []+ runner = _make_runner(calls)+ adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)+ calls.clear()++ head_file.write_text("ref: refs/heads/main\n", encoding="utf-8")+ runner.state["branch"] = "main"+ runner.state["status"] = ""++ refreshed = adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)++ assert refreshed.branch == "main"+ assert refreshed.status == ""+ assert len(calls) == 3+++def test_detached_checkout_move_retakes_the_snapshot(head_file: Path) -> None:+ """A detached HEAD writes a commit id, and moving it counts as a move."""+ adapter = _make_adapter()+ runner = _make_runner([])+ head_file.write_text("a" * 40 + "\n", encoding="utf-8")+ adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)++ head_file.write_text("b" * 40 + "\n", encoding="utf-8")+ runner.state["status"] = " M moved.py"+ refreshed = adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)++ assert refreshed.status == " M moved.py"+++def test_a_new_conversation_takes_a_fresh_snapshot(head_file: Path) -> None:"""A new session is a new conversation, so it re-reads git."""adapter = _make_adapter()calls: list[list[str]] = []runner = _make_runner(calls)- adapter._resolve_session_git_snapshot("/repo", "sess_a", runner)+ adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)runner.state["status"] = " M b.py"calls.clear()- fresh = adapter._resolve_session_git_snapshot("/repo", "sess_b", runner)+ fresh = adapter._resolve_session_git_snapshot("/repo", "sess_b", str(head_file), runner)assert fresh.status == " M b.py"assert len(calls) == 3-def test_switching_project_dir_takes_a_fresh_snapshot() -> None:+def test_switching_project_dir_takes_a_fresh_snapshot(head_file: Path) -> None:"""Two project dirs in one session must not share a snapshot."""adapter = _make_adapter()calls: list[list[str]] = []runner = _make_runner(calls)- adapter._resolve_session_git_snapshot("/repo/a", "sess_a", runner)+ adapter._resolve_session_git_snapshot("/repo/a", "sess_a", str(head_file), runner)calls.clear()- adapter._resolve_session_git_snapshot("/repo/b", "sess_a", runner)+ adapter._resolve_session_git_snapshot("/repo/b", "sess_a", str(head_file), runner)assert len(calls) == 3-def test_status_is_capped_at_fifty_lines() -> None:+def test_unreadable_head_degrades_to_holding_the_snapshot(tmp_path: Path) -> None:+ """Losing the HEAD probe must not make every turn re-run git."""+ adapter = _make_adapter()+ calls: list[list[str]] = []+ runner = _make_runner(calls)+ missing = str(tmp_path / "nope" / "HEAD")++ adapter._resolve_session_git_snapshot("/repo", "sess_a", missing, runner)+ calls.clear()+ adapter._resolve_session_git_snapshot("/repo", "sess_a", missing, runner)++ assert calls == []+++def test_status_is_capped_at_fifty_lines(head_file: Path) -> None:"""A large working tree must not flood the prompt."""adapter = _make_adapter()runner = _make_runner([], status="\n".join(f" M file{i}.py" for i in range(80)))- snapshot = adapter._resolve_session_git_snapshot("/repo", "sess_a", runner)+ snapshot = adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), runner)assert len(snapshot.status.splitlines()) == 50-def test_detached_head_falls_back_to_a_stable_name() -> None:+def test_detached_head_falls_back_to_a_stable_name(head_file: Path) -> None:"""An empty branch read must not leave the prompt with a blank field."""adapter = _make_adapter()def _run(args: list[str]) -> str:return ""- snapshot = adapter._resolve_session_git_snapshot("/repo", "sess_a", _run)+ snapshot = adapter._resolve_session_git_snapshot("/repo", "sess_a", str(head_file), _run)assert snapshot.branch == "HEAD"-def test_snapshots_are_immutable() -> None:+def test_snapshots_are_immutable(head_file: Path) -> None:"""A shared snapshot must not be editable by one caller."""adapter = _make_adapter()- snapshot = adapter._resolve_session_git_snapshot("/repo", "sess_a", _make_runner([]))+ snapshot = adapter._resolve_session_git_snapshot(+ "/repo", "sess_a", str(head_file), _make_runner([])+ )with pytest.raises(Exception):snapshot.status = "tampered"+++def test_read_git_head_handles_a_missing_probe() -> None:+ """An unset or unreadable path yields an empty fingerprint, not an error."""+ assert _read_git_head("") == ""+ assert _read_git_head("/nonexistent/path/HEAD") == ""diff --git a/tests/unit_tests/agentserver/test_stable_git_facts_cache.py b/tests/unit_tests/agentserver/test_stable_git_facts_cache.pyindex 466b720152..bbb5541405 100644--- a/tests/unit_tests/agentserver/test_stable_git_facts_cache.py+++ b/tests/unit_tests/agentserver/test_stable_git_facts_cache.py@@ -28,6 +28,8 @@ def _make_runner(calls: list[list[str]], *, is_repo: bool = True) -> callable:return "alan"if args[0] == "rev-parse" and "--verify" in args:return "abc123" if args[-1] == "origin/master" else ""+ if args[:2] == ["rev-parse", "--absolute-git-dir"]:+ return "/repo/.git"return ""return _run@@ -46,8 +48,10 @@ def test_stable_facts_are_resolved_once_per_project() -> None:assert first.user_name == "alan"# origin/main is probed first and misses, origin/master answers.assert first.main_branch == "origin/master"- # is-inside-work-tree + user.name + two probes, and nothing on later turns.- assert len(calls) == 4+ # Resolved via git, so it is right for a subdirectory, worktree or submodule.+ assert first.head_file.endswith("HEAD")+ # is-inside-work-tree + user.name + two probes + git-dir, then nothing.+ assert len(calls) == 5def test_non_repo_skips_the_remaining_probes() -> None: