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(cli): route decision commands to the worktree's base index (#3398)

Aman308738ef5e11
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index f8e80afbc..661959a2c 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -28,6 +28,7 @@ from repowise.cli.helpers import (
run_async,
)
from repowise.cli.output import emit_json, emit_refusal, format_option, notice_console
+from repowise.cli.worktree import detect_worktree_base
from repowise.core.agents.identity import is_agent_slug
from repowise.core.analysis.decisions.lifecycle import (
ACCEPTER_SESSION_MAX,
@@ -43,11 +44,15 @@ from repowise.core.precedent.currency import describe_decision_currency
_SOURCE_CHOICES: tuple[str, ...] = (*LISTABLE_SOURCES, "all")
-def _resolve_decision_repo(path: str | None, fmt: str = "table"):
+def _resolve_decision_repo(path: str | None, fmt: str = "table", *, needs_store: bool = True):
"""Resolve the repo path for decision subcommands.
Honors workspace auto-detection: in workspace mode without an explicit
path, targets the primary repo and prints a transparency notice.
+
+ With ``needs_store`` (the default) the returned path is the checkout whose
+ index the command should read and write; see :func:`_checkout_with_index`.
+ Commands that only touch config files pass ``needs_store=False``.
"""
target = resolve_command_target(path=path)
@@ -56,9 +61,38 @@ def _resolve_decision_repo(path: str | None, fmt: str = "table"):
primary = target.primary_path()
if primary is None:
raise click.ClickException("Workspace has no primary repo configured.")
- return primary
- assert target.repo_path is not None
- return target.repo_path
+ repo_path = primary
+ else:
+ assert target.repo_path is not None
+ repo_path = target.repo_path
+ return _checkout_with_index(repo_path, fmt) if needs_store else repo_path
+
+
+def _checkout_with_index(repo_path: Path, fmt: str) -> Path:
+ """The checkout whose index a decision command should use.
+
+ A linked worktree that was never indexed answers to its base checkout,
+ the way ``init`` and ``update`` already treat it; otherwise the record
+ lands in a fresh store nothing else reads and is lost with the worktree.
+ With no index anywhere the command refuses instead of creating one.
+ """
+ from repowise.core.persistence.database import has_db_store
+
+ if has_db_store(repo_path):
+ return repo_path
+ base = detect_worktree_base(repo_path)
+ if base is not None and has_db_store(base):
+ notice_console(fmt).print(
+ f"[dim]No index in this worktree; using the base checkout's at {base}.[/dim]"
+ )
+ return base
+ emit_refusal(
+ "no_index",
+ f"No index found at {repo_path}.",
+ fmt,
+ remedy="Run `repowise init` first.",
+ )
+ raise click.exceptions.Exit(1) # emit_refusal already exits; keeps the return type honest
def _describe_signature(acceptance) -> dict[str, str] | None:
diff --git a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
index 8fe177868..7271e4548 100644
--- a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
@@ -252,7 +252,7 @@ def config_show(path: str | None, fmt: str) -> None:
"""Show the resolved capture policy for this repository."""
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
_emit(repo_path, _load(repo_path), fmt)
@@ -268,7 +268,7 @@ def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
from repowise.core.analysis.decisions.policy import preset_policy
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
# A preset names source membership. The harness list and the two agent
# switches are not membership, so applying one leaves them as the caller
# set them.
@@ -317,7 +317,7 @@ def config_discovery(
"""Set the per-update budget for broad session discovery."""
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
fields = {
key: value
for key, value in (
@@ -352,7 +352,7 @@ def config_agent_acceptance(
"""
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
current = _load(repo_path).policy
_apply(repo_path, current.with_agent_acceptance(bool(enabled)), fmt, dry_run)
@@ -376,7 +376,7 @@ def config_capture_prompt(
"""
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
current = _load(repo_path).policy
_apply(repo_path, current.with_capture_prompt(bool(enabled)), fmt, dry_run)
if dry_run:
@@ -437,7 +437,7 @@ def source_list(path: str | None, fmt: str) -> None:
"""List every capture source with its capabilities and current state."""
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
_emit(repo_path, _load(repo_path), fmt)
@@ -467,7 +467,7 @@ def source_set(
if enabled is None and llm is None:
raise click.ClickException("Pass --on/--off or --llm/--no-llm.")
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
current = _load(repo_path).policy
_apply(repo_path, current.with_source(source, enabled=enabled, llm=llm), fmt, dry_run)
@@ -491,6 +491,6 @@ def llm_command(path: str | None, enabled: bool | None, dry_run: bool, fmt: str)
"""
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
- repo_path = _resolve_decision_repo(path, fmt)
+ repo_path = _resolve_decision_repo(path, fmt, needs_store=False)
current = _load(repo_path).policy
_apply(repo_path, current.with_llm(bool(enabled)), fmt, dry_run)
diff --git a/tests/unit/cli/test_decision_batch_review.py b/tests/unit/cli/test_decision_batch_review.py
index 20903868f..69e7ca83b 100644
--- a/tests/unit/cli/test_decision_batch_review.py
+++ b/tests/unit/cli/test_decision_batch_review.py
@@ -161,8 +161,8 @@ def test_an_ambiguous_single_id_refuses_instead_of_crashing(tmp_path: Path) -> N
def test_an_id_shaped_directory_stays_an_id(review_repo: Path, monkeypatch) -> None:
"""Reading a hex token as a path would drop it from the batch and exit 0."""
- monkeypatch.chdir(review_repo.parent)
- (review_repo.parent / "cccc").mkdir()
+ monkeypatch.chdir(review_repo)
+ (review_repo / "cccc").mkdir()
result = CliRunner().invoke(
cli, ["decision", "confirm", "aaaa", "cccc", "--preview", "--format", "json"]
diff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.py
index 07bb48128..3c92add9c 100644
--- a/tests/unit/cli/test_decision_cmd.py
+++ b/tests/unit/cli/test_decision_cmd.py
@@ -53,11 +53,28 @@ def _seed_wiki_db(repo_root: Path, decisions: list[dict]) -> None:
asyncio.run(_build())
+def _create_empty_index(repo_root: Path) -> None:
+ """Create ``.repowise/wiki.db`` with the schema and no rows: an indexed repo.
+
+ ``decision`` commands refuse a checkout with no index, so a repo that is
+ only an empty ``.repowise/`` directory no longer stands in for one.
+ """
+
+ async def _build() -> None:
+ db_path = repo_root / ".repowise" / "wiki.db"
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")
+ await init_db(engine)
+ await engine.dispose()
+
+ asyncio.run(_build())
+
+
@pytest.fixture
def indexed_repo(tmp_path: Path) -> Path:
repo = tmp_path / "repo"
repo.mkdir()
- (repo / ".repowise").mkdir()
+ _create_empty_index(repo)
return repo
@@ -640,3 +657,184 @@ def test_decision_add_stays_silent_when_the_repo_has_no_real_embedder(tmp_path,
assert built == [], "no store should be built without a real embedder"
assert not (tmp_path / ".repowise" / "lancedb").exists()
+
+
+# -- index routing: worktrees and unindexed checkouts --------------------------
+
+
+def _git(args: list[str], cwd: Path) -> None:
+ import subprocess
+
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", *args],
+ cwd=cwd,
+ check=True,
+ capture_output=True,
+ )
+
+
+def base_checkout(tmp_path: Path) -> Path:
+ base = tmp_path / "base"
+ base.mkdir()
+ _git(["init", "-q", "-b", "main"], base)
+ (base / "a.py").write_text("x = 1\n")
+ _git(["add", "."], base)
+ _git(["commit", "-q", "-m", "init"], base)
+ return base
+
+
+def linked_worktree(base_checkout: Path, tmp_path: Path) -> Path:
+ wt = tmp_path / "wt"
+ _git(["worktree", "add", "-q", str(wt), "-b", "feature"], base_checkout)
+ return wt
+
+
+def _stored_titles(repo_root: Path) -> list[str]:
+ import sqlite3
+
+ conn = sqlite3.connect(repo_root / ".repowise" / "wiki.db")
+ try:
+ return [r[0] for r in conn.execute("SELECT title FROM decision_records")]
+ finally:
+ conn.close()
+
+
+_ADD = ["decision", "add", "--title", "Use X", "--decision", "We use X"]
+
+
+def test_add_in_an_unindexed_repo_refuses_and_creates_nothing(tmp_path: Path) -> None:
+ repo = tmp_path / "plain"
+ repo.mkdir()
+
+ result = CliRunner().invoke(cli, [*_ADD, str(repo)])
+
+ assert result.exit_code == 1, result.output
+ assert "No index found" in result.output
+ assert "repowise init" in result.output
+ assert not (repo / ".repowise").exists()
+
+
+def test_add_json_in_an_unindexed_repo_emits_a_refusal_document(tmp_path: Path) -> None:
+ repo = tmp_path / "plain"
+ repo.mkdir()
+
+ result = CliRunner().invoke(cli, [*_ADD, str(repo), "--format", "json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["error"] == "no_index"
+ assert payload["remedy"] == "Run `repowise init` first."
+ assert not (repo / ".repowise").exists()
+
+
+def test_add_in_an_unindexed_worktree_of_an_unindexed_base_refuses(
+ base_checkout: Path, linked_worktree: Path
+) -> None:
+ result = CliRunner().invoke(cli, [*_ADD, str(linked_worktree)])
+
+ assert result.exit_code == 1, result.output
+ assert not (linked_worktree / ".repowise").exists()
+ assert not (base_checkout / ".repowise").exists()
+
+
+def test_add_in_an_unindexed_worktree_writes_to_the_base_index(
+ base_checkout: Path, linked_worktree: Path
+) -> None:
+ _create_empty_index(base_checkout)
+
+ result = CliRunner().invoke(cli, [*_ADD, str(linked_worktree), "--format", "json"])
+
+ assert result.exit_code == 0, result.output
+ assert not (linked_worktree / ".repowise").exists()
+ assert _stored_titles(base_checkout) == ["Use X"]
+
+
+def test_add_from_a_worktree_says_where_the_record_went(
+ base_checkout: Path, linked_worktree: Path
+) -> None:
+ _create_empty_index(base_checkout)
+
+ result = CliRunner().invoke(cli, [*_ADD, str(linked_worktree)])
+
+ assert result.exit_code == 0, result.output
+ assert "using the base checkout's" in result.output
+ assert str(base_checkout) in result.output.replace("\n", "")
+
+
+def test_add_json_from_a_worktree_reports_the_base_as_the_repo(
+ base_checkout: Path, linked_worktree: Path
+) -> None:
+ _create_empty_index(base_checkout)
+
+ result = CliRunner().invoke(cli, [*_ADD, str(linked_worktree), "--format", "json"])
+
+ assert result.exit_code == 0, result.output
+ # Click 8.1 mixes stderr into the captured stdout and 8.2+ keeps them apart,
+ # so lift the document out of the output instead of assuming either. That
+ # the notice itself goes to stderr under --format json is pinned by
+ # test_notice_console_is_stderr_under_json.
+ output = result.output
+ document, _ = json.JSONDecoder().raw_decode(output[output.index("{") :])
+ assert Path(document["repo"]).resolve() == base_checkout.resolve()
+ assert "using the base checkout's" in output
+
+
+def test_a_worktree_with_its_own_index_keeps_writing_to_it(
+ base_checkout: Path, linked_worktree: Path
+) -> None:
+ _create_empty_index(base_checkout)
+ _create_empty_index(linked_worktree)
+
+ result = CliRunner().invoke(cli, [*_ADD, str(linked_worktree)])
+
+ assert result.exit_code == 0, result.output
+ assert _stored_titles(linked_worktree) == ["Use X"]
+ assert _stored_titles(base_checkout) == []
+
+
+def test_list_in_a_worktree_reads_the_base_index(
+ base_checkout: Path, linked_worktree: Path
+) -> None:
+ _seed_wiki_db(base_checkout, [{"id": "aaaaaaaa11111111", "title": "Base decision"}])
+
+ result = CliRunner().invoke(cli, ["decision", "list", str(linked_worktree)])
+
+ assert result.exit_code == 0, result.output
+ assert "Base decision" in result.output
+ assert not (linked_worktree / ".repowise").exists()
+
+
+def test_list_in_an_unindexed_repo_refuses_instead_of_creating_a_store(tmp_path: Path) -> None:
+ repo = tmp_path / "plain"
+ repo.mkdir()
+
+ result = CliRunner().invoke(cli, ["decision", "list", str(repo)])
+
+ assert result.exit_code == 1, result.output
+ assert not (repo / ".repowise").exists()
+
+
+def test_a_configured_database_counts_as_an_index(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo = tmp_path / "plain"
+ repo.mkdir()
+ db = tmp_path / "shared.db"
+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{db.as_posix()}")
+
+ result = CliRunner().invoke(cli, [*_ADD, str(repo)])
+
+ assert result.exit_code == 0, result.output
+ assert db.exists()
+
+
+def test_config_commands_do_not_need_an_index(tmp_path: Path) -> None:
+ repo = tmp_path / "plain"
+ repo.mkdir()
+
+ result = CliRunner().invoke(cli, ["decision", "config", "show", str(repo)])
+
+ assert result.exit_code == 0, result.output
+ assert "No index found" not in result.output
diff --git a/tests/unit/cli/test_decision_cmd_output.py b/tests/unit/cli/test_decision_cmd_output.py
index 7434d99b0..73a03066e 100644
--- a/tests/unit/cli/test_decision_cmd_output.py
+++ b/tests/unit/cli/test_decision_cmd_output.py
@@ -15,7 +15,7 @@ from click.testing import CliRunner
from repowise.cli.main import cli
-from .test_decision_cmd import _seed_wiki_db
+from .test_decision_cmd import _create_empty_index, _seed_wiki_db
@pytest.fixture(autouse=True)
@@ -31,7 +31,8 @@ def _no_embedder(monkeypatch):
@pytest.fixture
def repo(tmp_path: Path) -> Path:
root = tmp_path / "repo"
- (root / ".repowise").mkdir(parents=True)
+ root.mkdir()
+ _create_empty_index(root)
return root