The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update,plugins): address autostash entries by sha / bare index, never stash@{N}
teknium192e6cc189bb8
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex 736711080e0..c21871f167b 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -2072,23 +2072,31 @@ def _stash_ref(git_exe: str, target: Path) -> str:return probe.stdout.strip() if probe.returncode == 0 else ""-def _reapply_stash(git_exe: str, target: Path) -> bool:- """``stash apply`` the autostash; drop it on a clean apply. False when it applied with- errors or left unmerged paths (the stash entry is kept in that case)."""- restore = _run_plugin_git(git_exe, target, "stash", "apply", "stash@{0}")+def _reapply_stash(git_exe: str, target: Path, stash_sha: str) -> bool:+ """``stash apply`` the autostash commit *stash_sha*; drop it on a clean apply. False when it+ applied with errors or left unmerged paths (the stash entry is kept in that case).++ Git is addressed by the stash's commit sha, never a ``stash@{N}`` selector: on native Windows+ the MSYS runtime re-parses git.exe's argv and strips the braces, so ``stash@{0}`` reaches git+ as ``stash@0`` and both the apply and the drop fail (#87542)."""+ restore = _run_plugin_git(git_exe, target, "stash", "apply", stash_sha)unmerged = _run_plugin_git(git_exe, target, "diff", "--name-only", "--diff-filter=U")if restore.returncode != 0 or unmerged.stdout.strip():return False- _run_plugin_git(git_exe, target, "stash", "drop", "stash@{0}")+ # `stash drop` only takes a selector; a bare `drop` targets the newest entry, so drop+ # positionally only while the newest entry is still our autostash.+ if _stash_ref(git_exe, target) == stash_sha:+ _run_plugin_git(git_exe, target, "stash", "drop")return True-def _autostash_dirty_tree(git_exe: str, target: Path) -> tuple[bool, str]:- """Stash local edits before a pull. Returns ``(stash_created, error)``; a non-empty error means- the tree is dirty but nothing was saved, so the pull must not run."""+def _autostash_dirty_tree(git_exe: str, target: Path) -> tuple[str, str]:+ """Stash local edits before a pull. Returns ``(stash_sha, error)``; *stash_sha* is empty when+ the tree was clean, and a non-empty error means the tree is dirty but nothing was saved, so+ the pull must not run."""status = _run_plugin_git(git_exe, target, "status", "--porcelain", "-z")if status.returncode != 0 or not status.stdout.strip():- return False, ""+ return "", ""# `git add -N` entries make `git stash push` fail outright (see update_cmd_stash), so promote them# to real staged adds first; the checkout's own local edits are otherwise unstashable.from hermes_cli.update_cmd_stash import _intent_to_add_paths@@ -2102,7 +2110,7 @@ def _autostash_dirty_tree(git_exe: str, target: Path) -> tuple[bool, str]:post_stash = _stash_ref(git_exe, target)if not post_stash or post_stash == pre_stash:err = _safe_git_error(push)- return False, (+ return "", ("Local changes in the plugin checkout could not be ""stashed; update aborted before touching the checkout."+ (f"\n{err}" if err else ""))@@ -2110,7 +2118,7 @@ def _autostash_dirty_tree(git_exe: str, target: Path) -> tuple[bool, str]:# Saved-but-couldn't-clean (undeletable untracked files): the stash entry is complete;# reset tracked mods so the pull isn't blocked by a still-dirty tree._run_plugin_git(git_exe, target, "reset", "--hard", "HEAD")- return True, ""+ return post_stash, ""def _git_pull_plugin_dir(target: Path) -> tuple[bool, str]:@@ -2127,26 +2135,26 @@ def _git_pull_plugin_dir(target: Path) -> tuple[bool, str]:if not git_exe:return False, "git is not installed or not in PATH."try:- stash_created, err = _autostash_dirty_tree(git_exe, target)+ stash_sha, err = _autostash_dirty_tree(git_exe, target)if err:return False, errorigin = _run_plugin_git(git_exe, target, "remote", "get-url", "origin", timeout=15)result = _run_plugin_git(git_exe, target, "pull", "--ff-only", auth_url=origin.stdout.strip())if result.returncode != 0:err = _safe_git_error(result) or "git pull failed."- if not stash_created:+ if not stash_sha:return False, err# Put the user's edits back before reporting the failure.- if _reapply_stash(git_exe, target):+ if _reapply_stash(git_exe, target, stash_sha):note = "Local changes were restored."else:note = "Local changes are preserved in git stash (restore with: git stash pop)."return False, f"{err}\n{note}"pulled = result.stdout.strip()- if not stash_created:+ if not stash_sha:return True, pulled- if _reapply_stash(git_exe, target):+ if _reapply_stash(git_exe, target, stash_sha):return True, pulled + "\nLocal changes were re-applied on top of the update."# Conflicted re-apply: leave the plugin importable on the updated@@ -2155,7 +2163,7 @@ def _git_pull_plugin_dir(target: Path) -> tuple[bool, str]:return True, pulled + ("\n⚠ Local changes in this plugin conflicted with the update and ""were NOT re-applied. They are preserved in git stash — inspect "- "with `git stash show -p stash@{0}` and re-apply with "+ "with `git stash show -p` and re-apply with "f"`git stash pop` inside {target}.")except FileNotFoundError:return False, "git is not installed or not in PATH."diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.pyindex 1c5b2841cf2..b2971858a60 100644--- a/hermes_cli/update_cmd_stash.py+++ b/hermes_cli/update_cmd_stash.py@@ -5,6 +5,7 @@ Origin helpers are imported lazily per function (no cycle; test patches on the o"""import logging+import reimport subprocessfrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -123,12 +124,17 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[stdef _resolve_stash_selector(git_cmd: list[str], cwd: Path, stash_ref: str) -> Optional[str]:+ """Selector for the stash entry whose commit is *stash_ref*, as the bare index ``N``+ (git accepts it wherever ``stash@{N}`` is valid). Never ``stash@{N}`` itself: on native+ Windows the MSYS runtime strips the braces from git.exe's argv, so ``stash@{0}`` reaches git+ as ``stash@0`` and the drop fails (#87542)."""from hermes_cli.update_cmd import _git_runstash_list = _git_run(git_cmd, ["stash", "list", "--format=%gd %H"], cwd, check=True)for line in stash_list.stdout.splitlines():selector, _, commit = line.partition(" ")if commit.strip() == stash_ref:- return selector.strip()+ match = re.fullmatch(r"stash@\{(\d+)\}", selector.strip())+ return match.group(1) if match else selector.strip()return None@@ -199,7 +205,7 @@ def _print_stash_cleanup_guidance(stash_ref: str, stash_selector: Optional[str]if stash_selector:print(f" Remove it with: git stash drop {stash_selector}")else:- print(f" Look for commit {stash_ref}, then drop its selector with: git stash drop stash@{{N}}")+ print(f" Look for commit {stash_ref}, then drop it by index with: git stash drop <N>")def _stash_apply_failed_only_on_existing_untracked(stderr: str) -> bool:diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.pyindex d6f3af7b4ce..99da7f89466 100644--- a/tests/hermes_cli/test_plugins_cmd.py+++ b/tests/hermes_cli/test_plugins_cmd.py@@ -295,6 +295,34 @@ class TestGitPullPluginDirAutostash:assert ok is Trueassert "Already up to date" in msg+ def test_autostash_addresses_git_by_sha_never_brace_selector(self, tmp_path, monkeypatch):+ """Native Windows: MSYS strips the braces from ``stash@{0}`` in git.exe's argv, so the+ apply and the drop must target the autostash by its commit sha / positionally (#87542)."""+ import hermes_cli.plugins_cmd as pc++ if not pc._resolve_git_executable():+ pytest.skip("git not available")+ origin, checkout, git = self._make_repos(tmp_path)+ self._set_line(origin, "VALUE", "VALUE = 2")+ git(origin, "commit", "-qam", "bump value")+ self._set_line(checkout, "OTHER", "OTHER = 'local'")++ argv_log: list[tuple[str, ...]] = []+ real_run = pc._run_plugin_git++ def recording_run(git_exe, target, *args, **kwargs):+ argv_log.append(args)+ return real_run(git_exe, target, *args, **kwargs)++ monkeypatch.setattr(pc, "_run_plugin_git", recording_run)+ ok, msg = pc._git_pull_plugin_dir(checkout)++ assert ok is True and "re-applied" in msg+ assert git(checkout, "stash", "list").strip() == ""+ assert not any("{" in arg or "}" in arg for args in argv_log for arg in args), argv_log+ applied = [args for args in argv_log if args[:2] == ("stash", "apply")]+ assert len(applied) == 1 and len(applied[0][2]) == 40, applied # by commit sha+# ── _repo_name_from_url ──────────────────────────────────────────────────@@ -992,7 +1020,8 @@ def test_autostash_dirty_tree_promotes_intent_to_add_entries(tmp_path):stashed, error = _autostash_dirty_tree("git", tmp_path)- assert (stashed, error) == (True, ""), "the plugin autostash must not be blocked by i-t-a entries"+ assert error == "", "the plugin autostash must not be blocked by i-t-a entries"+ assert stashed == git("rev-parse", "refs/stash").stdout.strip() # the autostash commit shaassert git("status", "--porcelain").stdout == ""diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.pyindex 8d48a6d12df..47db53b97ea 100644--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@ -736,6 +736,36 @@ def test_update_autostash_survives_undeletable_untracked_dir(tmp_path):os.chmod(pkg, 0o755)+def test_stash_selector_is_a_bare_index_never_a_brace_selector(tmp_path):+ """The updater drops its autostash through a selector read back from ``git stash list``; on+ native Windows MSYS strips the braces from ``stash@{N}`` in git.exe's argv, so the selector+ must be the bare index git accepts everywhere (#87542)."""+ import subprocess++ import hermes_cli.update_cmd_stash as stash_mod++ def git(*args):+ return subprocess.run(["git", *args], cwd=tmp_path, capture_output=True, text=True, check=True)++ git("init", "-q", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "t")+ (tmp_path / "f.txt").write_text("v1\n")+ git("add", "-A")+ git("commit", "-qm", "init")+ (tmp_path / "f.txt").write_text("older\n")+ git("stash", "push", "-q", "-m", "older")+ target_sha = git("rev-parse", "refs/stash").stdout.strip()+ (tmp_path / "f.txt").write_text("newer\n")+ git("stash", "push", "-q", "-m", "newer")++ selector = stash_mod._resolve_stash_selector(["git"], tmp_path, target_sha)++ assert selector == "1"+ git("stash", "drop", selector)+ assert target_sha not in git("stash", "list", "--format=%H").stdout++def test_autostash_survives_intent_to_add_entries(tmp_path):"""An index entry from `git add -N` must not block the update autostash.