Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(update): seed a linked worktree whose base has synced past its fork point (#4673)
Raghav Chamadiya6a123d957bbf
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 330c8396d..58a47ddaa 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -763,7 +763,9 @@ def _prepare_repo(repo_path: Path) -> None:f"[dim]\\[worktree][/dim] Unindexed linked worktree of {wt_base}; "f"seeding its index.")- seed_index_from_base(root=repo_path, repo_paths=[repo_path], seed_base=wt_base)+ seed_index_from_base(+ root=repo_path, repo_paths=[repo_path], seed_base=wt_base, require_ancestor=False+ )ensure_repowise_dir(repo_path)diff --git a/packages/cli/src/repowise/cli/worktree.py b/packages/cli/src/repowise/cli/worktree.pyindex 68d9ddffe..6e062b6a5 100644--- a/packages/cli/src/repowise/cli/worktree.py+++ b/packages/cli/src/repowise/cli/worktree.py@@ -16,7 +16,13 @@ import timeimport uuidfrom pathlib import Path-from repowise.cli.helpers import as_commit_id, console, warn+from repowise.cli.helpers import (+ UPDATE_LOCK_FILENAME,+ UPDATE_QUEUED_FILENAME,+ as_commit_id,+ console,+ warn,+)_SEED_TEMPDIR_STALENESS_SECS = 3600@@ -79,6 +85,23 @@ def sweep_stale_seed_backups(paths: list[Path]) -> None:pass+def _seed_commit_refusal(repo: Path, commit: str, *, require_ancestor: bool) -> str | None:+ """Why *commit* cannot start a seeded index in *repo*, or None when it can."""+ if as_commit_id(commit) is None:+ return "is not a commit id"+ if require_ancestor:+ args = ["merge-base", "--is-ancestor", "--end-of-options", commit, "HEAD"]+ refusal = "is not an ancestor of worktree HEAD"+ else:+ args = ["cat-file", "-e", f"{commit}^{{commit}}"]+ refusal = "is not in this repository"+ try:+ subprocess.check_call(["git", *args], cwd=repo, stderr=subprocess.DEVNULL)+ except (OSError, subprocess.CalledProcessError):+ return refusal+ return None++def _get_initial_commit(p: Path) -> str:return _git_output(["rev-list", "--max-parents=0", "HEAD"], p)@@ -152,6 +175,7 @@ def seed_index_from_base(seed_base: Path,include_submodules: bool | None = None,dry_run: bool = False,+ require_ancestor: bool = True,) -> bool:"""Copy ``.repowise/`` from a base checkout into each target repo.@@ -164,6 +188,11 @@ def seed_index_from_base(``include_submodules`` is the caller's CLI flag; pass None to skip theconflict warning (update has no such flag).++ ``require_ancestor=False`` accepts any last_sync_commit the target repo+ has. ``update`` passes it: its catch-up diffs two trees, so a base that+ moved past the worktree's fork point is still a valid start, and update+ has no full init to fall back to."""sweep_stale_seed_backups([root, *repo_paths])@@ -202,19 +231,11 @@ def seed_index_from_base(success = Falsebreak- try:- if as_commit_id(last_sync_commit) is None:- raise subprocess.CalledProcessError(1, "git merge-base")- subprocess.check_call(- ["git", "merge-base", "--is-ancestor", "--end-of-options", last_sync_commit, "HEAD"],- cwd=r_path,- stderr=subprocess.DEVNULL,- )- except subprocess.CalledProcessError:+ refusal = _seed_commit_refusal(r_path, last_sync_commit, require_ancestor=require_ancestor)+ if refusal is not None:console.print(f"[yellow]Seed source {src_repo} last_sync_commit "- f"{last_sync_commit[:8]} is not an ancestor of worktree HEAD. "- f"Falling back to full init.[/yellow]"+ f"{last_sync_commit[:8]} {refusal}. Falling back to full init.[/yellow]")success = Falsebreak@@ -233,7 +254,14 @@ def seed_index_from_base(temp_dir = Path(tempfile.mkdtemp(prefix=".repowise-seed-", dir=r_path))temp_dirs.append((r_path, temp_dir))- shutil.copytree(src_repo / ".repowise", temp_dir, dirs_exist_ok=True)+ # The base's update markers belong to the base: a copied lock+ # would defer this checkout's update to a run that never covers it.+ shutil.copytree(+ src_repo / ".repowise",+ temp_dir,+ dirs_exist_ok=True,+ ignore=shutil.ignore_patterns(UPDATE_LOCK_FILENAME, UPDATE_QUEUED_FILENAME),+ )# Since config.yaml is copied atomically alongside state.json, the# config_fingerprint remains valid.diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.pyindex 8b8135a4b..08c89c386 100644--- a/tests/integration/test_cli.py+++ b/tests/integration/test_cli.py@@ -1452,6 +1452,53 @@ class TestInitSeedFrom:finally:_remove_worktree(git_work_repo, worktree_dir)+ def test_update_seeds_worktree_behind_its_base(self, git_work_repo, monkeypatch):+ """The base synced past the worktree's fork point: update still seeds.++ Its catch-up diffs two trees, so the base's last sync need not be an+ ancestor. This used to exit 1 with "No previous sync found".+ """+ import json++ from click.testing import CliRunner++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)++ r0 = CliRunner().invoke(+ cli, ["init", str(git_work_repo), "--index-only"], catch_exceptions=False+ )+ assert r0.exit_code == 0, r0.output++ worktree_dir = git_work_repo.parent / "behind-worktree"+ _git(["worktree", "add", "-b", "behind", str(worktree_dir), "HEAD"], git_work_repo)+ try:+ (git_work_repo / "base_only.py").write_text("x = 1\n", encoding="utf-8")+ _git(["add", "base_only.py"], git_work_repo)+ _git(["commit", "-m", "base moves on"], git_work_repo)+ r1 = CliRunner().invoke(+ cli, ["update", str(git_work_repo), "--index-only"], catch_exceptions=False+ )+ assert r1.exit_code == 0, r1.output++ (worktree_dir / "wt_only.py").write_text("y = 2\n", encoding="utf-8")+ _git(["add", "wt_only.py"], worktree_dir)+ _git(["commit", "-m", "worktree work"], worktree_dir)++ r2 = CliRunner().invoke(+ cli, ["update", str(worktree_dir), "--index-only"], catch_exceptions=False+ )+ assert r2.exit_code == 0, r2.output+ state = json.loads(+ (worktree_dir / ".repowise" / "state.json").read_text(encoding="utf-8")+ )+ assert state["last_sync_commit"] == _rev_parse(worktree_dir, "HEAD")+ db = worktree_dir / ".repowise" / "wiki.db"+ nodes = "SELECT COUNT(*) FROM graph_nodes WHERE node_id = '{}'"+ assert _db_scalar(db, nodes.format("wt_only.py")) == 1+ assert _db_scalar(db, nodes.format("base_only.py")) == 0+ finally:+ _remove_worktree(git_work_repo, worktree_dir)+def test_seed_from_self_fails(self, git_work_repo):from click.testing import CliRunnerdiff --git a/tests/unit/cli/test_worktree.py b/tests/unit/cli/test_worktree.pyindex 8e4edf3a9..9d575d65a 100644--- a/tests/unit/cli/test_worktree.py+++ b/tests/unit/cli/test_worktree.py@@ -119,3 +119,69 @@ def test_as_commit_id_accepts_only_hex_commit_ids() -> None:assert as_commit_id("DeadBee") == "DeadBee"for bad in ("--output=x", "-abcdef0", "abc123", "a" * 41, "HEAD", "", None, 7):assert as_commit_id(bad) is None+++def _base_moved_past_worktree(base_repo: Path, tmp_path: Path) -> tuple[Path, str]:+ """A worktree forked at the first commit, and the base synced one commit later."""+ import json+ import sqlite3++ wt = tmp_path / "wt"+ _git(["worktree", "add", "-b", "behind", str(wt)], base_repo)+ (base_repo / "b.py").write_text("y = 2\n", encoding="utf-8")+ _git(["add", "-A"], base_repo)+ _git(["commit", "-m", "base moves on"], base_repo)+ head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=base_repo, text=True).strip()+ dot = base_repo / ".repowise"+ dot.mkdir()+ (dot / "state.json").write_text(json.dumps({"last_sync_commit": head}), encoding="utf-8")+ conn = sqlite3.connect(dot / "wiki.db")+ conn.execute("CREATE TABLE repositories (id TEXT, name TEXT, local_path TEXT)")+ conn.close()+ (dot / ".update.lock").write_text("{}", encoding="utf-8")+ (dot / ".update.queued").write_text("{}", encoding="utf-8")+ return wt, head+++def test_seed_commit_refusal(base_repo: Path, tmp_path: Path) -> None:+ from repowise.cli.worktree import _seed_commit_refusal++ wt, head = _base_moved_past_worktree(base_repo, tmp_path)+ assert _seed_commit_refusal(wt, head, require_ancestor=True) == (+ "is not an ancestor of worktree HEAD"+ )+ assert _seed_commit_refusal(wt, head, require_ancestor=False) is None+ assert _seed_commit_refusal(wt, "f" * 40, require_ancestor=False) == (+ "is not in this repository"+ )+ assert _seed_commit_refusal(wt, "--bad", require_ancestor=False) == "is not a commit id"+++def test_seed_accepts_a_base_past_the_fork_point(base_repo: Path, tmp_path: Path) -> None:+ from repowise.cli.worktree import seed_index_from_base++ wt, _ = _base_moved_past_worktree(base_repo, tmp_path)+ assert not seed_index_from_base(root=wt, repo_paths=[wt], seed_base=base_repo)+ assert seed_index_from_base(+ root=wt, repo_paths=[wt], seed_base=base_repo, require_ancestor=False+ )+ seeded = wt / ".repowise"+ assert (seeded / "state.json").exists()+ assert not (seeded / ".update.lock").exists()+ assert not (seeded / ".update.queued").exists()+++def test_update_seeds_without_the_ancestor_check(tmp_path: Path, monkeypatch) -> None:+ import repowise.cli.worktree as worktree+ from repowise.cli.commands.update_cmd.command import _prepare_repo++ calls: list[dict] = []+ monkeypatch.setattr(worktree, "detect_worktree_base", lambda _p: tmp_path / "base")+ monkeypatch.setattr(worktree, "base_is_seedable", lambda _p: True)+ monkeypatch.setattr(worktree, "seed_index_from_base", lambda **kw: calls.append(kw))+ repo = tmp_path / "wt"+ repo.mkdir()++ _prepare_repo(repo)++ assert calls and calls[0]["require_ancestor"] is False