Skip to content

The agent that grows with you

fix(update): keep the autostash when the update replaced a user's untracked file (#124641)

teknium178ee5e96db80
diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.py
index 8c78f5c6bd3..e5e00af799c 100644
--- a/hermes_cli/update_cmd_stash.py
+++ b/hermes_cli/update_cmd_stash.py
@@ -224,6 +224,28 @@ def _stash_apply_failed_only_on_existing_untracked(stderr: str) -> bool:
return saw_untracked_error
+def _untracked_collisions_that_differ(git_cmd: list[str], cwd: Path, stash_ref: str, stderr: str) -> list[str]:
+ """Paths ``git stash apply`` refused ("<path> already exists, no checkout") whose working-tree
+ content is NOT the stash's untracked copy (``<stash>^3``). Unknown -> treated as differing."""
+ differing = []
+ suffix = " already exists, no checkout"
+ for ln in (stderr or "").splitlines():
+ ln = ln.strip()
+ if not ln.endswith(suffix):
+ continue
+ rel = ln[: -len(suffix)]
+ stashed = subprocess.run(
+ [*git_cmd, "show", f"{stash_ref}^3:{rel}"], cwd=cwd, capture_output=True, check=False,
+ )
+ try:
+ current = (Path(cwd) / rel).read_bytes()
+ except OSError:
+ current = None
+ if stashed.returncode != 0 or current != stashed.stdout:
+ differing.append(rel)
+ return differing
+
+
def _park_stashed_changes(stash_ref: str) -> None:
"""Leave a pre-update autostash parked (``--keep-stash``, the desktop updater's mode): local source
edits must never be silently re-applied onto updated code; the entry stays in ``git stash``."""
@@ -326,10 +348,21 @@ def _apply_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> bool:
if restore.returncode == 0 and not conflicted_files:
return True
if not conflicted_files and _stash_apply_failed_only_on_existing_untracked(restore.stderr):
- # Tracked changes applied; only undeletable-at-stash-time untracked files were refused. Their
- # content is untouched — treat as restored.
- print(" ⚠ Some stashed untracked files already exist in the working tree and were kept as-is.")
- return True
+ # Tracked changes applied; git refused to overwrite untracked files that already exist. That is
+ # harmless only when the occupant IS the stashed copy (undeletable at stash time, #70127). When
+ # the update added its own file at that path, dropping the stash would lose the user's copy.
+ replaced = _untracked_collisions_that_differ(git_cmd, cwd, stash_ref, restore.stderr)
+ if not replaced:
+ print(" ⚠ Some stashed untracked files already exist in the working tree and were kept as-is.")
+ return True
+ print(f"⚠ The update added {len(replaced)} file(s) where you had untracked files of the same name:")
+ for path in replaced[:10]:
+ print(f" {path}")
+ print(" The updated files are in place; your versions are kept in the stash, which was NOT dropped.")
+ print(f" Stash ref: {stash_ref}")
+ print(f" Recover a file with: git show {stash_ref}^3:<path> > <path>.mine")
+ _record_stash_disposition("parked", stash_ref, f"untracked files replaced by the update: {', '.join(replaced[:10])}")
+ return False
print("✗ Update pulled new code, but restoring local changes hit conflicts.")
_print_nonempty(restore.stdout)
_print_nonempty(restore.stderr)
diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.py
index ef927ee6b65..936214b356d 100644
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@ -577,3 +577,42 @@ def test_keep_stash_park_records_parked_step_in_receipt(capsys):
assert len(disposition) == 1
assert disposition[0]["ok"] is False
assert "parked" in disposition[0]["detail"]
+
+
+def test_untracked_file_replaced_by_the_update_keeps_the_stash(tmp_path):
+ """#124641: the update adds a file where the user had an untracked file of the same name.
+ ``stash apply`` refuses it ("already exists, no checkout"); the stash is the only copy of the
+ user's version, so it must stay (parked), never be dropped as "kept as-is"."""
+ import subprocess
+
+ def git(*args, check=True):
+ return subprocess.run(["git", *args], cwd=tmp_path, capture_output=True, text=True, check=check)
+
+ git("init", "-q", "-b", "main")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ (tmp_path / "tracked.txt").write_text("v1\n", encoding="utf-8")
+ git("add", "-A")
+ git("commit", "-qm", "init")
+
+ (tmp_path / "tracked.txt").write_text("v1 local edit\n", encoding="utf-8")
+ (tmp_path / "notes.md").write_text("my private notes\n", encoding="utf-8")
+ stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
+ assert stash_ref
+ # The pull adds its own notes.md.
+ (tmp_path / "notes.md").write_text("upstream notes\n", encoding="utf-8")
+ git("add", "-A")
+ git("commit", "-qm", "upstream adds notes.md")
+
+ probe = _ReceiptProbe()
+ with _active_receipt(probe):
+ restored = hermes_main._restore_stashed_changes(["git"], tmp_path, stash_ref, prompt_user=False)
+
+ assert restored is False
+ assert (tmp_path / "tracked.txt").read_text(encoding="utf-8") == "v1 local edit\n"
+ assert (tmp_path / "notes.md").read_text(encoding="utf-8") == "upstream notes\n"
+ assert git("stash", "list").stdout.strip(), "the stash is the only copy of the user's notes.md"
+ assert git("show", f"{stash_ref}^3:notes.md").stdout == "my private notes\n"
+ disposition = [s for s in probe.steps if s["name"] == "local_changes_stash"]
+ assert len(disposition) == 1 and disposition[0]["ok"] is False
+ assert "parked" in disposition[0]["detail"] and "notes.md" in disposition[0]["detail"]