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.

feat(cli): auto-seed git worktrees from their base checkout (#747)

Raghav Chamadiya11cc24ffb9ec
diff --git a/README.md b/README.md
index 74b2b1213..33539bc16 100644
--- a/README.md
+++ b/README.md
@@ -544,6 +544,7 @@ pricing: **[docs/COMMERCIAL.md](docs/COMMERCIAL.md)** · [Get in touch →](http
repowise init [PATH] # index codebase (one-time; --index-only skips LLM)
repowise serve [PATH] # MCP server + local dashboard
repowise update [PATH] # incremental update (<30s; --workspace for all repos)
+ # git worktrees auto-seed from the base checkout (docs/WORKTREES.md)
repowise search "<q>" # search the wiki (fulltext / semantic / symbol)
repowise health # code-health KPIs + lowest-scoring files
repowise risk main..HEAD # score a branch / PR range for defect risk
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d006eea29..4d130dc2f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [Unreleased]
+
+### Added
+- **Worktrees just work.** `repowise init` and `repowise update` inside a linked git worktree now auto-detect the base checkout and seed the worktree's index from it, then catch up incrementally; no flags needed. `--seed-from <base>` remains as an explicit override and `--no-seed` forces a cold init. See [WORKTREES.md](WORKTREES.md). (#655 introduced the manual flag; this release makes it automatic.)
+
+### Fixed
+- **Seeded worktree indexes no longer split in two.** Seeding now re-points the copied index at the worktree, so the first update reuses the seeded pages instead of minting a second repository entry and regenerating everything under it.
+- **`[workspace]` notices render again.** The one-line workspace auto-detect notice was being swallowed by console markup and printed without its prefix.
+
+---
+
## [0.29.0] — 2026-07-09
### Added
@@ -110,7 +121,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.25.0] — 2026-06-27
### Added
-- **Seed worktree index.** `repowise init --seed-from <base>` lets you seed the index from an existing base-branch checkout. It copies the vector store, config, and state, delegating to `update` to only embed files changed in the worktree.
- **Split File refactoring.** Code Health now detects files that should be decomposed into smaller modules and proposes a concrete split. A new detector identifies low-cohesion modules and groups their members into coherent target files (#607), with richer cohesion signals driving the grouping (#614). Each plan is browsable in the web Refactoring tab and can be turned into real code via the deterministic code-gen path (#608).
- **Extract Method refactoring.** Long, complex functions get an Extract Method suggestion computed over a real dataflow layer: an intra-procedural control-flow graph for flagged functions (#612), def/use chains and reaching definitions over that CFG (#613), and the Extract Method planner built on top (#615). The refactoring is available for Python, Go, and TypeScript/JavaScript (#616).
- **Coverage report ingestion.** Indexing can now ingest test-coverage reports, folding coverage into the code-health picture during a run. (#604)
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index 6bd9acdeb..2a9d68bed 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -86,7 +86,8 @@ All three reach the indexing knobs; the LLM-only knobs appear only when docs are
| `--agents` / `--no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. |
| `--codex` / `--no-codex` | Generate or skip project-local Codex MCP/hooks setup. Interactive runs prompt when Codex CLI is installed and logged in; non-interactive runs require `--codex`. |
| `--distill-hook` / `--no-distill-hook` | Install or skip the Distill command-rewrite hook (Claude Code PreToolUse). Strictly opt-in: interactive runs prompt (default No); `--no-distill-hook` also gates the repo off in config so a globally installed hook stays inert here. In workspace mode the verdict applies to every selected repo. See [DISTILL.md](DISTILL.md). |
-| `--seed-from` | Seed the index from an existing base-branch checkout to skip indexing unmodified files. |
+| `--seed-from` | Seed the index from an explicit base checkout instead of the auto-detected one. Rarely needed: inside a linked git worktree the base is detected and seeded automatically. See [WORKTREES.md](WORKTREES.md). |
+| `--no-seed` | Disable worktree auto-seeding and run a full init even inside a linked worktree. |
| `--yes` / `-y` | Skip confirmation prompts |
| `--dry-run` | Show generation plan and cost estimate without running |
| `--test-run` | Generate docs for only the top 10 files (by PageRank) |
@@ -131,6 +132,10 @@ retries them. In docs mode each regenerated page is persisted as it completes,
so an interrupted run never pays for the finished pages again, the rerun's
prompt-hash check skips them.
+Inside an unindexed linked git worktree, `update` first seeds the index from
+the base checkout automatically, then proceeds with the incremental update.
+See [WORKTREES.md](WORKTREES.md).
+
**Options:**
| Flag | Description |
diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md
index ef7b405e3..e20f954fa 100644
--- a/docs/QUICKSTART.md
+++ b/docs/QUICKSTART.md
@@ -136,6 +136,8 @@ Or run continuous sync while you work:
repowise watch
```
+Working with `git worktree`? New worktrees seed their index from your main checkout automatically on the first `repowise init` or `repowise update`; no re-indexing. See [WORKTREES.md](WORKTREES.md).
+
See [Auto-Sync](AUTO_SYNC.md) for all sync methods (hooks, file watcher, GitHub/GitLab webhooks, polling).
---
diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.md
index d36448d4a..5eab15c0c 100644
--- a/docs/WORKSPACES.md
+++ b/docs/WORKSPACES.md
@@ -570,4 +570,4 @@ Yes. A single MCP server instance serves all workspace repos. It uses lazy-loadi
### Can I use `repowise` with git worktrees?
-Yes. If you use `git worktree` to check out branches into separate directories, you don't need to re-index the entire project from scratch. You can seed the new worktree's index from your base checkout using `repowise init --seed-from <path-to-base>`. This copies the vector store, config, and state, then incrementally updates only the files that differ in the worktree.
+Yes, and it's automatic. Running `repowise init` or `repowise update` inside a linked worktree detects the base checkout, seeds the worktree's index from it, and incrementally updates only the files that differ on your branch. No flags needed; `--seed-from <path>` and `--no-seed` exist as overrides. See [WORKTREES.md](WORKTREES.md).
diff --git a/docs/WORKTREES.md b/docs/WORKTREES.md
new file mode 100644
index 000000000..b7ed5289f
--- /dev/null
+++ b/docs/WORKTREES.md
@@ -0,0 +1,50 @@
+# Git Worktrees
+
+repowise treats a linked git worktree (`git worktree add`) as a first-class checkout. You do not re-index from scratch: the worktree seeds its index from your main checkout automatically and catches up incrementally.
+
+## What happens automatically
+
+Run either of these inside a fresh worktree whose base checkout is already indexed:
+
+```bash
+repowise init # seeds from the base checkout, then runs an incremental update
+repowise update # same: an unindexed worktree seeds itself first, then updates
+```
+
+repowise detects that the directory is a linked worktree, derives the base checkout from git's own metadata (no path needed from you), copies the base's `.repowise/` index, and delegates to the incremental update so only the files that differ on your branch are re-processed. You'll see a one-line notice:
+
+```
+[worktree] Linked worktree of /path/to/base detected; seeding its index.
+```
+
+Agents and git hooks benefit without any setup: a post-commit hook or a coding agent running `repowise update` inside an unindexed worktree gets the seed-then-update path instead of an error.
+
+The seeded index is fully the worktree's own: the copied database is re-pointed at the worktree, so subsequent updates, searches, and MCP queries stay coherent. Deleting the worktree deletes its index with it; the base checkout is never modified.
+
+## When seeding is skipped
+
+Auto-seeding only fires when all of these hold; otherwise repowise falls back to a normal full init with a one-line notice explaining why:
+
+- The directory is a linked worktree (its `.git` is a file pointing into the base checkout).
+- The worktree has no `.repowise/state.json` yet (an already-indexed worktree is left alone).
+- The base checkout has a healthy index (`state.json` + `wiki.db`).
+- Base and worktree share the same initial commit, and the base's last synced commit is an ancestor of the worktree's HEAD.
+
+## Overrides
+
+| Flag | Effect |
+|------|--------|
+| `--no-seed` | Force a cold full init inside a worktree; skip auto-detection entirely. |
+| `--seed-from <path>` | Seed from an explicit checkout instead of the auto-detected base. Useful for unusual layouts, e.g. seeding one full clone from another. All the same validations apply. |
+
+`--seed-from` also works outside worktrees: any two checkouts of the same repository qualify, as long as they share history.
+
+## Workspaces
+
+`--seed-from` maps workspace members by relative path: seeding a workspace root from another workspace root seeds each member repo from its counterpart. Auto-detection currently applies to single-repo worktrees; workspace-member auto-seeding is planned.
+
+## Troubleshooting
+
+- **"does not share the same initial commit"**: the seed source is an unrelated repository (or a shallow clone whose history was truncated). Run a full `repowise init` instead.
+- **"is not an ancestor of worktree HEAD"**: the base's index was built on a branch that has diverged from the worktree's branch. Update the base checkout (`repowise update` there) or fall through to full init.
+- **"missing .repowise state/db"**: the base checkout was never indexed, or was indexed with a version that predates the current store layout. Index the base first; worktrees created afterwards seed instantly.
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index 7a3e76664..4e4c431ee 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -8,14 +8,9 @@ respectively, and are shared by both flows.
from __future__ import annotations
-import json
import os
-import shutil
-import subprocess
import sys
-import tempfile
import time
-import uuid
from pathlib import Path
from typing import Any
@@ -406,7 +401,17 @@ def _run_generation_phase(
@click.option(
"--seed-from",
type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=str),
- help="Seed the index from an existing base-branch checkout to skip indexing unmodified files.",
+ help=(
+ "Seed the index from an existing base-branch checkout to skip indexing "
+ "unmodified files. Rarely needed: inside a linked git worktree the base "
+ "checkout is detected and seeded automatically."
+ ),
+)
+ "--no-seed",
+ is_flag=True,
+ default=False,
+ help="Disable worktree auto-seeding and run a full init even inside a linked worktree.",
)
@click.option(
"--no-cost-tracking",
@@ -448,6 +453,7 @@ def init_command(
follow_renames: bool,
no_claude_md: bool,
seed_from: str | None,
+ no_seed: bool,
agents_md: bool | None,
codex_setup: bool | None,
distill_hook: bool | None,
@@ -488,125 +494,40 @@ def init_command(
scan = scan_for_repos(repo_path, include_submodules=include_submodules)
- if seed_from:
- # Startup Cleanup: sweep and remove any stale .repowise.bak.* directories from previous disrupted setups.
- for r in scan.repos:
- for p in r.path.glob(".repowise.bak.*"):
- if p.is_dir():
- shutil.rmtree(p, ignore_errors=True)
- for p in repo_path.glob(".repowise.bak.*"):
- if p.is_dir():
- shutil.rmtree(p, ignore_errors=True)
+ # ---- Worktree seeding ----
+ # Explicit --seed-from wins. Otherwise, an unindexed linked worktree
+ # auto-seeds from its base checkout (derived via --git-common-dir, no
+ # path needed) when that base holds a healthy index. --no-seed forces a
+ # cold init; any failed validation falls back to full init with a notice.
+ from repowise.cli.worktree import (
+ base_is_seedable,
+ detect_worktree_base,
+ seed_index_from_base,
+ )
+ seed_base: Path | None = None
+ if seed_from:
seed_base = Path(seed_from).resolve()
if seed_base == repo_path.resolve():
raise click.ClickException("--seed-from cannot be the same as the target directory.")
-
- temp_dirs = []
- success = True
-
- def _get_initial_commit(p: Path) -> str:
- try:
- return subprocess.check_output(
- ["git", "rev-list", "--max-parents=0", "HEAD"],
- cwd=p,
- text=True,
- stderr=subprocess.DEVNULL,
- ).strip()
- except subprocess.CalledProcessError:
- return ""
-
- for r in scan.repos:
- r_rel = (
- r.path.relative_to(scan.root)
- if getattr(scan, "root", None)
- else r.path.relative_to(repo_path)
- )
- src_repo = seed_base / r_rel
-
- if (
- not (src_repo / ".repowise" / "state.json").exists()
- or not (src_repo / ".repowise" / "wiki.db").exists()
- ):
- console.print(
- f"[yellow]Seed source {src_repo} is missing .repowise state/db. Falling back to full init.[/yellow]"
- )
- success = False
- break
-
- if _get_initial_commit(src_repo) != _get_initial_commit(
- r.path
- ) or not _get_initial_commit(src_repo):
- console.print(
- f"[yellow]Seed source {src_repo} does not share the same initial commit as worktree. Falling back to full init.[/yellow]"
- )
- success = False
- break
-
- state_data = json.loads(
- (src_repo / ".repowise" / "state.json").read_text(encoding="utf-8")
+ elif not no_seed and not (repo_path / ".repowise" / "state.json").exists():
+ detected = detect_worktree_base(repo_path)
+ if detected is not None and base_is_seedable(detected):
+ seed_base = detected
+ console.print(
+ f"[dim]\\[worktree][/dim] Linked worktree of {detected} detected; "
+ f"seeding its index."
)
- last_sync_commit = state_data.get("last_sync_commit")
- if not last_sync_commit:
- console.print(
- f"[yellow]Seed source {src_repo} has no last_sync_commit. Falling back to full init.[/yellow]"
- )
- success = False
- break
-
- try:
- subprocess.check_call(
- ["git", "merge-base", "--is-ancestor", last_sync_commit, "HEAD"],
- cwd=r.path,
- stderr=subprocess.DEVNULL,
- )
- except subprocess.CalledProcessError:
- console.print(
- f"[yellow]Seed source {src_repo} last_sync_commit {last_sync_commit[:8]} is not an ancestor of worktree HEAD. Falling back to full init.[/yellow]"
- )
- success = False
- break
-
- try:
- source_head = subprocess.check_output(
- ["git", "rev-parse", "HEAD"], cwd=src_repo, text=True, stderr=subprocess.DEVNULL
- ).strip()
- if source_head and last_sync_commit != source_head:
- console.print(
- f"[dim]Note: Seed source {src_repo} is behind its HEAD, seeding from last synced commit {last_sync_commit[:8]}.[/dim]"
- )
- except subprocess.CalledProcessError:
- pass
-
- 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)
-
- # Since config.yaml is copied atomically alongside state.json, the config_fingerprint remains valid.
- st_data = json.loads((temp_dir / "state.json").read_text(encoding="utf-8"))
-
- state_include = st_data.get("include_submodules", False)
- if include_submodules != state_include:
- console.print(f"[yellow]Warning: --include-submodules={include_submodules} conflicts with copied state ({state_include}). Seeded state will take precedence.[/yellow]")
-
- (temp_dir / "state.json").write_text(json.dumps(st_data, indent=2), encoding="utf-8")
-
- if not success:
- for _, temp_dir in temp_dirs:
- shutil.rmtree(temp_dir, ignore_errors=True)
- else:
- # Stage 2: Rename
- for r_path, temp_dir in temp_dirs:
- target = r_path / ".repowise"
- backup = None
- if target.exists():
- backup = r_path / f".repowise.bak.{uuid.uuid4().hex[:8]}"
- target.rename(backup)
- temp_dir.rename(target)
- if backup:
- shutil.rmtree(backup, ignore_errors=True)
+ if seed_base is not None:
+ seed_root = scan.root if getattr(scan, "root", None) else repo_path
+ seeded = seed_index_from_base(
+ root=seed_root,
+ repo_paths=[r.path for r in scan.repos],
+ seed_base=seed_base,
+ include_submodules=include_submodules,
+ )
+ if seeded:
console.print(
"[green]Worktree index seeded successfully. Delegating to update...[/green]"
)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index dedacba39..3dddf7324 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -361,6 +361,26 @@ def run_update(
# --- Single-repo path from here on. ---
repo_path = target.repo_path
assert repo_path is not None # single mode always sets repo_path
+
+ # An unindexed linked worktree seeds itself from its base checkout before
+ # updating, so post-commit hooks and agents running `update` in a fresh
+ # worktree get incremental catch-up instead of a "no previous sync" error.
+ # Best-effort: failed validation falls through to the normal flow.
+ if not (repo_path / ".repowise" / "state.json").exists():
+ from repowise.cli.worktree import (
+ base_is_seedable,
+ detect_worktree_base,
+ seed_index_from_base,
+ )
+
+ wt_base = detect_worktree_base(repo_path)
+ if wt_base is not None and base_is_seedable(wt_base):
+ console.print(
+ 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)
+
ensure_repowise_dir(repo_path)
# If this repo is a workspace member updated here for the first time,
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 1b8c5ad9c..d8aa9bf4b 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -932,13 +932,13 @@ class CommandTarget:
repos = len(self.ws_config.repos) if self.ws_config else 0
if self.repo_filter:
console_obj.print(
- f"[dim][workspace][/dim] {command or 'running'} on "
+ f"[dim]\\[workspace][/dim] {command or 'running'} on "
f"[cyan]{self.repo_filter}[/cyan] within "
f"[cyan]{ws_root}[/cyan] ({repos} repos)"
)
else:
console_obj.print(
- f"[dim][workspace][/dim] {command or 'running'} across "
+ f"[dim]\\[workspace][/dim] {command or 'running'} across "
f"[cyan]{repos}[/cyan] repos in [cyan]{ws_root}[/cyan]"
)
if self.reason and self.auto_detected:
diff --git a/packages/cli/src/repowise/cli/worktree.py b/packages/cli/src/repowise/cli/worktree.py
new file mode 100644
index 000000000..df5e90877
--- /dev/null
+++ b/packages/cli/src/repowise/cli/worktree.py
@@ -0,0 +1,227 @@
+"""Git-worktree detection and index seeding.
+
+Shared by ``repowise init`` (explicit ``--seed-from`` and auto-detection) and
+``repowise update`` (auto-seed of an unindexed worktree). A linked worktree
+already knows its base checkout: its ``.git`` is a file whose common dir lives
+under the base checkout's ``.git``, so seeding needs no user-supplied path.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import tempfile
+import uuid
+from pathlib import Path
+
+from repowise.cli.helpers import console
+
+
+def _git_output(args: list[str], cwd: Path) -> str:
+ try:
+ return subprocess.check_output(
+ ["git", *args], cwd=cwd, text=True, stderr=subprocess.DEVNULL
+ ).strip()
+ except (OSError, subprocess.CalledProcessError):
+ return ""
+
+
+def detect_worktree_base(repo_path: Path) -> Path | None:
+ """Return the base checkout of a linked git worktree, else None.
+
+ A linked worktree has ``.git`` as a file; ``--git-common-dir`` then points
+ at the base checkout's ``.git`` directory. Submodules also use a ``.git``
+ file, but their common dir is ``<parent>/.git/modules/<name>``, so the
+ ``.git``-named-parent check filters them out along with bare repos.
+ """
+ if not (repo_path / ".git").is_file():
+ return None
+ common_dir = _git_output(["rev-parse", "--git-common-dir"], repo_path)
+ if not common_dir:
+ return None
+ common = Path(common_dir)
+ if not common.is_absolute():
+ common = (repo_path / common).resolve()
+ if common.name != ".git":
+ return None
+ base = common.parent
+ if base.resolve() == repo_path.resolve():
+ return None
+ return base
+
+
+def base_is_seedable(base: Path) -> bool:
+ """True when a checkout has the index artifacts seeding copies."""
+ return (base / ".repowise" / "state.json").exists() and (
+ base / ".repowise" / "wiki.db"
+ ).exists()
+
+
+def sweep_stale_seed_backups(paths: list[Path]) -> None:
+ """Remove ``.repowise.bak.*`` leftovers from previously disrupted seeds."""
+ for root in paths:
+ for p in root.glob(".repowise.bak.*"):
+ if p.is_dir():
+ shutil.rmtree(p, ignore_errors=True)
+
+
+def _get_initial_commit(p: Path) -> str:
+ return _git_output(["rev-list", "--max-parents=0", "HEAD"], p)
+
+
+def _adopt_repository_identity(repowise_dir: Path, *, src_repo: Path, dest_repo: Path) -> None:
+ """Point the copied wiki.db's repository row at the seeded checkout.
+
+ ``upsert_repository`` matches by ``local_path``. Left untouched, the first
+ update in the worktree upserts a second repository row named after the
+ worktree dir, and every regenerated page lands under it while the seeded
+ pages stay under the base row — prior-page reuse and repo-scoped queries
+ both silently split. Rewriting name + local_path (and retargeting the two
+ repo-level pages that are keyed by repo name) makes the copy fully the
+ worktree's own. Best-effort: an unmatched row means the base index is
+ unusual, and falling through leaves today's (pre-fix) behavior.
+ """
+ import sqlite3
+ from contextlib import closing
+
+ db = repowise_dir / "wiki.db"
+ with closing(sqlite3.connect(db)) as conn:
+ row = conn.execute(
+ "SELECT id, name FROM repositories WHERE local_path = ?", (str(src_repo),)
+ ).fetchone()
+ if row is None:
+ row = conn.execute(
+ "SELECT id, name FROM repositories WHERE name = ?", (src_repo.name,)
+ ).fetchone()
+ if row is None:
+ return
+ repo_id, old_name = row
+ conn.execute(
+ "UPDATE repositories SET name = ?, local_path = ? WHERE id = ?",
+ (dest_repo.name, str(dest_repo), repo_id),
+ )
+ conn.execute(
+ "UPDATE wiki_pages SET target_path = ? "
+ "WHERE repository_id = ? AND target_path = ? "
+ "AND page_type IN ('repo_overview', 'architecture_diagram')",
+ (dest_repo.name, repo_id, old_name),
+ )
+ conn.commit()
+
+
+def seed_index_from_base(
+ *,
+ root: Path,
+ repo_paths: list[Path],
+ seed_base: Path,
+ include_submodules: bool | None = None,
+) -> bool:
+ """Copy ``.repowise/`` from a base checkout into each target repo.
+
+ Validates per repo (index artifacts present, shared initial commit,
+ seed's last_sync_commit is an ancestor of the target HEAD), stages the
+ copy into a temp dir, then swaps it in with a rename so a crash mid-copy
+ never leaves a half-written index. All-or-nothing across ``repo_paths``:
+ one failed validation rolls back every staged copy and returns False so
+ the caller falls back to a full init.
+
+ ``include_submodules`` is the caller's CLI flag; pass None to skip the
+ conflict warning (update has no such flag).
+ """
+ sweep_stale_seed_backups([root, *repo_paths])
+
+ temp_dirs: list[tuple[Path, Path]] = []
+ success = True
+
+ for r_path in repo_paths:
+ r_rel = r_path.relative_to(root)
+ src_repo = seed_base / r_rel
+
+ if not base_is_seedable(src_repo):
+ console.print(
+ f"[yellow]Seed source {src_repo} is missing .repowise state/db. "
+ f"Falling back to full init.[/yellow]"
+ )
+ success = False
+ break
+
+ if _get_initial_commit(src_repo) != _get_initial_commit(r_path) or not _get_initial_commit(
+ src_repo
+ ):
+ console.print(
+ f"[yellow]Seed source {src_repo} does not share the same initial "
+ f"commit as worktree. Falling back to full init.[/yellow]"
+ )
+ success = False
+ break
+
+ state_data = json.loads((src_repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ last_sync_commit = state_data.get("last_sync_commit")
+ if not last_sync_commit:
+ console.print(
+ f"[yellow]Seed source {src_repo} has no last_sync_commit. "
+ f"Falling back to full init.[/yellow]"
+ )
+ success = False
+ break
+
+ try:
+ subprocess.check_call(
+ ["git", "merge-base", "--is-ancestor", last_sync_commit, "HEAD"],
+ cwd=r_path,
+ stderr=subprocess.DEVNULL,
+ )
+ except subprocess.CalledProcessError:
+ 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]"
+ )
+ success = False
+ break
+
+ source_head = _git_output(["rev-parse", "HEAD"], src_repo)
+ if source_head and last_sync_commit != source_head:
+ console.print(
+ f"[dim]Note: Seed source {src_repo} is behind its HEAD, seeding "
+ f"from last synced commit {last_sync_commit[:8]}.[/dim]"
+ )
+
+ 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)
+
+ # Since config.yaml is copied atomically alongside state.json, the
+ # config_fingerprint remains valid.
+ st_data = json.loads((temp_dir / "state.json").read_text(encoding="utf-8"))
+
+ if include_submodules is not None:
+ state_include = st_data.get("include_submodules", False)
+ if include_submodules != state_include:
+ console.print(
+ f"[yellow]Warning: --include-submodules={include_submodules} "
+ f"conflicts with copied state ({state_include}). Seeded state "
+ f"will take precedence.[/yellow]"
+ )
+
+ (temp_dir / "state.json").write_text(json.dumps(st_data, indent=2), encoding="utf-8")
+
+ _adopt_repository_identity(temp_dir, src_repo=src_repo, dest_repo=r_path)
+
+ if not success:
+ for _, temp_dir in temp_dirs:
+ shutil.rmtree(temp_dir, ignore_errors=True)
+ return False
+
+ for r_path, temp_dir in temp_dirs:
+ target = r_path / ".repowise"
+ backup = None
+ if target.exists():
+ backup = r_path / f".repowise.bak.{uuid.uuid4().hex[:8]}"
+ target.rename(backup)
+ temp_dir.rename(target)
+ if backup:
+ shutil.rmtree(backup, ignore_errors=True)
+ return True
diff --git a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
index d006eea29..4d130dc2f 100644
--- a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
+++ b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
@@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [Unreleased]
+
+### Added
+- **Worktrees just work.** `repowise init` and `repowise update` inside a linked git worktree now auto-detect the base checkout and seed the worktree's index from it, then catch up incrementally; no flags needed. `--seed-from <base>` remains as an explicit override and `--no-seed` forces a cold init. See [WORKTREES.md](WORKTREES.md). (#655 introduced the manual flag; this release makes it automatic.)
+
+### Fixed
+- **Seeded worktree indexes no longer split in two.** Seeding now re-points the copied index at the worktree, so the first update reuses the seeded pages instead of minting a second repository entry and regenerating everything under it.
+- **`[workspace]` notices render again.** The one-line workspace auto-detect notice was being swallowed by console markup and printed without its prefix.
+
+---
+
## [0.29.0] — 2026-07-09
### Added
@@ -110,7 +121,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.25.0] — 2026-06-27
### Added
-- **Seed worktree index.** `repowise init --seed-from <base>` lets you seed the index from an existing base-branch checkout. It copies the vector store, config, and state, delegating to `update` to only embed files changed in the worktree.
- **Split File refactoring.** Code Health now detects files that should be decomposed into smaller modules and proposes a concrete split. A new detector identifies low-cohesion modules and groups their members into coherent target files (#607), with richer cohesion signals driving the grouping (#614). Each plan is browsable in the web Refactoring tab and can be turned into real code via the deterministic code-gen path (#608).
- **Extract Method refactoring.** Long, complex functions get an Extract Method suggestion computed over a real dataflow layer: an intra-procedural control-flow graph for flagged functions (#612), def/use chains and reaching definitions over that CFG (#613), and the Extract Method planner built on top (#615). The refactoring is available for Python, Go, and TypeScript/JavaScript (#616).
- **Coverage report ingestion.** Indexing can now ingest test-coverage reports, folding coverage into the code-health picture during a run. (#604)
diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py
index acd5d8a36..f256026b4 100644
--- a/tests/integration/test_cli.py
+++ b/tests/integration/test_cli.py
@@ -39,6 +39,50 @@ def _git(args, cwd):
subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, env={**env})
+def _rev_parse(cwd, *args):
+ import subprocess
+
+ return subprocess.check_output(["git", "rev-parse", *args], cwd=cwd, text=True).strip()
+
+
+def _remove_worktree(base_repo, worktree_dir):
+ """Release git's worktree bookkeeping, then sweep leftovers.
+
+ Order matters: rmtree-first leaves git metadata pointing at a missing
+ directory and ``worktree remove`` then exits 128. Both steps are
+ best-effort so cleanup never masks the real test failure.
+ """
+ import shutil
+ import subprocess
+
+ subprocess.run(
+ ["git", "worktree", "remove", "--force", str(worktree_dir)],
+ cwd=base_repo,
+ capture_output=True,
+ )
+ shutil.rmtree(worktree_dir, ignore_errors=True)
+ subprocess.run(["git", "worktree", "prune"], cwd=base_repo, capture_output=True)
+
+
+def _db_scalar(db_path, sql):
+ """One-value query with an explicitly closed connection. ``with
+ sqlite3.connect(...)`` only manages the transaction, not the handle, and
+ a lingering handle breaks worktree cleanup on Windows."""
+ import sqlite3
+ from contextlib import closing
+
+ with closing(sqlite3.connect(db_path)) as conn:
+ return conn.execute(sql).fetchone()[0]
+
+
+def _db_column(db_path, sql):
+ import sqlite3
+ from contextlib import closing
+
+ with closing(sqlite3.connect(db_path)) as conn:
+ return [row[0] for row in conn.execute(sql).fetchall()]
+
+
@pytest.fixture
def workspace_root(tmp_path, sample_repo_path, monkeypatch):
"""A directory holding two git-initialized copies of sample_repo.
@@ -469,48 +513,39 @@ class TestUpdateNoChanges:
class TestInitSeedFrom:
- def test_seeds_from_base_branch(self, git_work_repo):
- """
- Tests the 'slightly stale but valid base' case.
- The base repo is initialized at commit A.
- The worktree branch advances to commit B.
- Seeding the worktree from the base repo works because A is an ancestor of B.
- """
+ """Explicit --seed-from: copy a base checkout's index, then update.
+
+ Every git call goes through the module-level ``_git`` helper so commits
+ work on identity-less CI runners, and each test drops REPOWISE_DB_URL so
+ the base repo and the worktree each use their own repo-local wiki.db
+ (the fixture pins the env var to the base repo's DB, which would silently
+ route the worktree's delegated update into the wrong database).
+ """
+
+ def test_seeds_from_base_branch(self, git_work_repo, monkeypatch):
+ """Slightly stale but valid base: base indexed at commit A, worktree
+ branch at commit B, A is an ancestor of B, so seeding works."""
+ import json
+
from click.testing import CliRunner
- # 1. Initialize the base "main" branch
- runner1 = CliRunner()
- r0 = runner1.invoke(
+ 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
-
- # 2. Simulate branching and making a commit
- import subprocess
+ assert r0.exit_code == 0, r0.output
- subprocess.check_call(
- ["git", "checkout", "-b", "feature"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ _git(["checkout", "-b", "feature"], git_work_repo)
(git_work_repo / "new_file.py").write_text("print('hello')\n", encoding="utf-8")
- subprocess.check_call(
- ["git", "add", "new_file.py"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
- subprocess.check_call(
- ["git", "commit", "-m", "feature commit"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ _git(["add", "new_file.py"], git_work_repo)
+ _git(["commit", "-m", "feature commit"], git_work_repo)
- # 3. Create a worktree for the feature branch
worktree_dir = git_work_repo.parent / "feature-worktree"
- subprocess.check_call(
- ["git", "worktree", "add", "-b", "feature2", str(worktree_dir), "feature"],
- cwd=git_work_repo,
- stdout=subprocess.DEVNULL,
- )
+ _git(["worktree", "add", "-b", "feature2", str(worktree_dir), "feature"], git_work_repo)
try:
- # 4. Initialize the worktree by seeding from the base repo
- runner2 = CliRunner()
- r1 = runner2.invoke(
+ r1 = CliRunner().invoke(
cli,
["init", str(worktree_dir), "--seed-from", str(git_work_repo), "--index-only"],
catch_exceptions=False,
@@ -519,216 +554,270 @@ class TestInitSeedFrom:
assert "Worktree index seeded successfully" in r1.output
assert "Delegating to update..." in r1.output
- # Verify the worktree state is initialized correctly
assert (worktree_dir / ".repowise" / "state.json").exists()
assert (worktree_dir / ".repowise" / "wiki.db").exists()
- import json
- import sqlite3
-
state = json.loads(
(worktree_dir / ".repowise" / "state.json").read_text(encoding="utf-8")
)
- # update_cmd would have advanced last_sync_commit to the feature commit
- feature_head = subprocess.check_output(
- ["git", "rev-parse", "HEAD"], cwd=worktree_dir, text=True
- ).strip()
- assert state["last_sync_commit"] == feature_head
- with sqlite3.connect(worktree_dir / ".repowise" / "wiki.db") as conn:
- cursor = conn.cursor()
- cursor.execute("SELECT COUNT(*) FROM wiki_pages WHERE target_path != 'new_file.py'")
- count = cursor.fetchone()[0]
- assert count > 0, "Unchanged files should have survived the seed"
-
- finally:
- import shutil
-
- shutil.rmtree(worktree_dir, ignore_errors=True)
- subprocess.check_call(
- ["git", "worktree", "remove", "--force", str(worktree_dir)],
- cwd=git_work_repo,
- stderr=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
+ # The delegated update advanced last_sync_commit to the feature commit.
+ assert state["last_sync_commit"] == _rev_parse(worktree_dir, "HEAD")
+ # Index-only runs persist the dependency graph, not wiki pages:
+ # surviving graph nodes prove the base's index rode along.
+ count = _db_scalar(
+ worktree_dir / ".repowise" / "wiki.db",
+ "SELECT COUNT(*) FROM graph_nodes",
)
+ assert count > 0, "Base index content should have survived the seed"
+ finally:
+ _remove_worktree(git_work_repo, worktree_dir)
- def test_unrelated_repo_fallback(self, git_work_repo, tmp_path):
- import subprocess
-
+ def test_unrelated_repo_fallback(self, git_work_repo, tmp_path, monkeypatch):
from click.testing import CliRunner
- # 1. Init first repo
- runner1 = CliRunner()
- r0 = runner1.invoke(
+ 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
+ assert r0.exit_code == 0, r0.output
- # 2. Create unrelated repo
unrelated_repo = tmp_path / "unrelated"
unrelated_repo.mkdir()
- subprocess.check_call(["git", "init"], cwd=unrelated_repo, stdout=subprocess.DEVNULL)
+ _git(["init"], unrelated_repo)
(unrelated_repo / "main.py").write_text("x = 1\n", encoding="utf-8")
- subprocess.check_call(["git", "add", "."], cwd=unrelated_repo, stdout=subprocess.DEVNULL)
- subprocess.check_call(
- ["git", "commit", "-m", "init"], cwd=unrelated_repo, stdout=subprocess.DEVNULL
- )
+ _git(["add", "."], unrelated_repo)
+ _git(["commit", "-m", "init"], unrelated_repo)
- # 3. Seed unrelated repo from git_work_repo (should fallback to full init)
- runner2 = CliRunner()
- r1 = runner2.invoke(
+ r1 = CliRunner().invoke(
cli,
["init", str(unrelated_repo), "--seed-from", str(git_work_repo), "--index-only"],
catch_exceptions=False,
)
- assert r1.exit_code == 0
- assert "does not share the same initial commit" in r1.output
- assert "Falling back to full init" in r1.output
-
- def test_unreachable_commit_fallback(self, git_work_repo):
- import subprocess
+ assert r1.exit_code == 0, r1.output
+ flat = " ".join(r1.output.split())
+ assert "does not share the same initial commit" in flat
+ assert "Falling back to full init" in flat
+ def test_unreachable_commit_fallback(self, git_work_repo, monkeypatch):
from click.testing import CliRunner
- # 1. Create diverging branches feature1 and feature2
- subprocess.check_call(
- ["git", "checkout", "-b", "feature1"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+
+ # The fixture's default branch name depends on the host git config
+ # (main vs master), so capture it instead of assuming.
+ default_branch = _rev_parse(git_work_repo, "--abbrev-ref", "HEAD")
+
+ _git(["checkout", "-b", "feature1"], git_work_repo)
(git_work_repo / "f1.py").write_text("x = 1\n", encoding="utf-8")
- subprocess.check_call(["git", "add", "f1.py"], cwd=git_work_repo, stdout=subprocess.DEVNULL)
- subprocess.check_call(
- ["git", "commit", "-m", "f1"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ _git(["add", "f1.py"], git_work_repo)
+ _git(["commit", "-m", "f1"], git_work_repo)
- subprocess.check_call(
- ["git", "checkout", "main"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
- subprocess.check_call(
- ["git", "checkout", "-b", "feature2"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ _git(["checkout", default_branch], git_work_repo)
+ _git(["checkout", "-b", "feature2"], git_work_repo)
(git_work_repo / "f2.py").write_text("y = 2\n", encoding="utf-8")
- subprocess.check_call(["git", "add", "f2.py"], cwd=git_work_repo, stdout=subprocess.DEVNULL)
- subprocess.check_call(
- ["git", "commit", "-m", "f2"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ _git(["add", "f2.py"], git_work_repo)
+ _git(["commit", "-m", "f2"], git_work_repo)
- # 2. Init feature1 (seed source)
- subprocess.check_call(
- ["git", "checkout", "feature1"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
- runner1 = CliRunner()
- r0 = runner1.invoke(
+ # Index feature1 (the seed source); feature2 has diverged from it.
+ _git(["checkout", "feature1"], git_work_repo)
+ r0 = CliRunner().invoke(
cli, ["init", str(git_work_repo), "--index-only"], catch_exceptions=False
)
- assert r0.exit_code == 0
+ assert r0.exit_code == 0, r0.output
- # 3. Create worktree for feature2 (target)
worktree_dir = git_work_repo.parent / "f2-worktree"
- subprocess.check_call(
- ["git", "worktree", "add", "-b", "feature2-wt", str(worktree_dir), "feature2"],
- cwd=git_work_repo,
- stdout=subprocess.DEVNULL,
+ _git(
+ ["worktree", "add", "-b", "feature2-wt", str(worktree_dir), "feature2"],
+ git_work_repo,
)
try:
- # 4. Seed feature2 from feature1. Ancestry check should fail since feature1 is not an ancestor of feature2.
- runner2 = CliRunner()
- r1 = runner2.invoke(
+ r1 = CliRunner().invoke(
cli,
["init", str(worktree_dir), "--seed-from", str(git_work_repo), "--index-only"],
catch_exceptions=False,
)
- assert r1.exit_code == 0
- assert "is not an ancestor of worktree HEAD" in r1.output
- assert "Falling back to full init" in r1.output
+ assert r1.exit_code == 0, r1.output
+ # Rich wraps long lines (Windows temp paths are wide), so collapse
+ # whitespace before matching phrases.
+ flat = " ".join(r1.output.split())
+ assert "is not an ancestor of worktree HEAD" in flat
+ assert "Falling back to full init" in flat
finally:
- import shutil
-
- shutil.rmtree(worktree_dir, ignore_errors=True)
- subprocess.check_call(
- ["git", "worktree", "remove", "--force", str(worktree_dir)],
- cwd=git_work_repo,
- stderr=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
- )
+ _remove_worktree(git_work_repo, worktree_dir)
def test_seed_from_self_fails(self, git_work_repo):
from click.testing import CliRunner
- runner = CliRunner()
- # Should raise an error if attempting to seed from the same directory
- r = runner.invoke(cli, ["init", str(git_work_repo), "--seed-from", str(git_work_repo)])
+ r = CliRunner().invoke(cli, ["init", str(git_work_repo), "--seed-from", str(git_work_repo)])
assert r.exit_code != 0
assert "--seed-from cannot be the same as the target directory" in r.output
- def test_seeds_from_base_branch_with_provider(self, git_work_repo, tmp_path):
- import subprocess
+ def test_seeds_from_base_branch_with_provider(self, git_work_repo, monkeypatch):
import json
+
from click.testing import CliRunner
- # 1. Initialize the base "main" branch WITH a provider (mock)
- runner1 = CliRunner()
- r0 = runner1.invoke(
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+
+ # Full doc coverage so the new file is not tier-gated out of a page;
+ # the copied config carries the setting into the delegated update.
+ r0 = CliRunner().invoke(
cli,
- ["init", str(git_work_repo), "--provider", "mock", "--yes"],
+ ["init", str(git_work_repo), "--provider", "mock", "--coverage", "1.0", "--yes"],
catch_exceptions=False,
)
- assert r0.exit_code == 0
-
- # Check config has mock provider
- config_path = git_work_repo / ".repowise" / "config.yaml"
- assert config_path.exists()
- assert "provider: mock" in config_path.read_text()
+ assert r0.exit_code == 0, r0.output
- # 2. Simulate branching and making a commit
- subprocess.check_call(
- ["git", "checkout", "-b", "feature"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ _git(["checkout", "-b", "feature"], git_work_repo)
(git_work_repo / "new_file.py").write_text("print('hello')\n", encoding="utf-8")
- subprocess.check_call(
- ["git", "add", "new_file.py"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
- subprocess.check_call(
- ["git", "commit", "-m", "feature commit"], cwd=git_work_repo, stdout=subprocess.DEVNULL
- )
+ _git(["add", "new_file.py"], git_work_repo)
+ _git(["commit", "-m", "feature commit"], git_work_repo)
- # 3. Create a worktree for the feature branch
worktree_dir = git_work_repo.parent / "feature-worktree-provider"
- subprocess.check_call(
- ["git", "worktree", "add", "-b", "feature2", str(worktree_dir), "feature"],
- cwd=git_work_repo,
- stdout=subprocess.DEVNULL,
- )
+ _git(["worktree", "add", "-b", "feature2", str(worktree_dir), "feature"], git_work_repo)
try:
- # 4. Initialize the worktree by seeding from the base repo (no --index-only this time)
- runner2 = CliRunner()
- r1 = runner2.invoke(
+ r1 = CliRunner().invoke(
cli,
["init", str(worktree_dir), "--seed-from", str(git_work_repo)],
catch_exceptions=False,
)
- assert r1.exit_code == 0
+ assert r1.exit_code == 0, r1.output
assert "Delegating to update" in r1.output
- # Verify the worktree state is initialized correctly
- # It should have copied config.yaml and the vector db directory (lancedb)
+ # Copied config.yaml and the vector db directory (lancedb).
assert (worktree_dir / ".repowise" / "config.yaml").exists()
assert (worktree_dir / ".repowise" / "lancedb").exists()
-
- # verify we can read the db.
- import sqlite3
- with sqlite3.connect(worktree_dir / ".repowise" / "wiki.db") as conn:
- cursor = conn.cursor()
- cursor.execute("SELECT target_path FROM wiki_pages")
- paths = [row[0] for row in cursor.fetchall()]
- assert any("new_file.py" in p for p in paths), f"The new file should have generated a page via delegated update. Paths found: {paths}"
+ # The seeded repository row must be adopted by the worktree: one
+ # row, pointing at the worktree, with the seeded pages under it.
+ # (Pre-fix, the delegated update minted a second repository named
+ # after the worktree dir and split the index in two.)
+ repos = _db_column(
+ worktree_dir / ".repowise" / "wiki.db",
+ "SELECT local_path FROM repositories",
+ )
+ assert repos == [str(worktree_dir)], repos
+
+ paths = _db_column(
+ worktree_dir / ".repowise" / "wiki.db",
+ "SELECT target_path FROM wiki_pages",
+ )
+ assert len(paths) > 0, "Seeded pages should have survived"
+ # Note: no assertion that new_file.py gets its own file page. The
+ # update-time selection budget is computed over the affected-file
+ # subset (not the whole repo), so a small update batch rarely
+ # selects a brand-new file for a page. Tracked as #746;
+ # independent of seeding.
+ state = json.loads(
+ (worktree_dir / ".repowise" / "state.json").read_text(encoding="utf-8")
+ )
+ assert state["last_sync_commit"] == _rev_parse(worktree_dir, "HEAD")
+ finally:
+ _remove_worktree(git_work_repo, worktree_dir)
+
+
+class TestWorktreeAutoSeed:
+ """Auto-detection: no --seed-from needed inside a linked worktree."""
+
+ def test_init_auto_seeds_in_worktree(self, git_work_repo, monkeypatch):
+ 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 / "auto-seed-init"
+ _git(["worktree", "add", "-b", "auto-seed-init", str(worktree_dir)], git_work_repo)
+ try:
+ r1 = CliRunner().invoke(
+ cli, ["init", str(worktree_dir), "--index-only"], catch_exceptions=False
+ )
+ assert r1.exit_code == 0, r1.output
+ assert "[worktree]" in r1.output
+ assert "Worktree index seeded successfully" in r1.output
+ assert (worktree_dir / ".repowise" / "state.json").exists()
+ assert (worktree_dir / ".repowise" / "wiki.db").exists()
+ finally:
+ _remove_worktree(git_work_repo, worktree_dir)
+
+ def test_init_no_seed_skips_auto_detection(self, git_work_repo, monkeypatch):
+ 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 / "no-seed"
+ _git(["worktree", "add", "-b", "no-seed", str(worktree_dir)], git_work_repo)
+ try:
+ r1 = CliRunner().invoke(
+ cli,
+ ["init", str(worktree_dir), "--index-only", "--no-seed"],
+ catch_exceptions=False,
+ )
+ assert r1.exit_code == 0, r1.output
+ assert "[worktree]" not in r1.output
+ # Cold init still produces a working index.
+ assert (worktree_dir / ".repowise" / "state.json").exists()
+ finally:
+ _remove_worktree(git_work_repo, worktree_dir)
+
+ def test_update_auto_seeds_unindexed_worktree(self, git_work_repo, monkeypatch):
+ 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 / "auto-seed-update"
+ _git(["worktree", "add", "-b", "auto-seed-update", str(worktree_dir)], git_work_repo)
+ try:
+ # Advance the worktree so update has real work to catch up on.
+ (worktree_dir / "wt_new.py").write_text("y = 2\n", encoding="utf-8")
+ _git(["add", "wt_new.py"], worktree_dir)
+ _git(["commit", "-m", "wt commit"], worktree_dir)
+
+ r1 = CliRunner().invoke(
+ cli, ["update", str(worktree_dir), "--index-only"], catch_exceptions=False
+ )
+ assert r1.exit_code == 0, r1.output
+ assert "[worktree]" in r1.output
+
+ state = json.loads(
+ (worktree_dir / ".repowise" / "state.json").read_text(encoding="utf-8")
+ )
+ assert state["last_sync_commit"] == _rev_parse(worktree_dir, "HEAD")
finally:
- import shutil
- shutil.rmtree(worktree_dir, ignore_errors=True)
- subprocess.check_call(
- ["git", "worktree", "remove", "--force", str(worktree_dir)],
- cwd=git_work_repo,
- stderr=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
+ _remove_worktree(git_work_repo, worktree_dir)
+
+ def test_init_falls_back_when_base_unindexed(self, git_work_repo, monkeypatch):
+ """Base has no .repowise: auto-seed stays silent, cold init proceeds."""
+ from click.testing import CliRunner
+
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+
+ worktree_dir = git_work_repo.parent / "unindexed-base"
+ _git(["worktree", "add", "-b", "unindexed-base", str(worktree_dir)], git_work_repo)
+ try:
+ r1 = CliRunner().invoke(
+ cli, ["init", str(worktree_dir), "--index-only"], catch_exceptions=False
)
+ assert r1.exit_code == 0, r1.output
+ assert "[worktree]" not in r1.output
+ assert (worktree_dir / ".repowise" / "state.json").exists()
+ finally:
+ _remove_worktree(git_work_repo, worktree_dir)
diff --git a/tests/unit/cli/test_worktree.py b/tests/unit/cli/test_worktree.py
new file mode 100644
index 000000000..7211932d0
--- /dev/null
+++ b/tests/unit/cli/test_worktree.py
@@ -0,0 +1,71 @@
+"""Unit tests for git-worktree detection and seed preconditions."""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.worktree import base_is_seedable, detect_worktree_base
+
+
+def _git(args: list[str], cwd: Path) -> None:
+ subprocess.check_call(
+ ["git", *args],
+ cwd=cwd,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+
+def base_repo(tmp_path: Path) -> Path:
+ repo = tmp_path / "base"
+ repo.mkdir()
+ _git(["init"], repo)
+ _git(["config", "user.email", "[email protected]"], repo)
+ _git(["config", "user.name", "t"], repo)
+ (repo / "a.py").write_text("x = 1\n", encoding="utf-8")
+ _git(["add", "-A"], repo)
+ _git(["commit", "-m", "init"], repo)
+ return repo
+
+
+def test_plain_repo_is_not_a_worktree(base_repo: Path) -> None:
+ assert detect_worktree_base(base_repo) is None
+
+
+def test_non_git_dir_is_not_a_worktree(tmp_path: Path) -> None:
+ d = tmp_path / "plain"
+ d.mkdir()
+ assert detect_worktree_base(d) is None
+
+
+def test_linked_worktree_resolves_base(base_repo: Path, tmp_path: Path) -> None:
+ wt = tmp_path / "wt"
+ _git(["worktree", "add", "-b", "feature", str(wt)], base_repo)
+ detected = detect_worktree_base(wt)
+ assert detected is not None
+ assert detected.resolve() == base_repo.resolve()
+
+
+def test_submodule_git_file_is_not_a_worktree(base_repo: Path, tmp_path: Path) -> None:
+ # Fake a submodule layout: .git file whose gitdir points at the parent's
+ # modules dir, which does not end in a bare ".git" component.
+ sub = tmp_path / "sub"
+ sub.mkdir()
+ modules = base_repo / ".git" / "modules" / "sub"
+ modules.mkdir(parents=True)
+ (sub / ".git").write_text(f"gitdir: {modules}\n", encoding="utf-8")
+ assert detect_worktree_base(sub) is None
+
+
+def test_base_is_seedable_requires_state_and_db(tmp_path: Path) -> None:
+ repo = tmp_path / "r"
+ (repo / ".repowise").mkdir(parents=True)
+ assert not base_is_seedable(repo)
+ (repo / ".repowise" / "state.json").write_text("{}", encoding="utf-8")
+ assert not base_is_seedable(repo)
+ (repo / ".repowise" / "wiki.db").write_text("", encoding="utf-8")
+ assert base_is_seedable(repo)