Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(init): workspace init keeps the repos you did not pick and skips git worktrees (#4264)

Raghav Chamadiya3bc568cfb3f2
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_config.py b/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_config.py
new file mode 100644
index 000000000..9ef6af8b4
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_config.py
@@ -0,0 +1,174 @@
+"""The workspace config a workspace init writes, merged with the one already there.
+
+Picking a subset of repos on a re-run must not silently shrink the workspace:
+repos the user did not pick stay listed unless an interactive user asks to
+replace the list, and the existing primary stays unless the user picked one.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import click
+import yaml
+from rich.console import Console
+from rich.markup import escape
+
+from repowise.cli.ui import OK, WARN
+from repowise.core.ci.markdown import plural
+
+_NAMES_SHOWN = 5
+
+
+@dataclass(frozen=True)
+class WorkspacePick:
+ """What the user picked: the repos to index and the primary among them."""
+
+ selected: list[Any]
+ root: Path
+ primary_alias: str
+ primary_repo: Any
+ #: The user chose the primary in a prompt, so it replaces the existing one.
+ primary_picked: bool
+
+
+def build_workspace_config(pick: WorkspacePick, *, console: Console, ask: bool) -> Any:
+ """The config for the picked repos, keeping what an existing config lists.
+
+ *ask* allows a prompt before repos the user did not pick are dropped;
+ without it they are always kept.
+ """
+ from repowise.core.workspace import WorkspaceConfig
+
+ root = pick.root
+ existing = _load_existing(root, console)
+ previous = {_key(root, e.path): e for e in existing.repos} if existing else {}
+ picked = _picked_entries(pick, previous)
+ if existing is None:
+ return _finish(WorkspaceConfig(version=1), list(picked.values()), pick.primary_alias)
+
+ left_out = [e for k, e in previous.items() if k not in picked]
+ replace, kept, clashed = _settle_left_out(root, left_out, picked, console=console, ask=ask)
+ repos = _merged_repos(root, previous, picked, kept)
+ keep_primary = not replace and not pick.primary_picked
+ primary = _primary(existing.default_repo, repos, clashed, pick.primary_alias, keep_primary)
+ return _finish(existing, repos, primary)
+
+
+def _picked_entries(pick: WorkspacePick, previous: dict[str, Any]) -> dict[str, Any]:
+ """One entry per picked repo, keyed by real path, carrying its existing tags."""
+ from repowise.core.workspace import RepoEntry
+
+ picked: dict[str, Any] = {}
+ for repo in pick.selected:
+ key = _key(pick.root, repo.path)
+ before = previous.get(key)
+ picked[key] = RepoEntry(
+ path=repo.path.relative_to(pick.root).as_posix(),
+ alias=repo.alias,
+ tags=list(before.tags) if before else [],
+ )
+ return picked
+
+
+def _merged_repos(
+ root: Path, previous: dict[str, Any], picked: dict[str, Any], kept: list[Any]
+) -> list[Any]:
+ """Existing order first (picked entries replace theirs in place), then new picks."""
+ keep_keys = {_key(root, e.path) for e in kept} | picked.keys()
+ repos = [picked.get(k, e) for k, e in previous.items() if k in keep_keys]
+ return repos + [e for k, e in picked.items() if k not in previous]
+
+
+def _primary(
+ old: str | None, repos: list[Any], clashed: list[Any], picked: str, keep_old: bool
+) -> str:
+ # A clashed alias now names a different repo, so it is not the old primary.
+ still_there = {e.alias for e in repos} - {e.alias for e in clashed}
+ return old if keep_old and old in still_there else picked
+
+
+def _settle_left_out(
+ root: Path, left_out: list[Any], picked: dict[str, Any], *, console: Console, ask: bool
+) -> tuple[bool, list[Any], list[Any]]:
+ """Whether to replace the workspace, and the left-out repos kept and clashed."""
+ # A folder that no longer exists has nothing to keep.
+ gone, present = _partition(left_out, lambda e: not (root / e.path).is_dir())
+ replace = bool(present) and ask and _confirm_replace(console, present, len(picked))
+ picked_aliases = {e.alias for e in picked.values()}
+ # Shortcut: a kept repo whose alias a picked repo now uses is dropped
+ # rather than renamed, since other tools address repos by alias. The line
+ # below names it; renaming would need the user to pick a new alias.
+ clashed, kept = ([], []) if replace else _partition(present, lambda e: e.alias in picked_aliases)
+ _report_kept(console, kept, clashed, gone)
+ return replace, kept, clashed
+
+
+def _partition(items: list[Any], pred: Callable[[Any], bool]) -> tuple[list[Any], list[Any]]:
+ """(items matching *pred*, the rest), each in order."""
+ yes = [e for e in items if pred(e)]
+ return yes, [e for e in items if not pred(e)]
+
+
+def _finish(config: Any, repos: list[Any], primary: str) -> Any:
+ for entry in repos:
+ entry.is_primary = entry.alias == primary
+ config.repos = repos
+ config.default_repo = primary
+ return config
+
+
+def _load_existing(root: Path, console: Console) -> Any | None:
+ from repowise.core.workspace import WORKSPACE_CONFIG_FILENAME, WorkspaceConfig
+
+ if not (root / WORKSPACE_CONFIG_FILENAME).is_file():
+ return None
+ try:
+ return WorkspaceConfig.load(root)
+ # A malformed file raises from YAML, or from the shape checks in from_dict.
+ except (OSError, ValueError, TypeError, AttributeError, yaml.YAMLError) as exc:
+ # An unreadable file has nothing to merge; the write replaces it.
+ console.print(
+ f" [{WARN}]Could not read the existing workspace config "
+ f"({escape(str(exc))}); replacing it.[/]"
+ )
+ return None
+
+
+def _key(root: Path, path: str | Path) -> str:
+ return os.path.normcase(str((root / path).resolve()))
+
+
+def _names(entries: list[Any]) -> str:
+ names = [escape(e.alias) for e in entries[:_NAMES_SHOWN]]
+ more = len(entries) - _NAMES_SHOWN
+ return ", ".join(names) + (f" and {more} more" if more > 0 else "")
+
+
+def _confirm_replace(console: Console, left_out: list[Any], picked: int) -> bool:
+ console.print(
+ f" [{WARN}]The workspace already lists {plural(len(left_out), 'repo')} "
+ f"you did not pick: {_names(left_out)}[/]"
+ )
+ return click.confirm(
+ f" Replace the workspace with only the {plural(picked, 'repo')} you picked?",
+ default=False,
+ )
+
+
+def _report_kept(console: Console, kept: list[Any], clashed: list[Any], gone: list[Any]) -> None:
+ if kept:
+ console.print(
+ f" [{OK}]✓[/] Kept {plural(len(kept), 'existing repo')} in the workspace "
+ f"({_names(kept)}). Remove one with `repowise workspace remove <alias>`."
+ )
+ if clashed:
+ console.print(
+ f" [{WARN}]Dropped {_names(clashed)}: a repo you picked now uses that alias.[/]"
+ )
+ if gone:
+ console.print(f" [{WARN}]Dropped {_names(gone)}: the folder no longer exists.[/]")
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index 8f73aa643..fcf703b2d 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -69,12 +69,14 @@ from repowise.cli.ui import (
load_dotenv,
print_banner,
)
+from repowise.core.ci.markdown import plural
from repowise.core.docs_mode import docs_mode_state_fields
from repowise.core.generation.styles import DEFAULT_STYLE
from ._exit import COST_UNCONFIRMED_BUILT, exit_on_gaps
from ._ingest import structural_generation_config
from ._interactive import offer_distill_rewrite_hook, offer_hook_install
+from ._workspace_config import WorkspacePick, build_workspace_config
from .generation import (
CostGateDeclined,
concept_page_count,
@@ -838,10 +840,10 @@ def _workspace_init(
# --yes, --all or a non-terminal stdin take every detected repo (and the
# first as primary) without prompting: asking a pipe would end the run with
# an EOFError before anything was done, and "every repo" is what --all means.
- picked = _select_workspace_repos(scan, select_all=init_all or yes or not sys.stdin.isatty())
- if picked is None:
+ pick = _select_workspace_repos(scan, select_all=init_all or yes or not sys.stdin.isatty())
+ if pick is None:
return
- selected, primary_alias, primary_repo = picked
+ selected, primary_alias, primary_repo = pick.selected, pick.primary_alias, pick.primary_repo
load_dotenv(primary_repo.path)
# --yes suppresses every prompt, so it means non-interactive.
@@ -874,7 +876,7 @@ def _workspace_init(
provider, resolved_reasoning = _resolve_workspace_provider(
answers, primary_repo, embedder_name, yes=yes, save_key=save_key
)
- ws_config = _workspace_config(selected, root, primary_alias, dry_run=dry_run)
+ ws_config = _workspace_config(pick, ask=sys.stdin.isatty() and not yes, dry_run=dry_run)
from repowise.core.ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMIT
@@ -938,8 +940,8 @@ def _workspace_init(
exit_on_gaps(_workspace_gaps(ctx, totals))
-def _select_workspace_repos(scan: Any, *, select_all: bool) -> tuple[list[Any], str, Any] | None:
- """The repos to index, the primary alias and repo; None when none were selected."""
+def _select_workspace_repos(scan: Any, *, select_all: bool) -> WorkspacePick | None:
+ """The repos to index and the primary; None when none were selected."""
root = scan.root
selected = (
list(scan.repos) if select_all else interactive_repo_select(console, scan.repos, root)
@@ -951,7 +953,9 @@ def _select_workspace_repos(scan: Any, *, select_all: bool) -> tuple[list[Any],
selected[0].alias if select_all else interactive_primary_select(console, selected)
)
primary_repo = next((r for r in selected if r.alias == primary_alias), selected[0])
- return selected, primary_alias, primary_repo
+ # interactive_primary_select asks only when there is more than one to choose from.
+ primary_picked = not select_all and len(selected) > 1
+ return WorkspacePick(selected, root, primary_alias, primary_repo, primary_picked)
def _save_workspace(
@@ -986,7 +990,7 @@ def _ask_workspace_mode(
"""The mode menu, then the provider (and advanced config) it calls for."""
mode = interactive_mode_select(
console,
- title=f"How much should repowise write for these {len(selected)} repos?",
+ title=f"How much should repowise write for {plural(len(selected), 'repo')}?",
)
if mode == "index_only":
answers.index_only = True
@@ -1083,23 +1087,13 @@ def _resolve_workspace_provider(
return provider, resolved_reasoning
-def _workspace_config(selected: list[Any], root: Path, primary_alias: str, *, dry_run: bool) -> Any:
+def _workspace_config(pick: WorkspacePick, *, ask: bool, dry_run: bool) -> Any:
"""The workspace config for the selected repos, saved unless this is a dry run."""
- from repowise.core.workspace import RepoEntry, WorkspaceConfig
+ from repowise.core.workspace import WORKSPACE_CONFIG_FILENAME
- entries = [
- RepoEntry(
- path=repo.path.relative_to(root).as_posix(),
- alias=repo.alias,
- is_primary=(repo.alias == primary_alias),
- )
- for repo in selected
- ]
- ws_config = WorkspaceConfig(
- version=1,
- repos=entries,
- default_repo=primary_alias,
- )
+ root = pick.root
+ verb = "Updated" if (root / WORKSPACE_CONFIG_FILENAME).is_file() else "Created"
+ ws_config = build_workspace_config(pick, console=console, ask=ask)
if dry_run:
# `.repowise/` is still created per repo, so a later distill-hook
# decline can gate every selected path; nothing is written into it.
@@ -1109,7 +1103,7 @@ def _workspace_config(selected: list[Any], root: Path, primary_alias: str, *, dr
)
else:
config_path = ws_config.save(root)
- console.print(f" [{OK}]✓[/] Created {config_path.name}")
+ console.print(f" [{OK}]✓[/] {verb} {config_path.name}")
console.print()
return ws_config
diff --git a/packages/cli/src/repowise/cli/ui/workspace_selection.py b/packages/cli/src/repowise/cli/ui/workspace_selection.py
index 185799bd7..33313d477 100644
--- a/packages/cli/src/repowise/cli/ui/workspace_selection.py
+++ b/packages/cli/src/repowise/cli/ui/workspace_selection.py
@@ -47,7 +47,8 @@ def interactive_repo_select(
title="[bold]Discovered Repositories[/bold]",
title_style="",
)
- table.add_column("#", style=BRAND_STYLE, width=4)
+ # Wide enough for the largest "[N]", so a long list never truncates to "[10…".
+ table.add_column("#", style=BRAND_STYLE, width=len(f"[{len(repos)}]"), no_wrap=True)
table.add_column("Repository", style="bold", min_width=16)
table.add_column("Path", style="dim", min_width=20)
table.add_column("Status", min_width=14)
@@ -149,7 +150,7 @@ def interactive_primary_select(
console.print(" [bold]Primary repository[/bold]")
console.print(
" [dim]The primary repo is what MCP tools and the dashboard open by default.\n"
- " You can change it later in repowise.workspace.yaml.[/dim]"
+ " You can change it later in .repowise-workspace.yaml.[/dim]"
)
console.print()
for idx, repo in enumerate(repos, 1):
diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.py
index 4437f7df2..92d71af0a 100644
--- a/packages/core/src/repowise/core/workspace/config.py
+++ b/packages/core/src/repowise/core/workspace/config.py
@@ -343,7 +343,7 @@ class WorkspaceConfig:
dropped = previous - {e.alias for e in self.repos}
if dropped:
_log.warning(
- "Writing %s with %d repo(s), down from %d — dropping: %s",
+ "Writing %s with %d repo(s), down from %d, dropping: %s",
config_path,
len(self.repos),
len(previous),
diff --git a/packages/core/src/repowise/core/workspace/scanner.py b/packages/core/src/repowise/core/workspace/scanner.py
index 841b24b34..704c21ec0 100644
--- a/packages/core/src/repowise/core/workspace/scanner.py
+++ b/packages/core/src/repowise/core/workspace/scanner.py
@@ -92,6 +92,10 @@ def scan_for_repos(
unless *include_submodules* is True. The flag never applies to *root*
itself: that is the repo the caller explicitly pointed at, not something
discovery turned up, so it is always eligible.
+ - Linked git worktrees found during the walk are skipped: each is another
+ checkout of a repo that is (or can be) listed on its own.
+ - A repo reached twice (a symlink or junction to another listed repo) is
+ listed once.
"""
root = Path(root).resolve()
@@ -104,6 +108,7 @@ def scan_for_repos(
# nested repos like backend/ and frontend/).
found: list[tuple[Path, bool]] = [] # (abs_path, is_submodule)
skipped: list[str] = []
+ seen: set[str] = {_path_key(root)} if root_is_repo else set()
for dirpath_str, dirnames, _filenames in os.walk(root):
dirpath = Path(dirpath_str)
@@ -121,15 +126,20 @@ def scan_for_repos(
for dirname in list(dirnames):
child = dirpath / dirname
if _is_git_repo(child):
+ repos_at_this_level.append(dirname)
+ if _is_linked_worktree(child):
+ continue
is_sub = _is_submodule(child)
if not is_sub or include_submodules:
try:
resolved = child.resolve()
resolved.relative_to(root)
- found.append((resolved, is_sub))
except (OSError, ValueError):
continue # broken symlink or resolved outside root
- repos_at_this_level.append(dirname)
+ key = _path_key(resolved)
+ if key not in seen:
+ seen.add(key)
+ found.append((resolved, is_sub))
# Don't descend into discovered repos
for dirname in repos_at_this_level:
@@ -173,17 +183,25 @@ def _is_git_repo(path: Path) -> bool:
def _is_submodule(path: Path) -> bool:
"""A submodule has ``.git`` as a file pointing to the parent's modules dir."""
+ return (path / ".git").is_file() and not _is_linked_worktree(path)
+
+
+def _is_linked_worktree(path: Path) -> bool:
+ """A linked worktree's ``.git`` file points into another repo's ``.git/worktrees/``."""
git_file = path / ".git"
if not git_file.is_file():
return False
-
try:
- # Distinguish submodules from git worktrees (which also use a .git file)
- # by checking if the gitdir points to a worktrees directory.
content = git_file.read_text(encoding="utf-8")
- return "/worktrees/" not in content
except OSError:
- return True
+ return False
+ # Git writes forward slashes, but a hand-edited Windows pointer may not.
+ return "/worktrees/" in content.replace("\\", "/")
+
+
+def _path_key(path: Path) -> str:
+ """One key per directory on disk, whatever case the filesystem ignores."""
+ return os.path.normcase(str(path))
def _prune_dirs(
diff --git a/tests/unit/cli/test_workspace_init_config.py b/tests/unit/cli/test_workspace_init_config.py
new file mode 100644
index 000000000..fb710272e
--- /dev/null
+++ b/tests/unit/cli/test_workspace_init_config.py
@@ -0,0 +1,193 @@
+"""Workspace init keeps the repos and primary an existing config already lists.
+
+Picking one repo on a re-run used to rewrite ``.repowise-workspace.yaml`` with
+only that repo, dropping the rest without a question.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import yaml
+from rich.console import Console
+
+from repowise.cli.commands.init_cmd import workspace as ws_mod
+from repowise.cli.commands.init_cmd._workspace_config import (
+ WorkspacePick,
+ build_workspace_config,
+)
+from repowise.cli.ui.workspace_selection import interactive_repo_select
+from repowise.core.workspace import WorkspaceConfig
+
+CONFIG = ".repowise-workspace.yaml"
+
+
+def _repo(root: Path, name: str) -> SimpleNamespace:
+ path = root / name
+ path.mkdir(exist_ok=True)
+ return SimpleNamespace(path=path.resolve(), alias=name, name=name)
+
+
+def _write(root: Path, aliases: list[str], default: str, **extra: object) -> None:
+ repos = []
+ for a in aliases:
+ (root / a).mkdir(exist_ok=True)
+ repos.append({"path": a, "alias": a, "indexed_at": "2026-01-01T00:00:00"})
+ data = {"version": 1, "repos": repos, "default_repo": default, **extra}
+ (root / CONFIG).write_text(yaml.safe_dump(data), encoding="utf-8")
+
+
+def _build(root: Path, picked: list[str], primary: str, **kw: bool) -> WorkspaceConfig:
+ console = Console(record=True, width=200)
+ repos = [_repo(root, n) for n in picked]
+ pick = WorkspacePick(repos, root.resolve(), primary, repos[0], kw.get("primary_picked", False))
+ cfg = build_workspace_config(pick, console=console, ask=kw.get("ask", False))
+ cfg._console_text = console.export_text() # type: ignore[attr-defined]
+ return cfg
+
+
+def test_fresh_workspace_lists_the_picked_repos(tmp_path: Path) -> None:
+ cfg = _build(tmp_path, ["a", "b"], "b")
+ assert [e.alias for e in cfg.repos] == ["a", "b"]
+ assert cfg.default_repo == "b"
+ assert [e.is_primary for e in cfg.repos] == [False, True]
+
+
+def test_non_interactive_keeps_repos_it_did_not_pick(tmp_path: Path) -> None:
+ _write(tmp_path, ["a", "b", "c"], "b")
+ with patch("click.confirm", side_effect=AssertionError("must not prompt")):
+ cfg = _build(tmp_path, ["a"], "a", ask=False)
+
+ assert [e.alias for e in cfg.repos] == ["a", "b", "c"]
+ # Kept repos keep their stamps; the existing primary stays.
+ assert cfg.get_repo("c").indexed_at == "2026-01-01T00:00:00"
+ assert cfg.default_repo == "b"
+ assert "Kept 2 existing repos" in cfg._console_text
+ assert "repowise workspace remove <alias>" in cfg._console_text
+
+
+def test_interactive_default_keeps_and_adds(tmp_path: Path) -> None:
+ _write(tmp_path, ["b", "c"], "c")
+ with patch("click.confirm", return_value=False) as confirm:
+ cfg = _build(tmp_path, ["a"], "a", ask=True)
+
+ assert confirm.call_args.kwargs["default"] is False
+ assert [e.alias for e in cfg.repos] == ["b", "c", "a"]
+ assert cfg.default_repo == "c"
+
+
+def test_interactive_replace_drops_the_rest(tmp_path: Path) -> None:
+ _write(tmp_path, ["a", "b", "c"], "b")
+ with patch("click.confirm", return_value=True):
+ cfg = _build(tmp_path, ["a"], "a", ask=True)
+
+ assert [e.alias for e in cfg.repos] == ["a"]
+ assert cfg.default_repo == "a"
+
+
+def test_no_prompt_when_nothing_would_be_dropped(tmp_path: Path) -> None:
+ _write(tmp_path, ["a", "b"], "a")
+ with patch("click.confirm", side_effect=AssertionError("must not prompt")):
+ cfg = _build(tmp_path, ["a", "b", "c"], "a", ask=True)
+ assert [e.alias for e in cfg.repos] == ["a", "b", "c"]
+
+
+def test_a_primary_picked_in_the_prompt_wins(tmp_path: Path) -> None:
+ _write(tmp_path, ["a", "b"], "a")
+ cfg = _build(tmp_path, ["a", "b"], "b", ask=True, primary_picked=True)
+ assert cfg.default_repo == "b"
+ assert cfg.get_repo("b").is_primary and not cfg.get_repo("a").is_primary
+
+
+def test_existing_tags_and_contracts_survive(tmp_path: Path) -> None:
+ (tmp_path / "a").mkdir()
+ data = {
+ "version": 1,
+ "repos": [{"path": "a", "alias": "a", "tags": ["frontend"]}],
+ "default_repo": "a",
+ "contracts": {"detect_http": False},
+ }
+ (tmp_path / CONFIG).write_text(yaml.safe_dump(data), encoding="utf-8")
+
+ cfg = _build(tmp_path, ["a"], "a")
+ assert cfg.get_repo("a").tags == ["frontend"]
+ assert cfg.contracts.detect_http is False
+
+
+def test_kept_repo_whose_alias_was_taken_is_named(tmp_path: Path) -> None:
+ (tmp_path / "old").mkdir()
+ data = {"version": 1, "repos": [{"path": "old", "alias": "a"}], "default_repo": "a"}
+ (tmp_path / CONFIG).write_text(yaml.safe_dump(data), encoding="utf-8")
+
+ cfg = _build(tmp_path, ["a"], "a")
+ assert [(e.alias, e.path) for e in cfg.repos] == [("a", "a")]
+ assert "Dropped a" in cfg._console_text
+
+
+def test_picker_number_column_fits_three_digits() -> None:
+ repos = [
+ SimpleNamespace(name=f"r{i}", path=Path(f"/w/r{i}"), has_repowise=False, is_submodule=False)
+ for i in range(226)
+ ]
+ console = Console(record=True, width=120)
+ with patch("repowise.cli.ui.workspace_selection.Prompt.ask", return_value="none"):
+ interactive_repo_select(console, repos)
+ text = console.export_text()
+ assert "[226]" in text and "…" not in text
+
+
+def test_mode_question_pluralizes_repo_count() -> None:
+ titles: list[str] = []
+
+ def _mode(_console: object, *, title: str) -> str:
+ titles.append(title)
+ return "index_only"
+
+ answers = SimpleNamespace(index_only=False)
+ with patch.object(ws_mod, "interactive_mode_select", side_effect=_mode):
+ ws_mod._ask_workspace_mode(answers, [object()], None, None, save_key=False)
+ ws_mod._ask_workspace_mode(answers, [object(), object()], None, None, save_key=False)
+ assert titles == [
+ "How much should repowise write for 1 repo?",
+ "How much should repowise write for 2 repos?",
+ ]
+
+
+def test_primary_moves_when_its_alias_was_taken(tmp_path: Path) -> None:
+ (tmp_path / "old").mkdir()
+ (tmp_path / "b").mkdir()
+ data = {
+ "version": 1,
+ "repos": [{"path": "old", "alias": "a"}, {"path": "b", "alias": "b"}],
+ "default_repo": "a",
+ }
+ (tmp_path / CONFIG).write_text(yaml.safe_dump(data), encoding="utf-8")
+
+ cfg = _build(tmp_path, ["a"], "a")
+ assert cfg.default_repo == "a" and cfg.get_repo("a").path == "a"
+
+
+def test_repo_whose_folder_is_gone_is_dropped_and_named(tmp_path: Path) -> None:
+ _write(tmp_path, ["a", "b", "c"], "b")
+ (tmp_path / "c").rmdir()
+ with patch("click.confirm", side_effect=AssertionError("must not prompt")):
+ cfg = _build(tmp_path, ["a", "b"], "a", ask=True)
+
+ assert [e.alias for e in cfg.repos] == ["a", "b"]
+ assert "Dropped c: the folder no longer exists" in cfg._console_text
+
+
+def test_existing_primary_kept_on_single_pick_via_selector(tmp_path: Path) -> None:
+ scan = SimpleNamespace(root=tmp_path, repos=[_repo(tmp_path, "a"), _repo(tmp_path, "b")])
+ with patch.object(ws_mod, "interactive_repo_select", return_value=scan.repos[:1]):
+ assert ws_mod._select_workspace_repos(scan, select_all=False).primary_picked is False
+ assert ws_mod._select_workspace_repos(scan, select_all=True).primary_picked is False
+
+
+def test_a_malformed_config_is_replaced_with_a_note(tmp_path: Path) -> None:
+ (tmp_path / CONFIG).write_text("repos: [unclosed", encoding="utf-8")
+ cfg = _build(tmp_path, ["a"], "a")
+ assert [e.alias for e in cfg.repos] == ["a"]
+ assert "Could not read the existing workspace config" in cfg._console_text
diff --git a/tests/unit/workspace/test_scanner.py b/tests/unit/workspace/test_scanner.py
index b0d1b3f49..eccf94c36 100644
--- a/tests/unit/workspace/test_scanner.py
+++ b/tests/unit/workspace/test_scanner.py
@@ -4,6 +4,8 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
from repowise.core.workspace.scanner import (
_generate_aliases,
_is_git_repo,
@@ -334,3 +336,64 @@ class TestHelpers:
aliases = _generate_aliases(pairs)
assert aliases[Path("/ws/x/api")] == "api"
assert aliases[Path("/ws/y/api")] == "api-2"
+
+
+# ---------------------------------------------------------------------------
+# scan_for_repos — linked worktrees and duplicates
+# ---------------------------------------------------------------------------
+
+
+class TestScanWorktreesAndDuplicates:
+ def test_linked_worktree_is_not_listed(self, tmp_path: Path) -> None:
+ """A linked worktree is another checkout of a listed repo, not a repo."""
+ _make_repo(tmp_path, "app")
+ wt = tmp_path / "app-wt" / "feature"
+ wt.mkdir(parents=True)
+ (wt / ".git").write_text(f"gitdir: {(tmp_path / 'app/.git/worktrees/feature').as_posix()}")
+
+ assert [r.name for r in scan_for_repos(tmp_path).repos] == ["app"]
+
+ def test_linked_worktree_with_backslash_pointer(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "app")
+ wt = tmp_path / "wt"
+ wt.mkdir()
+ (wt / ".git").write_text(r"gitdir: C:\src\app\.git\worktrees\wt")
+
+ assert [r.name for r in scan_for_repos(tmp_path, include_submodules=True).repos] == [
+ "app"
+ ]
+
+ def test_worktree_contents_are_not_scanned(self, tmp_path: Path) -> None:
+ """A worktree is a repo boundary: clones inside it are not discovered."""
+ _make_repo(tmp_path, "app")
+ wt = tmp_path / "wt"
+ wt.mkdir()
+ (wt / ".git").write_text("gitdir: /src/app/.git/worktrees/wt")
+ _make_repo(tmp_path, "wt/inner")
+
+ assert [r.name for r in scan_for_repos(tmp_path).repos] == ["app"]
+
+ def test_root_worktree_is_still_scannable(self, tmp_path: Path) -> None:
+ (tmp_path / ".git").write_text("gitdir: /src/app/.git/worktrees/wt")
+
+ assert [r.path for r in scan_for_repos(tmp_path).repos] == [tmp_path.resolve()]
+
+ def test_link_to_a_listed_repo_is_listed_once(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "content_engine")
+ _make_repo(tmp_path, "other")
+ try:
+ (tmp_path / "content_engine_link").symlink_to(
+ tmp_path / "content_engine", target_is_directory=True
+ )
+ except OSError:
+ pytest.skip("symlinks unavailable")
+
+ names = [r.name for r in scan_for_repos(tmp_path).repos]
+ assert names == ["content_engine", "other"]
+
+ def test_nested_independent_clones_still_found(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "app")
+ _make_repo(tmp_path, "test-repos/one")
+ _make_repo(tmp_path, "test-repos/two")
+
+ assert [r.name for r in scan_for_repos(tmp_path).repos] == ["app", "one", "two"]