The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): surface leftover update autostashes older than 7 days (#63717)
kshitijk4poor6b46725a1712
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 0158390266e..adfe599c11b 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -5219,6 +5219,7 @@ _LAZY_COMMAND_EXPORTS = {"_sync_with_upstream_if_needed","_update_node_dependencies","_update_via_zip",+ "_warn_orphaned_update_autostashes","_upgrade_pip_before_lazy_refresh","_validate_critical_files_syntax","_validate_critical_modules_import",diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex b185b07bcdb..0c9a7f97093 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -2541,7 +2541,7 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[stfrom datetime import datetime, timezonestash_name = datetime.now(timezone.utc).strftime(- "hermes-update-autostash-%Y%m%d-%H%M%S"+ f"{_AUTOSTASH_NAME_PREFIX}%Y%m%d-%H%M%S")print("→ Local changes detected — stashing before update...")prev_stash = subprocess.run(@@ -2628,6 +2628,83 @@ def _resolve_stash_selector(return selector.strip()return None+#: Producer/consumer contract for update autostash names: the stash subject is+#: this prefix + a UTC YYYYMMDD-HHMMSS stamp (see _stash_local_changes_if_needed+#: and _warn_orphaned_update_autostashes).+_AUTOSTASH_NAME_PREFIX = "hermes-update-autostash-"++#: Age past which a leftover ``hermes-update-autostash-*`` entry is called out+#: at update time. Entries younger than this are normal (a parked stash from+#: the desktop updater's --keep-stash run minutes ago); older ones are almost+#: always forgotten (#63717 problem 6: an orphan persisted 9+ days unnoticed).+_AUTOSTASH_WARN_AGE_DAYS = 7+++def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:+ """Surface leftover update autostashes older than the warn threshold.++ Autostash entries legitimately outlive an update run (``--keep-stash``+ parks them; a conflicted or failed restore preserves them for safety), but+ nothing ever re-surfaces them afterwards — they sit in ``git stash``+ invisibly for weeks (#63717 problem 6). This prints a short notice naming+ the stale entries with recovery/cleanup guidance. Deliberately NOT a GC:+ a stash entry can be the only copy of the user's uncommitted work, so+ Hermes never drops one automatically.++ Best-effort — any git failure returns 0 and must not block the update.+ Returns the number of stale entries warned about.+ """+ from datetime import timedelta, timezone++ try:+ stash_list = subprocess.run(+ git_cmd + ["stash", "list", "--format=%gd %s"],+ cwd=cwd,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ )+ if stash_list.returncode != 0:+ return 0+ cutoff = datetime.now(timezone.utc) - timedelta(+ days=_AUTOSTASH_WARN_AGE_DAYS+ )+ marker = _AUTOSTASH_NAME_PREFIX+ stale: list[tuple[str, str]] = []+ for line in stash_list.stdout.splitlines():+ selector, _, subject = line.strip().partition(" ")+ pos = subject.find(marker)+ if pos < 0:+ continue+ stamp = subject[pos + len(marker):][:15] # "YYYYMMDD-HHMMSS"+ try:+ stash_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(+ tzinfo=timezone.utc+ )+ except ValueError:+ # Unparseable name — age unknown; leave it alone rather than+ # guess (same posture as _prune_orphan_rescue_refs).+ continue+ if stash_time < cutoff:+ stale.append((selector, stamp))+ if not stale:+ return 0+ print()+ print(+ f"⚠ {len(stale)} leftover update autostash entr"+ f"{'y is' if len(stale) == 1 else 'ies are'} more than "+ f"{_AUTOSTASH_WARN_AGE_DAYS} days old:"+ )+ for selector, stamp in stale:+ print(f" {selector} ({_AUTOSTASH_NAME_PREFIX}{stamp})")+ print(" These hold local changes stashed by earlier updates and never")+ print(" restored. Review with: git stash show -p <entry>")+ print(" Restore with: git stash apply <entry> Discard with: git stash drop <entry>")+ return len(stale)+ except Exception as exc:+ logger.debug("Autostash age check failed: %s", exc)+ return 0++def _print_stash_cleanup_guidance(stash_ref: str, stash_selector: Optional[str] = None) -> None:@@ -8462,6 +8539,11 @@ def _cmd_update_impl(args, gateway_mode: bool):if swept:print(" (removed %d aborted-fetch pack temp file(s))" % len(swept))+ # Surface autostash entries left behind by earlier updates (#63717+ # problem 6) — parked --keep-stash runs and failed restores preserve+ # the stash but nothing ever mentioned it again.+ _m()._warn_orphaned_update_autostashes(git_cmd, _m().PROJECT_ROOT)+print("→ Fetching updates...")fetch_result = subprocess.run(git_cmd + ["fetch", "origin", branch],diff --git a/tests/hermes_cli/test_update_autostash_orphan_warning.py b/tests/hermes_cli/test_update_autostash_orphan_warning.pynew file mode 100644index 00000000000..99b932560bf--- /dev/null+++ b/tests/hermes_cli/test_update_autostash_orphan_warning.py@@ -0,0 +1,104 @@+"""Orphaned update-autostash surfacing (#63717 problem 6).++``hermes update`` can legitimately leave an autostash behind (--keep-stash+parks it; a conflicted restore preserves it), but nothing ever mentioned those+entries again — they persisted invisibly for weeks. ``hermes update`` now+warns about ``hermes-update-autostash-*`` entries older than the threshold.+Behavioral tests use real git repos; no production mocking of the code under+test.+"""++import subprocess+from datetime import datetime, timedelta, timezone++import pytest++from hermes_cli import update_cmd+++def _git(cwd, *args, check=True):+ return subprocess.run(+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=check+ )+++def _make_repo_with_autostash(tmp_path, age_days: float):+ """Real repo with one hermes-update-autostash entry aged ``age_days``."""+ import shutil++ if shutil.which("git") is None:+ pytest.skip("git not available")+ _git(tmp_path, "init", "-q", "-b", "main")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ (tmp_path / "tracked.txt").write_text("v1\n")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "init")++ (tmp_path / "tracked.txt").write_text("local change\n")+ stamp = (+ datetime.now(timezone.utc) - timedelta(days=age_days)+ ).strftime("%Y%m%d-%H%M%S")+ name = f"hermes-update-autostash-{stamp}"+ _git(tmp_path, "stash", "push", "--include-untracked", "-m", name)+ return name+++def test_old_autostash_is_surfaced(tmp_path, capsys):+ name = _make_repo_with_autostash(tmp_path, age_days=9)+ count = update_cmd._warn_orphaned_update_autostashes(["git"], tmp_path)+ out = capsys.readouterr().out+ assert count == 1+ assert "leftover update autostash" in out+ assert name in out+ assert "git stash apply" in out+ # Never a GC: the entry must still exist.+ listed = _git(tmp_path, "stash", "list").stdout+ assert name in listed+++def test_fresh_autostash_is_not_flagged(tmp_path, capsys):+ _make_repo_with_autostash(tmp_path, age_days=1)+ count = update_cmd._warn_orphaned_update_autostashes(["git"], tmp_path)+ assert count == 0+ assert "leftover update autostash" not in capsys.readouterr().out+++def test_non_hermes_stash_is_ignored(tmp_path, capsys):+ import shutil++ if shutil.which("git") is None:+ pytest.skip("git not available")+ _git(tmp_path, "init", "-q", "-b", "main")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ (tmp_path / "tracked.txt").write_text("v1\n")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "init")+ (tmp_path / "tracked.txt").write_text("user's own WIP\n")+ _git(tmp_path, "stash", "push", "-m", "my own stash from 20200101-000000")+ count = update_cmd._warn_orphaned_update_autostashes(["git"], tmp_path)+ assert count == 0+ assert "leftover update autostash" not in capsys.readouterr().out+++def test_unparseable_autostash_timestamp_left_alone(tmp_path, capsys):+ import shutil++ if shutil.which("git") is None:+ pytest.skip("git not available")+ _git(tmp_path, "init", "-q", "-b", "main")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ (tmp_path / "tracked.txt").write_text("v1\n")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "init")+ (tmp_path / "tracked.txt").write_text("change\n")+ _git(tmp_path, "stash", "push", "-m", "hermes-update-autostash-notadate")+ count = update_cmd._warn_orphaned_update_autostashes(["git"], tmp_path)+ assert count == 0+++def test_git_failure_is_nonfatal(tmp_path):+ # Not a git repo at all — must return 0, not raise.+ assert update_cmd._warn_orphaned_update_autostashes(["git"], tmp_path) == 0