The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): diagnose a damaged checkout from the checkout, not the stderr
Teknium3a9d585e4f1a
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex b9e698c4683..34d8be0ff08 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -680,7 +680,7 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False, chgit_cmd, root, branch, ["--depth", "1"] if is_shallow else [],)if fetch_result.returncode != 0:- _print_fetch_failure(fetch_result.stderr)+ _print_fetch_failure(fetch_result.stderr, git_cmd=git_cmd, root=root)sys.exit(1)if is_shallow:_check.repair_shallow_grafts(root)@@ -1916,7 +1916,7 @@ def _cmd_update_impl(args, gateway_mode: bool):if is_partial_clone_pack_objects_crash(fetch_result.stderr or ""):print("✗ git still crashed after marking this checkout's packs. See 'Fetch fails with"" should_include_obj' in https://hermes-agent.nousresearch.com/docs/getting-started/updating")- _print_fetch_failure(fetch_result.stderr)+ _print_fetch_failure(fetch_result.stderr, git_cmd=git_cmd, root=_m().PROJECT_ROOT)_m()._resume_windows_gateways_after_update(_windows_gateway_resume)_record_stop("git_timeout" if fetch_result.returncode == 124 else "disk_full"if "No space left on device" in (fetch_result.stderr or "") else "fetch_failed")diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex 3160ff7ede5..95a241cf605 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -6,6 +6,8 @@ test patches on ``update_cmd`` stay effective)."""import logging+import os+import shlexfrom contextlib import nullcontext, suppressimport subprocessimport sys@@ -496,26 +498,39 @@ def _has_http_code(stderr: str, *codes: str) -> bool:return any(f"HTTP {code}" in stderr or f"returned error: {code}" in stderr for code in codes)-def _damaged_checkout_message() -> str:- from hermes_cli.update_cmd_maint import _REINSTALL_ONE_LINER-- return ("✗ This Hermes checkout's git data is damaged (git no longer recognizes its .git folder),"+def _damaged_checkout_message(root: Path) -> str:+ """The repair for a checkout git rejects: the installer pointed at THIS checkout (a bare one-liner+ would rebuild the default directory and leave a ``--dir`` install broken)."""+ if sys.platform == "win32":+ quoted = "'" + str(root).replace("'", "''") + "'"+ repair = ("& ([scriptblock]::Create((irm https://hermes-agent.nousresearch.com/install.ps1)))"+ f" -InstallDir {quoted}")+ else:+ repair = f"curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash -s -- --dir {shlex.quote(str(root))}"+ return (f"✗ This Hermes checkout's git data is damaged (git no longer recognizes {root / '.git'}),"" so it cannot be updated in place.\n"" Run the installer again to repair it; it moves the damaged checkout aside and keeps"- f" your config and chats:\n {_REINSTALL_ONE_LINER[sys.platform == 'win32']}")+ f" your config and chats:\n {repair}")+++def _checkout_rejected_by_git(stderr: str, git_cmd, root: Path) -> bool:+ """The fetch failed because git cannot open *root* itself, not because of its remote.++ git prints the same ``fatal: not a git repository`` for a remote whose ``.git`` is broken, so the+ stderr line alone is not proof: the checkout must also fail to resolve as its own top level.+ """+ if not any(line.startswith("fatal: not a git repository") for line in stderr.splitlines()):+ return False+ top = _git_run(git_cmd, ["rev-parse", "--show-toplevel"], cwd=root)+ return top.returncode != 0 or os.path.normcase(os.path.realpath(top.stdout.strip())) != os.path.normcase(+ os.path.realpath(root))# Ordered (predicate, diagnosis): curl reports HTTP errors as ``unable to access '<url>': ... error: 429``,# so rate-limit/outage checks must run BEFORE the generic "unable to access" check. An anonymous fetch# answered with HTTP 401 ("could not read Username") is GitHub during an outage (or a renamed/private-# repo), not a user credentials problem. A diagnosis may be a callable when it depends on the host.+# repo), not a user credentials problem._FETCH_FAILURE_RULES = (- # The updater only fetches when .git exists, so local git saying this about itself is a .git it- # rejects (empty dir, lost HEAD): no retry can work and the ZIP fallback cannot tell user edits- # apart, but the installer can. Line-anchored: a remote's own refusal arrives as "'<path>' does- # not appear to be a git repository" or relayed under "remote: ", and reinstalling cannot fix it.- (lambda s: any(line.startswith("fatal: not a git repository") for line in s.splitlines()),- _damaged_checkout_message),(lambda s: _has_http_code(s, "429") or "rate limit" in s.lower(),"✗ GitHub is rate limiting requests or having an outage (HTTP 429) — try again in 5 minutes."),(lambda s: _has_http_code(s, "500", "502", "503", "504"),@@ -541,14 +556,16 @@ _FETCH_FAILURE_RULES = (def _classify_fetch_failure(stderr: str) -> str:"""Map git-fetch stderr to a one-line diagnosis (caller also prints the raw first line)."""- message = next((message for matches, message in _FETCH_FAILURE_RULES if matches(stderr)), "✗ Failed to fetch updates from origin.")- return message() if callable(message) else message+ return next((message for matches, message in _FETCH_FAILURE_RULES if matches(stderr)), "✗ Failed to fetch updates from origin.")-def _print_fetch_failure(stderr: str) -> None:- """Print the classified diagnosis plus bounded raw stderr for diagnosis."""+def _print_fetch_failure(stderr: str, *, git_cmd=None, root: Optional[Path] = None) -> None:+ """Print the classified diagnosis plus bounded raw stderr for diagnosis. With *root*, a checkout+ git rejects (no fetch can ever work; the ZIP fallback cannot tell user edits apart) gets the+ installer repair instead."""stderr = (stderr or "").strip()- print(_classify_fetch_failure(stderr))+ damaged = root is not None and _checkout_rejected_by_git(stderr, git_cmd, Path(root))+ print(_damaged_checkout_message(Path(root)) if damaged else _classify_fetch_failure(stderr))if stderr:lines = stderr.splitlines()for line in lines[:15]:diff --git a/tests/hermes_cli/test_update_fetch_failure_classifier.py b/tests/hermes_cli/test_update_fetch_failure_classifier.pyindex b1c63b3325d..1dd9440573d 100644--- a/tests/hermes_cli/test_update_fetch_failure_classifier.py+++ b/tests/hermes_cli/test_update_fetch_failure_classifier.py@@ -9,8 +9,9 @@ stderr line must always be printed alongside the diagnosis.import osimport subprocess+from pathlib import Path-from hermes_cli import update_cmd+from hermes_cli import update_cmd, update_cmd_gitRATE_LIMIT_STDERR = (@@ -81,26 +82,31 @@ class TestClassifyFetchFailure:assert "SSH authentication failed" in msgassert "https://github.com/NousResearch/hermes-agent.git" in msg- def test_a_git_dir_git_rejects_names_the_installer_repair(self, tmp_path):- # The updater fetches only when .git exists; git rejecting it (here an empty .git) cannot- # be retried away, and the generic "Failed to fetch" left users with no way out.- (tmp_path / ".git").mkdir()- stderr = subprocess.run(["git", "fetch", "origin"], cwd=tmp_path, capture_output=True, check=False,- text=True, encoding="utf-8", errors="replace",- env={**os.environ, "GIT_CEILING_DIRECTORIES": str(tmp_path.parent)}).stderr- msg = update_cmd._classify_fetch_failure(stderr)- assert "damaged" in msg- assert "hermes-agent.nousresearch.com/install." in msg-- # A healthy checkout whose REMOTE is the broken one: reinstalling Hermes cannot fix that.- healthy = tmp_path / "healthy"- healthy.mkdir()+ def test_only_a_checkout_git_rejects_gets_the_installer_repair(self, tmp_path, capsys):+ # The updater fetches only when .git exists; git rejecting the checkout itself (here an+ # empty .git) cannot be retried away. A remote with a dangling `.git` file makes git print+ # the same "fatal: not a git repository" line, and reinstalling Hermes cannot fix that.+ def fetch(cwd: Path, *source: str) -> str:+ return subprocess.run(["git", "fetch", *source], cwd=cwd, capture_output=True, check=False,+ text=True, encoding="utf-8", errors="replace",+ env={**os.environ, "GIT_CEILING_DIRECTORIES": str(tmp_path)}).stderr++ damaged = tmp_path / "custom-dir" / "hermes-agent"+ (damaged / ".git").mkdir(parents=True)+ update_cmd_git._print_fetch_failure(fetch(damaged, "origin"), git_cmd=["git"], root=damaged)+ out = capsys.readouterr().out+ assert "damaged" in out and "hermes-agent.nousresearch.com/install." in out+ assert str(damaged) in out # the repair targets THIS checkout, not the default directory++ healthy, remote = tmp_path / "healthy", tmp_path / "remote"subprocess.run(["git", "init", "-q", str(healthy)], check=True)- remote = subprocess.run(["git", "fetch", str(tmp_path)], cwd=healthy, capture_output=True, check=False,- text=True, encoding="utf-8", errors="replace").stderr- for stderr in (remote, "remote: fatal: not a git repository (or any of the parent directories): .git\n"- "fatal: Could not read from remote repository."):- assert "damaged" not in update_cmd._classify_fetch_failure(stderr), stderr+ remote.mkdir()+ (remote / ".git").write_text(f"gitdir: {tmp_path / 'gone'}\n", encoding="utf-8")+ relayed = "remote: fatal: not a git repository (or any of the parent directories): .git"+ for stderr in (fetch(healthy, str(remote)), relayed):+ update_cmd_git._print_fetch_failure(stderr, git_cmd=["git"], root=healthy)+ out = capsys.readouterr().out+ assert "damaged" not in out, outdef test_ssh_host_key_failure_reports_ssh_auth(self):msg = update_cmd._classify_fetch_failure(diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex 8869da386ca..0b72940538f 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -227,11 +227,13 @@ On Windows, a Desktop reopened during packaging is stopped again immediately bef`hermes update` stops with "This Hermes checkout's git data is damaged" when the install's `.git` folder is still there but git no longer accepts it: a lost or empty `HEAD`, or a `.git` file pointing at a folder that is gone. A killed update, a crash mid-write, or a sync or antivirus tool touching `.git` can leave it that way. No update can fetch on such a checkout. Gateways the update paused are started again on the unchanged code, since nothing was written.-Run the installer again to repair it. It moves the damaged checkout aside as `hermes-agent.broken-<timestamp>` (nothing is deleted) and clones fresh; your config, sessions and other data live outside the checkout and are kept:+Run the installer again to repair it. It moves the damaged checkout aside as `hermes-agent.broken-<timestamp>` (nothing is deleted) and clones fresh; your config, sessions and other data live outside the checkout and are kept. The error prints the exact command for your checkout. For the default location it is:- Linux / macOS / WSL2: `curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash`- Windows (PowerShell): `iex (irm https://hermes-agent.nousresearch.com/install.ps1)`+A checkout installed somewhere else needs its directory passed again (`bash -s -- --dir <path>` on Linux/macOS, `-InstallDir <path>` on Windows), as in the printed command; without it the installer repairs the default location instead.+Once Hermes works again you can delete the `.broken-*` folder.### Fetch fails with `should_include_obj should only be called on existing objects`