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): a command that reads one workspace repo names that repo (#4559)

Raghav Chamadiyade1852bbf4a9
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index cd7addca0..b42bd14e1 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -60,6 +60,9 @@ Grouped by task; `PATH` and flags are in each command's section.
## Workspace auto-detect (cross-cutting)
Most commands detect a workspace root and route to it, with a one-line `[workspace] …` notice.
+A command that reads one repo (`health`, `dead-code`, `events`, `next`, `doc-drift`, `coverage`,
+`decision`, `impacted-tests`, `costs` without `--all`) names it: `[workspace] health reads one repo:
+carts (primary) of 5 in sockshop; pass --repo <alias> for another`.
| Flag | What it does | Default |
|------|--------------|---------|
@@ -1418,6 +1421,8 @@ repowise events --since 7d --kind bus_factor_drop
| Flag | What it does | Default |
|------|--------------|---------|
| `--path` | Repo path. | cwd |
+| `--repo` | One workspace repo (implies workspace mode). | primary repo |
+| `--no-workspace` | Force single-repo mode. | auto-detect |
| `--since` | `7d`, `12h` or ISO date. | |
| `--kind` | Only this kind. Repeatable. | all kinds |
| `--limit` | 1 to 10000. | `200` |
diff --git a/packages/cli/src/repowise/cli/_helpers/target.py b/packages/cli/src/repowise/cli/_helpers/target.py
index 68b8f3f32..093026011 100644
--- a/packages/cli/src/repowise/cli/_helpers/target.py
+++ b/packages/cli/src/repowise/cli/_helpers/target.py
@@ -98,9 +98,8 @@ class CommandTarget:
``--repo <alias>`` resolves to ``mode="workspace"`` with ``repo_path``
left ``None``, so a command that reads ``repo_path`` directly refuses
- every ``--repo`` call it advertises. Three commands already hand-roll
- this narrowing (``dead-code``, ``health``, ``costs``); this is where it
- belongs, beside :meth:`primary_path` and :meth:`resolve_repo_alias`.
+ every ``--repo`` call it advertises. A command that also prints its
+ scope calls :meth:`narrow` instead.
Raises ``click.ClickException`` when the alias is unknown or the
workspace declares no primary.
@@ -118,6 +117,40 @@ class CommandTarget:
raise click.ClickException("Workspace has no primary repo configured.")
return primary
+ def narrow(self, console_obj: Console, *, command: str, repo_option: bool = True) -> Path:
+ """:meth:`single_repo_path`, after one line saying which repo the command reads.
+
+ For commands that read one repo even from a workspace root, where
+ :meth:`notice` would claim the whole workspace. *repo_option* says
+ whether the command takes ``--repo <alias>``, so the hint names a way
+ to pick another repo that the command offers.
+ """
+ from rich.markup import escape
+
+ repo = self.single_repo_path()
+ if self.is_workspace:
+ assert self.ws_root is not None and self.ws_config is not None
+ role, hint = "", ""
+ alias = self.repo_filter
+ if alias is None:
+ alias, role = self.ws_config.get_primary().alias, " (primary)"
+ hint = (
+ "; pass --repo <alias> for another"
+ if repo_option
+ else "; run it inside another member repo for that one"
+ )
+ console_obj.print(
+ f"[dim]\\[workspace][/dim] {command} reads one repo: "
+ f"[cyan]{escape(alias)}[/cyan]{role} of {len(self.ws_config.repos)} "
+ f"in [cyan]{escape(self.ws_root.name)}[/cyan]{hint}"
+ )
+ elif self.auto_detected and self.ws_root is not None:
+ console_obj.print(
+ f"[dim]\\[single-repo][/dim] {command} reads [cyan]{escape(repo.name)}[/cyan], "
+ f"a repo inside workspace [cyan]{escape(self.ws_root.name)}[/cyan]"
+ )
+ return repo
+
# ------------------------------------------------------------------
# Notice rendering — every command should call this so users always
# know which mode they ended up in.
@@ -153,7 +186,7 @@ class CommandTarget:
if self.auto_detected and self.ws_root is not None:
# A workspace exists upstream but we chose single-repo anyway.
console_obj.print(
- f"[dim][single-repo][/dim] targeting "
+ f"[dim]\\[single-repo][/dim] targeting "
f"[cyan]{self.repo_path}[/cyan] "
f"(workspace also detected at [cyan]{self.ws_root}[/cyan]; "
f"pass --workspace to run across all repos)"
diff --git a/packages/cli/src/repowise/cli/commands/_tool_adapters.py b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
index 7b4be1af9..c3c086038 100644
--- a/packages/cli/src/repowise/cli/commands/_tool_adapters.py
+++ b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
@@ -85,22 +85,7 @@ def resolve_indexed_repo(
no_workspace_flag=no_workspace,
repo_alias=repo_alias,
)
- target.notice(_notices(fmt), command=command)
-
- if target.is_workspace:
- if target.repo_filter is not None:
- picked = target.resolve_repo_alias(target.repo_filter)
- if picked is None:
- raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
- repo_path = picked
- else:
- primary = target.primary_path()
- if primary is None:
- raise click.ClickException("Workspace has no primary repo configured.")
- repo_path = primary
- else:
- assert target.repo_path is not None
- repo_path = target.repo_path
+ repo_path = target.narrow(_notices(fmt), command=command)
from repowise.cli.helpers import REPOWISE_DIR
diff --git a/packages/cli/src/repowise/cli/commands/costs_cmd.py b/packages/cli/src/repowise/cli/commands/costs_cmd.py
index 4be3a6d72..940e44703 100644
--- a/packages/cli/src/repowise/cli/commands/costs_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/costs_cmd.py
@@ -103,34 +103,19 @@ def costs_command(
no_workspace_flag=no_workspace,
repo_alias=repo_alias,
)
- target.notice(notices, command="costs")
# Parsed before the early returns below so ``since`` has one type in every
# json payload: an ISO string normalised by the parser, never the raw
# argument on one path and the normalised form on another.
since_dt = _parse_date(since)
- # Resolve which repo paths to query
- repo_paths: list[Path] = []
- if target.is_workspace:
+ # Resolve which repo paths to query: every member with --all, else one.
+ if target.is_workspace and show_all:
assert target.ws_root is not None and target.ws_config is not None
- if show_all:
- repo_paths = [
- (target.ws_root / e.path).resolve() for e in target.ws_config.repos
- ]
- elif target.repo_filter is not None:
- picked = target.resolve_repo_alias(target.repo_filter)
- if picked is None:
- raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
- repo_paths = [picked]
- else:
- primary = target.primary_path()
- if primary is None:
- raise click.ClickException("Workspace has no primary repo configured.")
- repo_paths = [primary]
+ target.notice(notices, command="costs")
+ repo_paths = [(target.ws_root / e.path).resolve() for e in target.ws_config.repos]
else:
- assert target.repo_path is not None
- repo_paths = [target.repo_path]
+ repo_paths = [target.narrow(notices, command="costs")]
# Filter to repos that have a .repowise/ — otherwise the cost query
# would just return an empty result and confuse the user.
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index f171fe73e..e1cc48325 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -38,14 +38,7 @@ from repowise.core.workspace.update import get_head_commit
def _resolve_coverage_repo(path: str | None, fmt: str = "table") -> Path:
"""Resolve the repo path for coverage subcommands (workspace-aware)."""
target = resolve_command_target(path=path)
- target.notice(notice_console(fmt), command="coverage")
- if target.is_workspace:
- 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
+ return target.narrow(notice_console(fmt), command="coverage", repo_option=False)
async def _repo_file_keys(session, repo_id: str) -> set[str]:
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index 7dd56a12c..2efd4bf09 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -290,24 +290,7 @@ def dead_code_command(
repo_alias=repo_alias,
)
notices = notice_console(fmt)
- target.notice(notices, command="dead-code")
-
- if target.is_workspace:
- if target.repo_filter is not None:
- picked = target.resolve_repo_alias(target.repo_filter)
- if picked is None:
- raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
- repo_path = picked
- else:
- primary = target.primary_path()
- if primary is None:
- raise click.ClickException("Workspace has no primary repo configured.")
- repo_path = primary
- notices.print("[dim] (Tip: pass --repo <alias> to analyze a different repo.)[/dim]")
- else:
- assert target.repo_path is not None
- repo_path = target.repo_path
-
+ repo_path = target.narrow(notices, command="dead-code")
notices.print(f"[bold]repowise dead-code[/bold]: {repo_path}")
config: dict = {
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index 426a39cb4..93f59ed24 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -56,15 +56,7 @@ def _resolve_decision_repo(path: str | None, fmt: str = "table", *, needs_store:
"""
target = resolve_command_target(path=path)
- target.notice(notice_console(fmt), command="decision")
- if target.is_workspace:
- primary = target.primary_path()
- if primary is None:
- raise click.ClickException("Workspace has no primary repo configured.")
- repo_path = primary
- else:
- assert target.repo_path is not None
- repo_path = target.repo_path
+ repo_path = target.narrow(notice_console(fmt), command="decision", repo_option=False)
return _checkout_with_index(repo_path, fmt) if needs_store else repo_path
diff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
index c0c5577ef..faff8de38 100644
--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
@@ -53,8 +53,7 @@ def _repo_path(path: str | None, repo_alias: str | None, no_workspace: bool, fmt
target = resolve_command_target(
path=path, no_workspace_flag=no_workspace, repo_alias=repo_alias
)
- target.notice(ci_notices(fmt), command="doc-drift")
- return target.single_repo_path().resolve()
+ return target.narrow(ci_notices(fmt), command="doc-drift").resolve()
async def _read(root: Path, *, min_confidence: float | None, kinds: tuple[str, ...]) -> Any:
diff --git a/packages/cli/src/repowise/cli/commands/events_cmd.py b/packages/cli/src/repowise/cli/commands/events_cmd.py
index f813b9e03..90ddec146 100644
--- a/packages/cli/src/repowise/cli/commands/events_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/events_cmd.py
@@ -15,6 +15,7 @@ from pathlib import Path
import click
+from repowise.cli.ci import ci_notices
from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async
from repowise.cli.output import emit_json, format_option
@@ -53,19 +54,33 @@ async def _read(root: Path, since: datetime | None, kinds: tuple[str, ...], limi
@click.option("--since", default=None, help="Only events from then on: 7d, 12h or an ISO date.")
@click.option("--kind", "kinds", multiple=True, help="Only this kind (repeatable).")
@click.option("--limit", default=200, show_default=True, type=click.IntRange(1, 10000))
[email protected]("--repo", "repo_alias", default=None, help="In workspace mode, target one repo.")
[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")
@format_option(choices=("table", "json", "jsonl"))
def events_command(
- repo: str | None, since: str | None, kinds: tuple[str, ...], limit: int, fmt: str
+ repo: str | None,
+ since: str | None,
+ kinds: tuple[str, ...],
+ limit: int,
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
) -> None:
- """List typed events (new hotspot, bus factor drop, ...) oldest first."""
+ """List typed events (new hotspot, bus factor drop, ...) oldest first.
+
+ Events belong to one repo: from a workspace root this reads the primary
+ repo; pass --repo <alias> for another.
+ """
from repowise.core.events.model import KINDS, to_cloudevent
unknown = [k for k in kinds if k not in KINDS]
if unknown:
raise click.BadParameter(f"unknown kind(s) {unknown}; known: {sorted(KINDS)}")
- target = resolve_command_target(path=repo, no_workspace_flag=True)
- assert target.repo_path is not None
- read = run_async(_read(Path(target.repo_path).resolve(), _parse_since(since), kinds, limit))
+ target = resolve_command_target(
+ path=repo, no_workspace_flag=no_workspace, repo_alias=repo_alias
+ )
+ root = target.narrow(ci_notices(fmt), command="events").resolve()
+ read = run_async(_read(root, _parse_since(since), kinds, limit))
if read is None:
console.print("No index found. Run `repowise init` first.")
raise SystemExit(1)
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
index 2073cbd81..6dcde9a5f 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -386,19 +386,7 @@ def _resolve_repo_path(
target = resolve_command_target(
path=path, no_workspace_flag=no_workspace, repo_alias=repo_alias
)
- target.notice(status, command="health")
- if not target.is_workspace:
- assert target.repo_path is not None
- return target.repo_path
- if target.repo_filter is not None:
- picked = target.resolve_repo_alias(target.repo_filter)
- if picked is None:
- raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
- return picked
- primary = target.primary_path()
- if primary is None:
- raise click.ClickException("Workspace has no primary repo configured.")
- return primary
+ return target.narrow(status, command="health")
def _render_stored_view(repo_path: Path, status: Any, opts: _Options) -> bool:
diff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
index bd71e0392..70a922c65 100644
--- a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py
@@ -64,14 +64,7 @@ _TABLE_CANDIDATES = 10
def _resolve_repo_path(path: str | None, fmt: str):
"""Resolve the repo path (workspace-aware), mirroring ``coverage``."""
target = resolve_command_target(path=path)
- target.notice(ci_notices(fmt), command="impacted-tests")
- if target.is_workspace:
- 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
+ return target.narrow(ci_notices(fmt), command="impacted-tests", repo_option=False)
@click.command("impacted-tests")
diff --git a/packages/cli/src/repowise/cli/commands/next_cmd.py b/packages/cli/src/repowise/cli/commands/next_cmd.py
index 4a6b82ea7..1ae265195 100644
--- a/packages/cli/src/repowise/cli/commands/next_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/next_cmd.py
@@ -166,8 +166,7 @@ def next_command(
target = resolve_command_target(
path=path, no_workspace_flag=no_workspace, repo_alias=repo_alias
)
- target.notice(notice_console(fmt), command="next")
- root = target.single_repo_path().resolve()
+ root = target.narrow(notice_console(fmt), command="next").resolve()
view = load_view(root)
if fmt == "json":
diff --git a/tests/unit/cli/test_command_target.py b/tests/unit/cli/test_command_target.py
index 58933d561..32623ebe1 100644
--- a/tests/unit/cli/test_command_target.py
+++ b/tests/unit/cli/test_command_target.py
@@ -255,3 +255,61 @@ def test_single_repo_path_refuses_an_unknown_alias(fake_workspace, chdir):
with pytest.raises(click.ClickException):
target.single_repo_path()
+
+
+# ---------------------------------------------------------------------------
+# narrow: the one repo, with the scope said in one line
+# ---------------------------------------------------------------------------
+
+
+def _said(target, **kwargs) -> tuple[Path, str]:
+ from io import StringIO
+
+ from rich.console import Console
+
+ buf = StringIO()
+ picked = target.narrow(Console(file=buf, width=300), command="health", **kwargs)
+ return picked, buf.getvalue()
+
+
+def test_narrow_from_the_root_names_the_primary_not_the_workspace(fake_workspace, chdir):
+ chdir(fake_workspace)
+ picked, said = _said(resolve_command_target())
+
+ assert picked == fake_workspace / "backend"
+ assert said.strip() == (
+ f"[workspace] health reads one repo: backend (primary) of 2 in {fake_workspace.name}; "
+ "pass --repo <alias> for another"
+ )
+
+
+def test_narrow_names_the_picked_alias(fake_workspace, chdir):
+ chdir(fake_workspace)
+ picked, said = _said(resolve_command_target(repo_alias="frontend"))
+
+ assert picked == fake_workspace / "frontend"
+ assert "reads one repo: frontend of 2" in said and "--repo" not in said
+
+
+def test_narrow_hint_matches_a_command_without_repo_option(fake_workspace, chdir):
+ chdir(fake_workspace)
+ _, said = _said(resolve_command_target(), repo_option=False)
+
+ assert "--repo" not in said and "run it inside another member repo" in said
+
+
+def test_narrow_inside_a_member_repo_says_so(fake_workspace, chdir):
+ chdir(fake_workspace / "backend")
+ picked, said = _said(resolve_command_target())
+
+ assert picked == fake_workspace / "backend"
+ # The tag survives Rich markup, and no --workspace promise is made.
+ assert said.strip() == (
+ f"[single-repo] health reads backend, a repo inside workspace {fake_workspace.name}"
+ )
+
+
+def test_narrow_is_silent_for_an_explicit_single_repo(fake_workspace):
+ picked, said = _said(resolve_command_target(path=str(fake_workspace / "backend")))
+
+ assert picked == fake_workspace / "backend" and said == ""
diff --git a/tests/unit/cli/test_events_cmd.py b/tests/unit/cli/test_events_cmd.py
index 44edef7d0..b93989b82 100644
--- a/tests/unit/cli/test_events_cmd.py
+++ b/tests/unit/cli/test_events_cmd.py
@@ -82,3 +82,26 @@ def test_no_events_says_whether_runs_could_be_compared(tmp_path):
assert got.exit_code == 0, got.output
# No snapshot is stored, so no events is not a quiet history.
assert "No events yet: 0 component snapshot(s) stored" in got.output
+
+
+def test_a_workspace_root_reads_one_named_repo(tmp_path, monkeypatch):
+ """From a workspace root events read the primary repo, say so, and take --repo."""
+ _repo(tmp_path)
+ (tmp_path / "other" / ".git").mkdir(parents=True)
+ (tmp_path / ".repowise-workspace.yaml").write_text(
+ "version: 1\ndefault_repo: repo\nrepos:\n"
+ " - path: repo\n alias: repo\n is_primary: true\n"
+ " - path: other\n alias: other\n",
+ encoding="utf-8",
+ )
+ monkeypatch.chdir(tmp_path)
+ runner = CliRunner()
+
+ got = runner.invoke(events_command, [])
+ assert got.exit_code == 0, got.output
+ assert "events reads one repo: repo (primary) of 2" in got.output
+ assert "dead_code_growth" in got.output and "2 event(s)" in got.output
+
+ other = runner.invoke(events_command, ["--repo", "other"])
+ assert "events reads one repo: other of 2" in other.output
+ assert other.exit_code == 1 and "No index found" in other.output
diff --git a/tests/unit/cli/test_health_cmd_controls.py b/tests/unit/cli/test_health_cmd_controls.py
index 22c0e99ad..66166b60a 100644
--- a/tests/unit/cli/test_health_cmd_controls.py
+++ b/tests/unit/cli/test_health_cmd_controls.py
@@ -77,7 +77,7 @@ def test_the_trend_says_the_controls_do_not_reach_it() -> None:
resolve.return_value = SimpleNamespace(
is_workspace=False,
repo_path=Path("."),
- notice=lambda *a, **k: None,
+ narrow=lambda *a, **k: Path("."),
)
result = runner.invoke(cli, ["health", "--trend", "--counts", "code_shape"])
render.assert_called_once()
@@ -95,7 +95,7 @@ def test_the_trend_stays_quiet_when_no_control_was_passed() -> None:
resolve.return_value = SimpleNamespace(
is_workspace=False,
repo_path=Path("."),
- notice=lambda *a, **k: None,
+ narrow=lambda *a, **k: Path("."),
)
result = runner.invoke(cli, ["health", "--trend"])
assert "do not apply to it" not in result.output
@@ -168,7 +168,7 @@ def _mostly_unanalysed_output(*args: str) -> str:
resolve.return_value = SimpleNamespace(
is_workspace=False,
repo_path=Path("."),
- notice=lambda *a, **k: None,
+ narrow=lambda *a, **k: Path("."),
)
result = runner.invoke(cli, ["health", *args])
assert result.exit_code == 0, result.output
diff --git a/tests/unit/cli/test_health_cmd_score_live.py b/tests/unit/cli/test_health_cmd_score_live.py
index f913d5d5e..607eebd0d 100644
--- a/tests/unit/cli/test_health_cmd_score_live.py
+++ b/tests/unit/cli/test_health_cmd_score_live.py
@@ -30,7 +30,7 @@ def _git(repo: Path, *args: str) -> None:
def _invoke(repo: Path, *args: str):
with patch.object(health_module, "resolve_command_target") as resolve:
resolve.return_value = SimpleNamespace(
- is_workspace=False, repo_path=repo, notice=lambda *a, **k: None
+ is_workspace=False, repo_path=repo, narrow=lambda *a, **k: repo
)
return CliRunner().invoke(cli, ["health", *args])
diff --git a/tests/unit/cli/test_health_cmd_withheld.py b/tests/unit/cli/test_health_cmd_withheld.py
index e6fec385a..1115fc41f 100644
--- a/tests/unit/cli/test_health_cmd_withheld.py
+++ b/tests/unit/cli/test_health_cmd_withheld.py
@@ -75,7 +75,7 @@ def _run(monkeypatch, *args: str) -> tuple[str, str]:
patch.object(health_module, "console", console),
):
resolve.return_value = SimpleNamespace(
- is_workspace=False, repo_path=Path("."), notice=lambda *a, **k: None
+ is_workspace=False, repo_path=Path("."), narrow=lambda *a, **k: Path(".")
)
result = runner.invoke(cli, ["health", *args])
assert result.exit_code == 0, result.output