Personal AI, On Personal Devices
Python
fix(install): recover release versions from shallow checkouts (#945)
Elliot Slusky4387c0f67067
diff --git a/deploy/windows/install.ps1 b/deploy/windows/install.ps1index 10681988..16732715 100644--- a/deploy/windows/install.ps1+++ b/deploy/windows/install.ps1@@ -276,7 +276,13 @@ if (Test-Path (Join-Path $srcDir '.git')) {}} else {Write-Info "Cloning $repoUrl..."- & $gitExe clone --depth 1 $repoUrl $srcDir+ # Preserve history without partial-clone lazy fetches from local sources,+ # which may themselves be shallow. Remote sources can omit old blobs.+ if ($repoUrl -like 'file://*' -or (Test-Path -LiteralPath $repoUrl -ErrorAction SilentlyContinue)) {+ & $gitExe clone $repoUrl $srcDir+ } else {+ & $gitExe clone --filter=blob:none $repoUrl $srcDir+ }if ($LASTEXITCODE -ne 0) { Write-Fail "git clone failed" }Write-Ok "Cloned to $srcDir"}diff --git a/docs/getting-started/install.md b/docs/getting-started/install.mdindex dc8283aa..c2326d23 100644--- a/docs/getting-started/install.md+++ b/docs/getting-started/install.md@@ -97,10 +97,17 @@ Removes `~/.openjarvis/`, `~/.local/bin/jarvis`, and `~/.local/bin/jarvis-uninst## Updating```bash-jarvis update+jarvis self-update```-Pulls the latest source, refreshes the editable install, and rebuilds the Rust extension in the background. Models are not touched.+Fetches release-tag history, pulls the latest source with a fast-forward-only+update, and rebuilds OpenJarvis in the Python environment that launched Jarvis.+Previously installed extras are preserved. Older shallow installs are repaired+automatically so `jarvis --version` reports a version derived from release tags.++Use `jarvis self-update --check` to preview the update plan, or `--yes` to skip+the confirmation prompt. If Git reports a conflict or diverged branch, resolve+it before retrying; self-update does not reset local changes.## Troubleshootingdiff --git a/scripts/install/install.sh b/scripts/install/install.shindex 0738b748..e20d9105 100755--- a/scripts/install/install.sh+++ b/scripts/install/install.sh@@ -448,7 +448,13 @@ clone_repo() {echo " repo already at $SRC_DIR"return 0fi- git clone --depth 1 "$OPENJARVIS_REPO_URL" "$SRC_DIR"+ # Keep commit/tag history for hatch-vcs. Local sources may themselves be+ # shallow and cannot safely serve a partial clone's lazy object fetches.+ if [[ "$OPENJARVIS_REPO_URL" == file://* || -e "$OPENJARVIS_REPO_URL" ]]; then+ git clone "$OPENJARVIS_REPO_URL" "$SRC_DIR"+ else+ git clone --filter=blob:none "$OPENJARVIS_REPO_URL" "$SRC_DIR"+ fi}copy_scripts() {diff --git a/src/openjarvis/cli/_install_detect.py b/src/openjarvis/cli/_install_detect.pyindex 716a777a..7c2613ce 100644--- a/src/openjarvis/cli/_install_detect.py+++ b/src/openjarvis/cli/_install_detect.py@@ -10,10 +10,9 @@ Three install paths are supported today:``uv tool upgrade openjarvis``.- **Editable git checkout** (``uv sync`` / ``pip install -e .`` from acloned repo). The package's ``__file__`` is inside a working tree- with a ``.git`` directory at the repo root. Upgrade with- ``git pull && uv sync --inexact`` from the checkout. ``--inexact`` is- important here: a bare ``uv sync`` removes packages installed by extras or- dependency groups that are not part of the base project.+ with a ``.git`` directory at the repo root. ``jarvis self-update`` repairs+ shallow Git history, fast-forwards the checkout, and rebuilds package metadata+ in the running environment without removing extras.We detect by inspecting ``openjarvis.__file__``. If we can't tell withconfidence we fall back to the PyPI command — that's the most common@@ -70,7 +69,7 @@ def detect_install() -> InstallInfo:if (candidate / ".git").exists() and (candidate / "pyproject.toml").exists():return InstallInfo(kind="editable-git",- upgrade_command=(f"cd {candidate} && git pull && uv sync --inexact"),+ upgrade_command="jarvis self-update",repo_root=candidate,)if candidate.parent == candidate:diff --git a/src/openjarvis/cli/_version_check.py b/src/openjarvis/cli/_version_check.pyindex dc01f6c5..7b61757d 100644--- a/src/openjarvis/cli/_version_check.py+++ b/src/openjarvis/cli/_version_check.py@@ -119,6 +119,10 @@ def _do_check() -> None:import openjarviscurrent = openjarvis.__version__+ # A source-build placeholder is not an old release. Comparing it with PyPI+ # creates a permanent upgrade prompt even when Git is already up to date.+ if "unknown" in current.lower():+ returnlatest = _get_latest_version(current)if latest is None:return@@ -130,11 +134,14 @@ def _do_check() -> None:from openjarvis.cli._install_detect import detect_installcmd = detect_install().upgrade_command+ alternative = (+ "" if cmd == "jarvis self-update" else "Or run: jarvis self-update\n"+ )sys.stderr.write(f"\033[33mA new version of OpenJarvis is available "f"(v{current} → v{latest})\n"f"Update: {cmd}\n"- f"Or run: jarvis self-update\033[0m\n\n"+ f"{alternative}\033[0m\n")except InvalidVersion:passdiff --git a/src/openjarvis/cli/self_update_cmd.py b/src/openjarvis/cli/self_update_cmd.pyindex 3004b744..7a9b9b12 100644--- a/src/openjarvis/cli/self_update_cmd.py+++ b/src/openjarvis/cli/self_update_cmd.py@@ -4,9 +4,9 @@ Runs the right upgrade command for how the user installed OpenJarvis:- PyPI installs get ``pip install --upgrade openjarvis``.- uv-tool installs get ``uv tool upgrade openjarvis``.-- Editable git checkouts get ``git pull && uv sync --inexact`` in the checkout.- The inexact sync preserves packages previously installed through extras and- dependency groups.+- Editable Git checkouts recover release-tag history, fast-forward, and rebuild+ OpenJarvis in the running environment. The inexact sync preserves packages+ previously installed through extras and dependency groups.The detection logic is shared with the post-command "new versionavailable" hint in ``_version_check.py`` so both surfaces stay in sync.@@ -14,9 +14,11 @@ available" hint in ``_version_check.py`` so both surfaces stay in sync.from __future__ import annotations+import osimport shleximport subprocessimport sys+from pathlib import Pathimport click@@ -24,6 +26,69 @@ import openjarvisfrom openjarvis.cli._install_detect import detect_install+def _update_git_checkout(repo_root: Path) -> int:+ """Repair version history and update without discarding local work."""+ shallow = subprocess.run(+ ["git", "rev-parse", "--is-shallow-repository"],+ cwd=repo_root,+ capture_output=True,+ text=True,+ )+ if shallow.returncode:+ click.echo(shallow.stderr, err=True)+ return shallow.returncode+ if shallow.stdout.strip() not in {"true", "false"}:+ click.echo("Could not determine whether the checkout is shallow.", err=True)+ return 1++ # Fetching tags alone cannot make tags beyond a shallow boundary reachable.+ fetch = ["git", "fetch", "--tags"]+ if shallow.stdout.strip() == "true":+ fetch.append("--unshallow")+ click.echo("Restoring Git history for release version detection...")+ for command in (fetch, ["git", "pull", "--ff-only"]):+ result = subprocess.run(command, cwd=repo_root)+ if result.returncode:+ return result.returncode++ # Version metadata is baked at install time, so an up-to-date checkout also+ # needs a rebuild after history repair. The Unix installer keeps its venv+ # beside src/, not inside it: target the running venv, never a new src/.venv.+ click.echo("Rebuilding OpenJarvis in the running Python environment...")+ if sys.prefix != sys.base_prefix:+ result = subprocess.run(+ [+ "uv",+ "sync",+ "--python",+ sys.executable,+ "--inexact",+ "--reinstall-package",+ "openjarvis",+ ],+ cwd=repo_root,+ env={**os.environ, "UV_PROJECT_ENVIRONMENT": sys.prefix},+ )+ else:+ # Editable installs in a non-venv interpreter have no uv project+ # environment to sync. Reinstall into that same interpreter instead.+ result = subprocess.run(+ [+ "uv",+ "pip",+ "install",+ "--python",+ sys.executable,+ "--reinstall-package",+ "openjarvis",+ "-e",+ ".",+ ],+ cwd=repo_root,+ )+ return result.returncode++@click.command("self-update",help=(@@ -50,7 +115,14 @@ def self_update(check: bool, yes: bool) -> None:click.echo(f"Current OpenJarvis version: v{current}")click.echo(f"Install method: {info.kind}")- click.echo(f"Upgrade command: {info.upgrade_command}")+ if info.kind == "editable-git":+ click.echo(f"Repository: {info.repo_root}")+ click.echo(+ "Upgrade plan: restore release-tag history, git pull --ff-only, "+ "then rebuild OpenJarvis while preserving installed extras."+ )+ else:+ click.echo(f"Upgrade command: {info.upgrade_command}")if check:return@@ -68,24 +140,27 @@ def self_update(check: bool, yes: bool) -> None:click.echo("Aborted.")sys.exit(1)- click.echo(f"\n→ {info.upgrade_command}\n")-- # ``editable-git`` uses shell features (``&&``); the others are- # simple argv-style commands. Use ``shell=True`` only for the- # editable case to keep the surface small. The command itself is- # constructed from a trusted, locally-detected path — no user- # input flows into it.if info.kind == "editable-git":- result = subprocess.run(info.upgrade_command, shell=True)+ click.echo("\nUpdating the source checkout...\n")else:- result = subprocess.run(shlex.split(info.upgrade_command))-- if result.returncode != 0:+ click.echo(f"\n→ {info.upgrade_command}\n")++ try:+ if info.kind == "editable-git":+ if info.repo_root is None:+ raise click.ClickException("Could not locate the editable checkout.")+ returncode = _update_git_checkout(info.repo_root)+ else:+ returncode = subprocess.run(shlex.split(info.upgrade_command)).returncode+ except OSError as exc:+ raise click.ClickException(f"Could not run the upgrade: {exc}") from exc++ if returncode != 0:click.echo(- f"\nUpgrade command exited with code {result.returncode}. "+ f"\nUpgrade command exited with code {returncode}. ""Inspect the output above for the failure mode.",err=True,)- sys.exit(result.returncode)+ sys.exit(returncode)click.echo("\nUpgrade complete. Re-run `jarvis --version` to confirm.")diff --git a/tests/cli/test_install_detect.py b/tests/cli/test_install_detect.pyindex 6034bb50..91a92da8 100644--- a/tests/cli/test_install_detect.py+++ b/tests/cli/test_install_detect.py@@ -34,8 +34,7 @@ def test_editable_git_install_detected(tmp_path, monkeypatch):info = detect_install()assert info.kind == "editable-git"- assert "git pull" in info.upgrade_command- assert info.upgrade_command.endswith("uv sync --inexact")+ assert info.upgrade_command == "jarvis self-update"assert info.repo_root == repodiff --git a/tests/cli/test_self_update.py b/tests/cli/test_self_update.pyindex b9d8df62..8afb5a74 100644--- a/tests/cli/test_self_update.py+++ b/tests/cli/test_self_update.py@@ -7,8 +7,11 @@ unit test; the subprocess call is mocked.from __future__ import annotations+from pathlib import Path+from subprocess import CompletedProcessfrom unittest.mock import MagicMock, patch+import pytestfrom click.testing import CliRunnerfrom openjarvis.cli._install_detect import InstallInfo@@ -21,9 +24,10 @@ def _mock_info(kind: str = "pypi") -> InstallInfo:upgrade_command={"pypi": "pip install --upgrade openjarvis","uv-tool": "uv tool upgrade openjarvis",- "editable-git": "cd /tmp/repo && git pull && uv sync --inexact",+ "editable-git": "jarvis self-update","unknown": "pip install --upgrade openjarvis",}[kind],+ repo_root=Path("/tmp/repo with spaces") if kind == "editable-git" else None,)@@ -39,11 +43,12 @@ def test_check_flag_prints_command_and_exits_clean():assert "Install method: pypi" in result.output-def test_check_does_not_invoke_subprocess():[email protected]("kind", ["pypi", "editable-git"])+def test_check_does_not_invoke_subprocess(kind):with (patch("openjarvis.cli.self_update_cmd.detect_install",- return_value=_mock_info("pypi"),+ return_value=_mock_info(kind),),patch("openjarvis.cli.self_update_cmd.subprocess.run") as mock_run,):@@ -72,9 +77,14 @@ def test_yes_skips_confirmation_and_runs():assert args[0] == ["pip", "install", "--upgrade", "openjarvis"]-def test_editable_git_uses_shell_true():- """The git path uses `&&` so shell=True is needed; the others don't."""- mock_proc = MagicMock(returncode=0)[email protected]("shallow", ["true", "false"])+def test_editable_git_repairs_history_and_rebuilds_active_venv(monkeypatch, shallow):+ """Recover tags before rebuilding even when Git has no new commits."""+ mock_proc = CompletedProcess([], 0, stdout=shallow + "\n", stderr="")+ monkeypatch.setattr("openjarvis.cli.self_update_cmd.sys.prefix", "/managed venv")+ monkeypatch.setattr(+ "openjarvis.cli.self_update_cmd.sys.executable", "/managed venv/bin/python"+ )with (patch("openjarvis.cli.self_update_cmd.detect_install",@@ -85,14 +95,38 @@ def test_editable_git_uses_shell_true():return_value=mock_proc,) as mock_run,):- CliRunner().invoke(self_update, ["-y"])- _, kwargs = mock_run.call_args- assert kwargs.get("shell") is True---def test_editable_git_preserves_extra_dependencies():- """The update sync must not remove packages from prior extras/groups."""- mock_proc = MagicMock(returncode=0)+ result = CliRunner().invoke(self_update, ["-y"])+ assert result.exit_code == 0, result.output+ commands = [call.args[0] for call in mock_run.call_args_list]+ assert commands[0] == ["git", "rev-parse", "--is-shallow-repository"]+ assert commands[1] == ["git", "fetch", "--tags"] + (+ ["--unshallow"] if shallow == "true" else []+ )+ assert commands[2] == ["git", "pull", "--ff-only"]+ assert commands[3] == [+ "uv",+ "sync",+ "--python",+ "/managed venv/bin/python",+ "--inexact",+ "--reinstall-package",+ "openjarvis",+ ]+ for call in mock_run.call_args_list:+ assert call.kwargs.get("shell") is not True+ assert call.kwargs["cwd"] == _mock_info("editable-git").repo_root+ assert mock_run.call_args.kwargs["env"]["UV_PROJECT_ENVIRONMENT"] == "/managed venv"+++def test_editable_global_install_rebuilds_running_interpreter(monkeypatch):+ mock_proc = CompletedProcess([], 0, stdout="false\n", stderr="")+ monkeypatch.setattr("openjarvis.cli.self_update_cmd.sys.prefix", "/global python")+ monkeypatch.setattr(+ "openjarvis.cli.self_update_cmd.sys.base_prefix", "/global python"+ )+ monkeypatch.setattr(+ "openjarvis.cli.self_update_cmd.sys.executable", "/global python/python"+ )with (patch("openjarvis.cli.self_update_cmd.detect_install",@@ -106,8 +140,37 @@ def test_editable_git_preserves_extra_dependencies():result = CliRunner().invoke(self_update, ["-y"])assert result.exit_code == 0- assert "uv sync --inexact" in result.output- assert "uv sync --inexact" in mock_run.call_args.args[0]+ assert mock_run.call_args.args[0] == [+ "uv",+ "pip",+ "install",+ "--python",+ "/global python/python",+ "--reinstall-package",+ "openjarvis",+ "-e",+ ".",+ ]++[email protected]("failed_step", [0, 1, 2, 3])+def test_editable_upgrade_stops_on_failure(monkeypatch, failed_step):+ monkeypatch.setattr("openjarvis.cli.self_update_cmd.sys.prefix", "/managed venv")+ responses = [CompletedProcess([], 0, stdout="true\n", stderr="")] * failed_step+ responses.append(CompletedProcess([], 7, stdout="", stderr="failed"))+ with (+ patch(+ "openjarvis.cli.self_update_cmd.detect_install",+ return_value=_mock_info("editable-git"),+ ),+ patch(+ "openjarvis.cli.self_update_cmd.subprocess.run", side_effect=responses+ ) as run,+ ):+ result = CliRunner().invoke(self_update, ["-y"])+ assert result.exit_code == 7+ assert run.call_count == failed_step + 1+ assert "Upgrade complete" not in result.outputdef test_failed_upgrade_propagates_exit_code():diff --git a/tests/cli/test_version_check.py b/tests/cli/test_version_check.pyindex 3df2d442..456ea447 100644--- a/tests/cli/test_version_check.py+++ b/tests/cli/test_version_check.py@@ -221,6 +221,17 @@ class TestGetLatestVersion:class TestCheckForUpdates:+ @pytest.mark.parametrize(+ "version", ["0.0.0+unknown", "0.0.1.dev1+unknown.gc1af3c94"]+ )+ def test_unknown_source_version_never_prompts_or_fetches(+ self, monkeypatch, version+ ):+ monkeypatch.setattr("openjarvis.__version__", version)+ with patch("openjarvis.cli._version_check._get_latest_version") as latest:+ _version_check._do_check()+ latest.assert_not_called()+@patch("openjarvis.cli._version_check._do_check")def test_runs_for_ask_command(self, mock_do):check_for_updates("ask")diff --git a/tests/install/test_version_history.py b/tests/install/test_version_history.pynew file mode 100644index 00000000..7208c94a--- /dev/null+++ b/tests/install/test_version_history.py@@ -0,0 +1,245 @@+"""Exercise installer clone flags and update repair against real local Git repos."""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest++from openjarvis.cli.self_update_cmd import _update_git_checkout++ROOT = Path(__file__).resolve().parents[2]+_RUN = subprocess.run+++def _git(repo: Path, *args: str) -> str:+ return _RUN(+ ["git", "-C", str(repo), *args],+ check=True,+ capture_output=True,+ text=True,+ timeout=30,+ ).stdout.strip()+++def _commit(repo: Path, name: str, content: str) -> None:+ (repo / name).write_text(content)+ _git(repo, "add", name)+ _git(repo, "-c", "commit.gpgsign=false", "commit", "-m", name)+++def tagged_repo(tmp_path: Path) -> Path:+ repo = tmp_path / "source"+ repo.mkdir()+ _git(repo, "init", "-b", "main")+ _git(repo, "config", "user.name", "Version Test")+ _git(repo, "config", "user.email", "[email protected]")+ _commit(repo, "README.md", "release\n")+ _git(repo, "-c", "tag.gpgsign=false", "tag", "v1.0.3")+ _commit(repo, "new-file.txt", "development commit after the release\n")+ return repo++[email protected](params=["bash", "powershell"])+def installer(request):+ if request.param == "bash":+ if sys.platform == "win32":+ pytest.skip("Native Windows uses the PowerShell installer")+ executable = shutil.which("bash")+ else:+ executable = shutil.which("pwsh") or shutil.which("powershell")+ if not executable:+ pytest.skip(f"{request.param} is not installed")+ return request.param, executable+++def _installer_clone(installer, source, clone, cwd, *, env_extra=None):+ """Execute the shipped clone branch without bootstrapping an entire install."""+ kind, executable = installer+ env = {+ **os.environ,+ "OPENJARVIS_REPO_URL": source,+ "SRC_DIR": str(clone),+ "FORCE": "0",+ }+ env.update(env_extra or {})+ if kind == "bash":+ script = (ROOT / "scripts/install/install.sh").read_text()+ start = script.index("clone_repo() {\n")+ end = script.index("\n}\n", start) + 2+ command = [+ executable,+ "-c",+ "set -euo pipefail\n" + script[start:end] + "\nclone_repo",+ ]+ else:+ script = (ROOT / "deploy/windows/install.ps1").read_text()+ start = script.index(" if ($repoUrl -like 'file://*'")+ end = script.index(" if ($LASTEXITCODE", start)+ body = (+ "$ErrorActionPreference = 'Stop'\n"+ "$repoUrl = $env:OPENJARVIS_REPO_URL\n"+ "$srcDir = $env:SRC_DIR\n"+ "$gitExe = (Get-Command git).Source\n"+ + script[start:end]+ + "\nexit $LASTEXITCODE\n"+ )+ command = [executable, "-NoProfile", "-NonInteractive", "-Command", body]+ return _RUN(+ command,+ env=env,+ cwd=cwd,+ capture_output=True,+ text=True,+ timeout=30,+ check=True,+ )++[email protected]("source_kind", ["path", "file-url", "remote-url"])+def test_installer_clone_retains_reachable_release_tag(+ tagged_repo: Path,+ tmp_path: Path,+ installer,+ source_kind: str,+) -> None:+ clone = tmp_path / "fresh install"+ source = str(tagged_repo) if source_kind == "path" else tagged_repo.as_uri()+ env_extra = {}+ if source_kind == "remote-url":+ # Exercise remote argument selection without network access. This full+ # local server explicitly supports filtering, unlike shallow CI clones.+ _git(tagged_repo, "config", "uploadpack.allowFilter", "true")+ source = "https://example.invalid/openjarvis.git"+ env_extra = {+ "GIT_CONFIG_COUNT": "1",+ "GIT_CONFIG_KEY_0": f"url.{tagged_repo.as_uri()}.insteadOf",+ "GIT_CONFIG_VALUE_0": source,+ }+ _installer_clone(installer, source, clone, tmp_path, env_extra=env_extra)++ assert _git(clone, "rev-parse", "--is-shallow-repository") == "false"+ assert _git(clone, "describe", "--tags", "--long").startswith("v1.0.3-1-g")+ config = _git(clone, "config", "--local", "--list")+ assert ("remote.origin.promisor=true" in config) is (source_kind == "remote-url")++[email protected]("source_kind", ["path", "relative-path", "file-url"])+def test_installer_clones_shallow_local_source_without_lazy_fetch_recursion(+ tagged_repo: Path,+ tmp_path: Path,+ installer,+ source_kind: str,+) -> None:+ source_repo = tmp_path / "shallow [local] source"+ _git(tmp_path, "clone", "--depth", "1", tagged_repo.as_uri(), str(source_repo))+ assert _git(source_repo, "rev-parse", "--is-shallow-repository") == "true"+ source = {+ "path": str(source_repo),+ "relative-path": source_repo.name,+ "file-url": source_repo.as_uri(),+ }[source_kind]+ clone = tmp_path / "installed from shallow source"+ trace_path = tmp_path / "clone-trace.jsonl"+ completed = _installer_clone(+ installer,+ source,+ clone,+ tmp_path,+ env_extra={"GIT_TRACE2_EVENT": str(trace_path)},+ )++ assert "filtering not recognized" not in completed.stderr+ assert "unable to fork" not in completed.stderr+ assert "shallow roots" not in completed.stderr+ events = [json.loads(line) for line in trace_path.read_text().splitlines()]+ upload_packs = [+ event+ for event in events+ if event.get("event") == "child_start"+ and any("upload-pack" in arg for arg in event.get("argv", []))+ ]+ assert len(upload_packs) <= 1, (+ "Local clone must not recursively fetch missing objects"+ )+ assert _git(clone, "rev-parse", "HEAD") == _git(source_repo, "rev-parse", "HEAD")+ assert _git(clone, "rev-list", "--all", "--count") == _git(+ source_repo, "rev-list", "--all", "--count"+ )+ assert (clone / "README.md").read_text() == "release\n"+ config = _git(clone, "config", "--local", "--list")+ assert "promisor" not in config+ assert "partialclone" not in config.lower()+ assert not list((clone / ".git" / "objects" / "pack").glob("*.promisor"))++[email protected]("shallow", [True, False])+def test_update_recovers_version_before_reinstall_and_preserves_user_files(+ tagged_repo: Path,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ shallow: bool,+) -> None:+ clone = tmp_path / "installed repo with spaces"+ flags = ["--depth", "1"] if shallow else ["--no-tags"]+ _git(tmp_path, "clone", *flags, tagged_repo.as_uri(), str(clone))+ assert _git(clone, "tag") == ""+ user_file = clone / "my settings.txt"+ user_file.write_text("preserve this\n")+ head = _git(clone, "rev-parse", "HEAD")+ active_venv = tmp_path / "managed environment"+ monkeypatch.setattr("openjarvis.cli.self_update_cmd.sys.prefix", str(active_venv))+ rebuild_versions: list[str] = []++ def run(command, **kwargs):+ if command[0] != "uv":+ return _RUN(command, **kwargs)+ assert command == [+ "uv",+ "sync",+ "--python",+ sys.executable,+ "--inexact",+ "--reinstall-package",+ "openjarvis",+ ]+ assert kwargs["env"]["UV_PROJECT_ENVIRONMENT"] == str(active_venv)+ rebuild_versions.append(_git(clone, "describe", "--tags", "--long"))+ return subprocess.CompletedProcess(command, 0)++ monkeypatch.setattr("openjarvis.cli.self_update_cmd.subprocess.run", run)+ assert _update_git_checkout(clone) == 0+ assert _git(clone, "rev-parse", "--is-shallow-repository") == "false"+ assert _git(clone, "rev-parse", "HEAD") == head+ assert user_file.read_text() == "preserve this\n"+ assert len(rebuild_versions) == 1+ assert rebuild_versions[0].startswith("v1.0.3-1-g")+++def test_update_does_not_merge_or_reinstall_diverged_checkout(+ tagged_repo: Path,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ clone = tmp_path / "diverged"+ _git(tmp_path, "clone", tagged_repo.as_uri(), str(clone))+ _git(clone, "config", "user.name", "Version Test")+ _git(clone, "config", "user.email", "[email protected]")+ _commit(clone, "local.txt", "local work\n")+ _commit(tagged_repo, "remote.txt", "upstream work\n")+ original_head = _git(clone, "rev-parse", "HEAD")++ def run(command, **kwargs):+ assert command[0] != "uv", "Failed Git update must not report a rebuilt package"+ return _RUN(command, **kwargs)++ monkeypatch.setattr("openjarvis.cli.self_update_cmd.subprocess.run", run)+ assert _update_git_checkout(clone) != 0+ assert _git(clone, "rev-parse", "HEAD") == original_head+ assert (clone / "local.txt").read_text() == "local work\n"