The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): keep the session-start workspace snapshot across prompt rebuilds
teknium1921ab7a16310
diff --git a/agent/coding_context.py b/agent/coding_context.pyindex 1cc962c1f65..181a1141856 100644--- a/agent/coding_context.py+++ b/agent/coding_context.py@@ -514,6 +514,9 @@ def project_facts_for(cwd: Optional[str | Path] = None) -> Optional[dict[str, An}+WORKSPACE_BLOCK_HEADER = "Workspace (snapshot at session start — re-check with `git` before acting on it):"++def build_coding_workspace_block(cwd: Optional[str | Path] = None) -> str:"""Workspace snapshot for the system prompt (empty outside a workspace): git state whenin a repo, plus project facts — so marker-only (non-git) projects still get one."""@@ -521,7 +524,7 @@ def build_coding_workspace_block(cwd: Optional[str | Path] = None) -> str:if root is None:return ""lines = [- "Workspace (snapshot at session start — re-check with `git` before acting on it):",+ WORKSPACE_BLOCK_HEADER,f"- Root: {root}",]if git_root is not None:diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 57af87b558c..d830d525588 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -31,7 +31,7 @@ from agent.prompt_caching import (from agent.repetition_guard import REPETITION_LOOP_INTERRUPTED, is_runaway_repetitionfrom agent.runtime_cwd import resolve_agent_cwdfrom agent.surface_switch import (- identity_line_value, note_inert_pinned_tools, split_runtime_boundary, stage_surface_switch_note,+ identity_line_value, note_inert_pinned_tools, runtime_host_value, stage_surface_switch_note,)from agent.turn_context import PreflightCompressionTimedOut, build_turn_contextfrom agent.turn_retry_state import TurnRetryState@@ -814,20 +814,6 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)def _stored_prompt_matches_runtime(agent, prompt: str) -> bool:"""Return False when the persisted runtime-identity lines are stale."""-- _identity, runtime_marker, runtime = split_runtime_boundary(prompt)-- def host_info_value(label: str) -> str:- """New prompts delimit runtime hints; legacy prompts put them before context."""- prefix = f"{label}:"- host_lines = (runtime.split("\n\n", 1)[0] if runtime_marker else prompt).splitlines()- for idx, line in enumerate(host_lines):- if line.startswith("User home directory:"):- for candidate in host_lines[idx + 1: idx + 4]:- if candidate.startswith(prefix):- return candidate[len(prefix):].strip()- return ""-# Model/provider identity, then cwd drift. A cwd change is a real content change (context# files, the workspace snapshot and the coding posture are all resolved from it), so it# still rebuilds; the runtime surface does not (agent/surface_switch.py).@@ -838,7 +824,7 @@ def _stored_prompt_matches_runtime(agent, prompt: str) -> bool:return False# Compare against resolve_agent_cwd() — the SAME resolver used to build the# prompt — so TERMINAL_CWD sessions are not falsely rejected.- stored_cwd = host_info_value("Current working directory")+ stored_cwd = runtime_host_value(prompt, "Current working directory")if stored_cwd and stored_cwd != str(resolve_agent_cwd()):return False# Platform is deliberately NOT an identity field: a surface switch does not invalidate thediff --git a/agent/surface_switch.py b/agent/surface_switch.pyindex 5b642ecd0b3..39e1f8f6bf3 100644--- a/agent/surface_switch.py+++ b/agent/surface_switch.py@@ -36,6 +36,20 @@ def split_runtime_boundary(prompt: str) -> tuple:return (identity, runtime_marker, runtime) if prompt.endswith(RUNTIME_ENVIRONMENT_END) else (prompt, "", "")+def runtime_host_value(prompt: str, label: str) -> str:+ """``Label: value`` from the host lines of a persisted prompt (``Current working directory``);+ new prompts delimit runtime hints, legacy prompts put them before context. "" when absent."""+ _identity, runtime_marker, runtime = split_runtime_boundary(prompt)+ prefix = f"{label}:"+ host_lines = (runtime.split("\n\n", 1)[0] if runtime_marker else prompt).splitlines()+ for idx, line in enumerate(host_lines):+ if line.startswith("User home directory:"):+ for candidate in host_lines[idx + 1: idx + 4]:+ if candidate.startswith(prefix):+ return candidate[len(prefix):].strip()+ return ""++def identity_line_value(prompt: str, label: str) -> str:"""Last ``Label: value`` line in the identity portion (the final runtime block is embedderprose, never identity). Last match wins — safe only for the volatile-tier trailer fields."""diff --git a/agent/system_prompt.py b/agent/system_prompt.pyindex 77390ce01d4..dd9a1e3173d 100644--- a/agent/system_prompt.py+++ b/agent/system_prompt.py@@ -26,7 +26,7 @@ from agent.prompt_builder import (TOOL_USE_ENFORCEMENT_GUIDANCE, TOOL_USE_ENFORCEMENT_MODELS, drain_truncation_warnings,)from agent import prompt_builder as _pb-from agent.runtime_cwd import resolve_context_cwd+from agent.runtime_cwd import resolve_agent_cwd, resolve_context_cwdfrom hermes_constants import get_default_hermes_root, get_hermes_homefrom utils import is_truthy_value@@ -592,6 +592,70 @@ def _alibaba_identity_part(agent: Any) -> List[str]:]+def _workspace_pin_key() -> str:+ """The directory the workspace probe inspects, which is also the prompt's ``Current working+ directory``: a build with no cwd bound (launch dir) and a later one binding that same dir+ (TUI ``/compress``) are one workspace, not two."""+ try:+ return str(resolve_context_cwd() or resolve_agent_cwd())+ except OSError: # deleted cwd+ return ""+++def _persisted_workspace_block(prompt: str, key: str) -> Optional[str]:+ """The workspace snapshot inside ``prompt`` taken for ``key`` (its ``- Root:`` is ``key`` or an+ ancestor); "" when the prompt has none; None when it has one for another root."""+ from agent.coding_context import WORKSPACE_BLOCK_HEADER+ head = f"\n\n{WORKSPACE_BLOCK_HEADER}\n- Root: "+ start = prompt.find(head)+ if start < 0:+ return ""+ cwd = Path(key).resolve()+ while start >= 0:+ block = prompt[start + 2:].split("\n\n", 1)[0]+ root = Path(block.split("\n", 2)[1][len("- Root: "):]).resolve()+ if root == cwd or root in cwd.parents:+ return block+ start = prompt.find(head, start + 2)+ return None+++def _session_prompt(agent: Any) -> Optional[str]:+ """Prompt bytes this session already sends: the cached copy, else its persisted row."""+ cached = getattr(agent, "_cached_system_prompt", None)+ if isinstance(cached, str) and cached:+ return cached+ db, session_id = getattr(agent, "_session_db", None), getattr(agent, "session_id", None)+ if db is None or not isinstance(session_id, str) or not session_id:+ return None+ try:+ row = db.get_session(session_id)+ except Exception:+ logger.debug("workspace snapshot: session row read failed (session=%s)", session_id, exc_info=True)+ return None+ prompt = row.get("system_prompt") if isinstance(row, dict) else None+ return prompt if isinstance(prompt, str) and prompt else None+++def _seed_workspace_pin(agent: Any, key: str) -> None:+ """Pin the snapshot the session's existing prompt already carries. An agent that did not+ build those bytes (resumed, or a fresh gateway/TUI agent whose first act is ``/compress``)+ would otherwise re-probe git at its first rebuild and rewrite the prompt for any repo that+ moved since session start. Only a snapshot provably taken in this cwd is adopted."""+ from agent.surface_switch import runtime_host_value+ prompt = _session_prompt(agent)+ if not prompt:+ return+ stored_cwd = runtime_host_value(prompt, "Current working directory")+ if stored_cwd and stored_cwd != key:+ return+ block = _persisted_workspace_block(prompt, key)+ # "" is only trustworthy when the prompt names this cwd: a legacy prompt without the+ # runtime line might have been built with tools off.+ if block or (block == "" and stored_cwd):+ agent._frozen_workspace_snapshot = (key, block)++def _coding_parts(agent: Any) -> Tuple[List[str], List[str], List[str]]:"""``(prefix, workspace, trailing)`` coding-posture blocks; all emptywithout tools or when probing fails (it must never block prompt build).@@ -599,15 +663,18 @@ def _coding_parts(agent: Any) -> Tuple[List[str], List[str], List[str]]:The workspace block is a live git probe after project context, ahead of the wholevolatile band; re-probing at the compaction rebuild re-emits different bytes for anyrepo that moved and defeats the keep-prompt fast path. So the bytes are pinned per- session on the agent, keyed by the resolved cwd (a gateway serves many cwds), and- replayed on rebuilds; ``reset_session_state`` drops the pin at a session boundary.+ session on the agent, keyed by the probed cwd (a gateway serves many cwds), seeded from+ the session's existing prompt when this agent did not build it, and replayed on+ rebuilds; ``reset_session_state`` drops the pin at a session boundary."""try:from agent.coding_context import coding_system_prompt_partsif not agent.valid_tool_names:return [], [], []cwd = resolve_context_cwd()- cwd_key = str(cwd) if cwd is not None else ""+ cwd_key = _workspace_pin_key()+ if getattr(agent, "_frozen_workspace_snapshot", None) is None:+ _seed_workspace_pin(agent, cwd_key)pinned = getattr(agent, "_frozen_workspace_snapshot", None)# "" is a real pinned value (no workspace here) — only a cwd mismatch re-probes.replay = pinned[1] if pinned is not None and pinned[0] == cwd_key else Nonediff --git a/tests/agent/test_compaction_prompt_rebuild.py b/tests/agent/test_compaction_prompt_rebuild.pyindex a3325c69e09..a9f40ab3090 100644--- a/tests/agent/test_compaction_prompt_rebuild.py+++ b/tests/agent/test_compaction_prompt_rebuild.py@@ -217,6 +217,72 @@ class TestWorkspaceSnapshotPinnedAcrossCompaction(unittest.TestCase):finally:shutil.rmtree(tmp, ignore_errors=True)+ def _pin_agent(self, **over):+ return _agent(+ load_soul_identity=False, skip_context_files=True, valid_tool_names={"terminal"},+ platform="cli", model="gpt-4o", _task_completion_guidance=False,+ _parallel_tool_call_guidance=False, _tool_use_enforcement=False, _execution_guidance=False,+ _environment_probe=False, _bot_mode_protocol=False, _kanban_worker_guidance="",+ pass_session_id=False, session_id="s1", _emit_status=lambda *a, **k: None, **over,+ )++ def test_binding_the_launch_dir_explicitly_replays_the_pin(self):+ """CLI-shaped first build (no cwd bound -> launch dir), then TUI /compress binds that same dir:+ one workspace, so the rebuild replays the session-start snapshot."""+ import os, tempfile, shutil+ from pathlib import Path+ from agent.system_prompt import build_system_prompt, invalidate_system_prompt++ tmp = Path(tempfile.mkdtemp(prefix="test-pinned-bind-"))+ old_cwd = os.getcwd()+ try:+ repo = _init_repo(tmp / "proj", "init commit")+ os.chdir(repo)+ agent = self._pin_agent()+ with patch("agent.prompt_builder.load_soul_md", return_value=""), \+ patch("agent.prompt_builder.build_environment_hints", return_value="ENV HINTS"):+ with patch("agent.system_prompt.resolve_context_cwd", return_value=None):+ p1 = build_system_prompt(agent)+ self.assertIn("Status: clean", p1)+ (repo / "untracked.txt").write_text("wip\n")+ invalidate_system_prompt(agent)+ with patch("agent.system_prompt.resolve_context_cwd", return_value=repo):+ self.assertEqual(build_system_prompt(agent), p1)+ finally:+ os.chdir(old_cwd)+ shutil.rmtree(tmp, ignore_errors=True)++ def test_agent_that_did_not_build_the_prompt_replays_the_persisted_snapshot(self):+ """Resume / gateway / TUI shape: a fresh agent rebuilds (compaction, a first /compress) after+ the repo moved and replays the snapshot its session row already holds — unless that prompt+ was taken in another cwd."""+ import tempfile, shutil+ from pathlib import Path+ from agent.system_prompt import build_system_prompt++ tmp = Path(tempfile.mkdtemp(prefix="test-pinned-resume-"))+ try:+ repo, other = _init_repo(tmp / "proj", "init commit"), _init_repo(tmp / "other", "init other")++ def env(cwd):+ return patch("agent.prompt_builder.build_environment_hints",+ return_value=f"Host: x\nUser home directory: /h\nCurrent working directory: {cwd}")++ with patch("agent.prompt_builder.load_soul_md", return_value=""), env(repo), \+ patch("agent.system_prompt.resolve_context_cwd", return_value=repo):+ stored = build_system_prompt(self._pin_agent())+ self.assertIn("Status: clean", stored)+ (repo / "untracked.txt").write_text("wip\n")+ db = SimpleNamespace(get_session=lambda sid: {"system_prompt": stored})+ resumed = self._pin_agent(_cached_system_prompt=None, _session_db=db)+ self.assertEqual(build_system_prompt(resumed), stored)+ with patch("agent.prompt_builder.load_soul_md", return_value=""), env(other), \+ patch("agent.system_prompt.resolve_context_cwd", return_value=other):+ moved = self._pin_agent(_cached_system_prompt=None, _session_db=db)+ self.assertIn(f"- Root: {other}", build_system_prompt(moved))+ finally:+ shutil.rmtree(tmp, ignore_errors=True)+if __name__ == "__main__":unittest.main()