Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(init): pick a workspace's repos with --repos, and workspace add builds documentation from code by default (#4260)
Raghav Chamadiya0cd478e3dfb1
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 5327e831d..a80e3c0e8 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -190,7 +190,8 @@ All three reach the indexing knobs; the LLM-only knobs appear only when model-wr| `--yes` / `-y` | Skip confirmation prompts || `--dry-run` | Show the generation plan and cost estimate. Writes no wiki || `--test-run` | Write docs with the model for only the top 10 files (by PageRank). Not with `--no-prose` or `--mode fast` |-| `--all` | In multi-repo mode, index every detected repo without prompting |+| `--all` | In a folder with several repos, index every detected repo without prompting. `--yes` and a piped stdin do the same and print which repos they took |+| `--repos` | In a folder with several repos, index only these, with no picker: `--repos api,web`. Each name is a repo's alias, directory name, or its path relative to the folder when two repos share a name. In a new workspace the first one listed is primary; an existing workspace keeps its primary. An unknown name stops the run and lists the available ones || `--no-workspace` | Force single-repo mode even when invoked from a workspace root (indexes only the target PATH instead of fanning out across workspace repos) || `--progress` | `rich` (default): a live checklist in a terminal, one short line per step (at most 100 columns) anywhere else. `json`: one JSON event per line on stdout, ending with a summary line; see below. |@@ -214,6 +215,7 @@ repowise init --no-editor-setup --yes # index only, leave globalrepowise init --provider openai --yes --no-save-key # CI: index, but never write the key to diskrepowise init . # workspace moderepowise init . --no-prose -x "node_modules/" # workspace, no LLM+repowise init . --yes --repos api,web # workspace, two of its reposrepowise init . --no-workspace # force single-repo, even in a workspace root```@@ -1897,13 +1899,13 @@ Show all repos in the workspace with their index status.Add a new repo to an existing workspace and index it.-This defaults to `--index --docs` when a provider is configured, the added repo is indexed and gets LLM doc generation in one step, with a cost-gate prompt before any tokens are spent. Pass `--no-docs` to skip generation, or `--no-index` to only register the entry. The provider, model, embedder, and exclude patterns are inherited from the primary repo's `.repowise/config.yaml` unless overridden.+By default the added repo is indexed and its documentation is built from code, with no model calls, so it never spends. Pass `--docs` (or `--provider`) to have a model write it, `--no-docs` to index only, or `--no-index` to only register the entry. The provider, model, embedder, and exclude patterns are inherited from the primary repo's `.repowise/config.yaml` unless overridden.| Flag | Description ||------|-------------|| `--alias` | Short name for the repo (defaults to directory name) || `--index` / `--no-index` | Run the index pipeline (default: on) |-| `--docs` / `--no-docs` | Run LLM doc generation (default: on when a provider is configured) |+| `--docs` / `--no-docs` | `--docs`: documentation written by the model. `--no-docs`: index only. Default: documentation built from code || `--provider` / `--model` | Override the inherited provider/model || `--concurrency` | Max concurrent LLM calls for this repo's generation || `--primary` | Mark this repo as the workspace default |@@ -1911,7 +1913,8 @@ This defaults to `--index --docs` when a provider is configured, the added repo```bashrepowise workspace add ../new-service --alias api-gateway-repowise workspace add ../mobile --no-docs # index, no LLM+repowise workspace add ../mobile --no-docs # index only, no documentation+repowise workspace add ../billing --docs # documentation written by the modelrepowise workspace add ../shared --no-index # register only```diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex da03b15a4..0cf7664bd 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -58,6 +58,10 @@ through provider setup, then indexes each repo, generates its docs (unless`--no-prose`), runs the cross-repo analysis, and registers the MCP server withyour editors.+To skip the picker, `--repos api,web` indexes only those repos (by alias,+directory name, or relative path) and makes the first one primary. `--yes`,+`--all` or a piped stdin take every repo and print which ones.+```bashrepowise status --workspace # workspace statusrepowise workspace list # repos and index state@@ -95,7 +99,7 @@ in the [CLI reference](../reference/CLI_REFERENCE.md#workspace-commands).|---------|--------------|| `repowise init .` | Initialize the workspace: scan for repos, select, index (`--no-prose` for a free structure-only wiki, `-x` to exclude globs) || `repowise workspace list` | Repos in the workspace with their index status |-| `repowise workspace add <path>` | Add and index a repo (`--alias`, `--no-docs`, `--no-index`) |+| `repowise workspace add <path>` | Add and index a repo, documentation built from code (`--alias`, `--docs` for model-written, `--no-docs`, `--no-index`) || `repowise workspace remove <alias>` | Remove a repo from the workspace (files are not deleted) || `repowise workspace scan` | Find repos not yet added || `repowise workspace set-default <alias>` | Change the default repo for MCP queries |diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py b/packages/cli/src/repowise/cli/commands/init_cmd/_options.pyindex 48a8c5f23..49655ed34 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py@@ -51,6 +51,7 @@ class InitOptions:include_submodules: boolno_workspace: boolinit_all: bool+ repos: str | Noneonboarding: boolmax_file_pages_opt: int | Nonecoverage_report: tuple[str, ...]diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_repos.py b/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_repos.pynew file mode 100644index 000000000..868c24f60--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_repos.py@@ -0,0 +1,96 @@+"""Which repos a multi-repo ``repowise init`` indexes, and which one is primary."""++from __future__ import annotations++import sys+from typing import Any++import click++from repowise.cli.helpers import console+from repowise.cli.ui.brand import WARN+from repowise.cli.ui.workspace_selection import (+ interactive_primary_select,+ interactive_repo_select,+ match_repo_names,+)++from ._workspace_config import WorkspacePick++#: Names shown in the all-repos line before it says "and N more".+_NAMES_SHOWN = 10+++def split_repo_names(raw: str | None) -> list[str]:+ """``--repos a,b , c`` as ``["a", "b", "c"]``; empty when the flag is absent."""+ return [part.strip() for part in (raw or "").split(",") if part.strip()]+++def check_repos_flag(repos: str | None, *, init_all: bool, is_workspace: bool) -> None:+ """Reject ``--repos`` where it cannot apply, before any indexing starts."""+ if not repos:+ return+ if init_all:+ raise click.UsageError("--repos and --all contradict each other. Pass one.")+ if not is_workspace:+ raise click.UsageError(+ "--repos picks repos in a folder that holds several; this run indexes one repo."+ )+++def select_workspace_repos(+ scan: Any, *, repo_names: list[str], select_all: bool+) -> WorkspacePick | None:+ """The repos to index and the primary; None when none were selected.++ ``--repos`` wins over everything and never prompts. Otherwise ``--yes``,+ ``--all`` or a non-terminal stdin take every detected repo (the first is+ primary): asking a pipe would end the run with an EOFError before anything+ was done.+ """+ root = scan.root+ if repo_names:+ try:+ selected = match_repo_names(scan.repos, repo_names, root)+ except ValueError as exc:+ raise click.UsageError(f"--repos: {exc}") from exc+ # The first name listed is primary only for a new workspace; an existing+ # workspace keeps its primary (see repos_primary_line).+ return WorkspacePick(selected, root, selected[0].alias, selected[0], False)++ select_all = select_all or not sys.stdin.isatty()+ if select_all:+ selected = list(scan.repos)+ console.print(all_repos_line(selected))+ else:+ selected = interactive_repo_select(console, scan.repos, root)+ if not selected:+ console.print(f"[{WARN}]No repositories selected. Aborting.[/]")+ return None+ primary_alias = (+ 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])+ # 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 repos_primary_line(default_repo: str | None, pick: WorkspacePick) -> str:+ """The primary a ``--repos`` run ended with, and where it came from."""+ if default_repo and default_repo != pick.primary_alias:+ return f" Primary: [bold]{default_repo}[/bold] (kept from the workspace)\n"+ return f" Primary: [bold]{pick.primary_alias}[/bold] (first in --repos)\n"+++def all_repos_line(repos: list[Any]) -> str:+ """One line naming every repo a promptless run takes, and how to pick fewer."""+ names = [r.alias for r in repos]+ shown = ", ".join(names[:_NAMES_SHOWN])+ if len(names) > _NAMES_SHOWN:+ shown += f" and {len(names) - _NAMES_SHOWN} more"+ example = ",".join(names[:2])+ return (+ f" Indexing all {len(names)} repos: {shown}.\n"+ f" [dim]Pick some with --repos {example}[/dim]\n"+ )diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex 3f9f3ae80..e5a9ee43f 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -60,6 +60,7 @@ from ._questions import (_offer_fast_mode,)from ._seed import delegate_to_seeded_update+from ._workspace_repos import check_repos_flag, split_repo_namesfrom .workspace import _workspace_init__all__ = [@@ -91,6 +92,7 @@ def _run_workspace_init(opts: InitOptions, scan: Any) -> None:_workspace_init(scan=scan,init_all=opts.init_all,+ repo_names=split_repo_names(opts.repos),exclude_patterns=list(opts.exclude),commit_limit=opts.commit_limit,follow_renames=opts.follow_renames,@@ -350,7 +352,22 @@ def _run_workspace_init(opts: InitOptions, scan: Any) -> None:"init_all",is_flag=True,default=False,- help="In multi-repo mode, index all detected repos without prompting.",+ help=(+ "In a folder with several repos, index every detected repo without "+ "prompting. --yes and a piped stdin do the same; use --repos to pick some."+ ),+)+ "--repos",+ "repos",+ default=None,+ metavar="NAMES",+ help=(+ "In a folder with several repos, index only these, with no picker. "+ "Comma-separated names (alias, directory name, or path relative to the "+ "folder when two repos share a name). In a new workspace the first one "+ "listed is primary; an existing workspace keeps its primary."+ ),)@click.option("--onboarding/--no-onboarding",@@ -490,9 +507,11 @@ def _run_init(opts: InitOptions) -> None:scan = scan_for_repos(repo_path, include_submodules=opts.include_submodules)+ is_workspace = len(scan.repos) > 1 and not opts.no_workspace+ check_repos_flag(opts.repos, init_all=opts.init_all, is_workspace=is_workspace)if delegate_to_seeded_update(opts, repo_path, scan):return- if len(scan.repos) > 1 and not opts.no_workspace:+ if is_workspace:_run_workspace_init(opts, scan)returndiff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex fbbe5579f..ad265f126 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -58,9 +58,7 @@ from repowise.cli.ui import (WARN,interactive_advanced_config,interactive_mode_select,- interactive_primary_select,interactive_provider_config_select,- interactive_repo_select,load_dotenv,print_banner,progress_steps,@@ -76,6 +74,7 @@ from ._exit import COST_UNCONFIRMED_BUILT, exit_on_gapsfrom ._ingest import structural_generation_configfrom ._interactive import offer_distill_rewrite_hook, offer_hook_installfrom ._workspace_config import WorkspacePick, build_workspace_config+from ._workspace_repos import repos_primary_line, select_workspace_reposfrom .generation import (CostGateDeclined,concept_page_count,@@ -778,6 +777,7 @@ def _workspace_init(*,scan: Any,init_all: bool,+ repo_names: list[str],exclude_patterns: list[str],commit_limit: int | None,follow_renames: bool,@@ -823,10 +823,7 @@ def _workspace_init(print_banner(console, repo_name=f"Workspace: {root.name}")console.print(f" Detected [bold]{len(scan.repos)}[/bold] repositories in {root}\n")- # --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.- pick = _select_workspace_repos(scan, select_all=init_all or yes or not sys.stdin.isatty())+ pick = select_workspace_repos(scan, repo_names=repo_names, select_all=init_all or yes)if pick is None:returnselected, primary_alias, primary_repo = pick.selected, pick.primary_alias, pick.primary_repo@@ -863,6 +860,8 @@ def _workspace_init(answers, primary_repo, embedder_name, yes=yes, save_key=save_key)ws_config = _workspace_config(pick, ask=sys.stdin.isatty() and not yes, dry_run=dry_run)+ if repo_names:+ console.print(repos_primary_line(ws_config.default_repo, pick))from repowise.core.ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMIT@@ -927,24 +926,6 @@ def _workspace_init(exit_on_gaps(_workspace_gaps(ctx, totals))-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)- )- if not selected:- console.print(f"[{WARN}]No repositories selected. Aborting.[/]")- return None- primary_alias = (- 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])- # 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(ws_config: Any,root: Path,diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.pyindex 1af8a98a3..f1a3e84bf 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.py@@ -14,7 +14,7 @@ from repowise.cli.helpers import (run_async,warn,)-from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode+from repowise.core.docs_mode import DocsMode, docs_mode_state_fields, resolve_docs_modefrom repowise.core.index_scope import fast_to_full_commandif TYPE_CHECKING:@@ -22,39 +22,19 @@ if TYPE_CHECKING:def _resolve_docs_flag(- *,- run_docs: bool | None,- provider_name: str | None,- ws_root: Path,- ws_config: WorkspaceConfig, # type: ignore[name-defined]-) -> tuple[bool, str | None]:- """Decide whether ``workspace add`` should generate docs by default.-- Priority:- 1. Explicit ``--docs`` or ``--no-docs``.- 2. ``--provider`` flag forces docs ON.- 3. A provider resolves for the primary repo (its ``config.yaml``, the- global default, ``REPOWISE_PROVIDER``, or a detectable API key) →- docs ON, reusing the same provider settings.- 4. Otherwise docs OFF, with a skip reason for the completion notice.+ *, run_docs: bool | None, provider_name: str | None+) -> tuple[DocsMode, str | None]:+ """The docs mode ``workspace add`` runs, and why there are none when off.++ ``--no-docs`` indexes only. ``--docs`` or ``--provider`` writes the+ documentation with a model. Otherwise it is built from code: a configured+ provider or a key in the environment is never a reason to spend unasked."""- if run_docs is True:- return True, Noneif run_docs is False:- return False, "--no-docs flag"- if provider_name is not None:- return True, None-- # The shared resolver: the primary repo's config.yaml, the global default,- # REPOWISE_PROVIDER, or a detectable API key.- from repowise.core.providers.llm.resolve import resolve_llm-- primary = ws_config.get_primary()- primary_path = (ws_root / primary.path).resolve() if primary is not None else None- if resolve_llm(primary_path).provider is not None:- return True, None-- return False, "no provider configured"+ return "none", "--no-docs flag"+ if run_docs or provider_name is not None:+ return "llm", None+ return "deterministic", Nonedef _inherit_distill_verdict(repo_path: Path, primary_cfg: dict) -> None:@@ -123,14 +103,17 @@ def _run_index_for_repo(ws_root: Path,ws_config: WorkspaceConfig, # type: ignore[name-defined]*,- generate_docs: bool = False,+ docs_mode: DocsMode = "none",provider_name: str | None = None,model: str | None = None,concurrency: int = 10,docs_skip_reason: str | None = None,save_key: bool = True,) -> None:- """Run the ingestion pipeline on a single repo, optionally with LLM docs.+ """Run the ingestion pipeline on a single repo, then build its documentation.++ *docs_mode* ``llm`` writes it with a model, ``deterministic`` builds it+ from code, ``none`` skips it.Updates the workspace config entry, persists results to the per-repoDB, writes ``.repowise/state.json`` (so ``repowise update`` knows the@@ -148,17 +131,16 @@ def _run_index_for_repo(exclude_patterns = list(primary_cfg.get("exclude_patterns") or [])commit_limit = primary_cfg.get("commit_limit")- # ``provider`` is None exactly when docs will not run, so it doubles as- # the docs-on flag from here on.+ # ``provider`` is None exactly when no model runs.provider = None- if generate_docs:- provider, failure = _resolve_docs_provider(+ if docs_mode == "llm":+ provider = _resolve_docs_provider(repo_path,provider_name or primary_cfg.get("provider"),model or primary_cfg.get("model"),)- if failure is not None:- docs_skip_reason = failure+ if provider is None:+ docs_mode = "deterministic"ensure_repowise_dir(repo_path)_inherit_distill_verdict(repo_path, primary_cfg)@@ -170,26 +152,24 @@ def _run_index_for_repo(warn(f"Indexing failed for '{alias}': {exc}")return- # Run LLM doc generation through the existing single-repo init pathway- # so we get cost gating, cascading, and full parity with `repowise init`.generated_pages = 0resolved_reasoning = resolve_reasoning(config=primary_cfg)- if provider is not None:- try:- generated_pages = _generate_docs_for_added_repo(- repo_path=repo_path,- provider=provider,- embedder_name=embedder_name,- concurrency=concurrency,- reasoning=resolved_reasoning,- exclude_patterns=exclude_patterns,- )- console.print(f" [green]✓[/green] Generated {generated_pages} pages")- except Exception as exc:- console.print(f" [yellow]Doc generation failed: {exc}[/yellow]")- docs_skip_reason = f"generation error: {exc}"+ if docs_mode != "none":+ generated_pages, error = _build_added_repo_docs(+ repo_path=repo_path,+ provider=provider,+ embedder_name=embedder_name,+ concurrency=concurrency,+ reasoning=resolved_reasoning,+ exclude_patterns=exclude_patterns,+ )+ if error is not None:+ docs_skip_reason = error+ # A model run keeps its provider state so `update --docs` retries it.+ if provider is None:+ docs_mode = "none"- head, state = _save_added_repo_state(repo_path, provider, generated_pages)+ head, state = _save_added_repo_state(repo_path, provider, generated_pages, docs_mode)# Persist provider settings into the added repo's config.yaml so future# `repowise update` runs don't have to re-prompt.@@ -217,6 +197,22 @@ def _run_index_for_repo()+def _build_added_repo_docs(*, provider: object | None, **kwargs: object) -> tuple[int, str | None]:+ """Generate the added repo's documentation as ``(pages, error)``; never raises."""+ try:+ pages = _generate_docs_for_added_repo(provider=provider, **kwargs) # type: ignore[arg-type]+ except Exception as exc:+ console.print(f" [yellow]Documentation failed: {exc}[/yellow]")+ return 0, f"generation error: {exc}"+ source = (+ "built from code"+ if provider is None+ else f"written by {getattr(provider, 'model_name', 'the model')}"+ )+ console.print(f" [green]✓[/green] Documentation: {pages} pages, {source}")+ return pages, None++def _load_primary_config(ws_root: Path,ws_config: WorkspaceConfig, # type: ignore[name-defined]@@ -239,24 +235,26 @@ def _load_primary_config(def _resolve_docs_provider(repo_path: Path, provider_name: str | None, model: str | None-) -> tuple[object | None, str | None]:- """Resolve the docs provider once, as ``(provider, failure_reason)``.+) -> object | None:+ """The model provider, or None (with a notice) when it does not resolve.- If docs were requested but provider resolution fails, fall back to- index-only with a loud notice instead of silently producing an empty wiki.+ The caller then builds the documentation from code rather than leave the+ repo with none."""from repowise.cli.helpers import resolve_providertry:provider = resolve_provider(provider_name, model, repo_path=repo_path)except Exception as exc:- console.print(f" [yellow]Provider unavailable ({exc}); skipping docs.[/yellow]")- return None, f"provider failure: {exc}"+ console.print(+ f" [yellow]Provider unavailable ({exc}); building documentation from code.[/yellow]"+ )+ return Noneconsole.print(f" Provider: [cyan]{provider.provider_name}[/cyan] / "f"Model: [cyan]{provider.model_name}[/cyan]")- return provider, None+ return providerdef _index_added_repo(@@ -284,7 +282,7 @@ def _index_added_repo(def _save_added_repo_state(- repo_path: Path, provider: object | None, generated_pages: int+ repo_path: Path, provider: object | None, generated_pages: int, docs_mode: DocsMode) -> tuple[str | None, dict]:"""Write ``state.json`` so `repowise update` has a baseline commit.@@ -297,9 +295,7 @@ def _save_added_repo_state(state: dict = {"last_sync_commit": head,"total_pages": generated_pages,- # No template fallback on this path: without a provider the added repo- # is indexed with no pages at all.- **docs_mode_state_fields("llm" if provider is not None else "none"),+ **docs_mode_state_fields(docs_mode),# The full index just walked git under the current history rules.GIT_HISTORY_VERSION_KEY: GIT_HISTORY_VERSION,}@@ -341,7 +337,7 @@ def _record_in_workspace(def _generate_docs_for_added_repo(*,repo_path: Path,- provider: object,+ provider: object | None,embedder_name: str,concurrency: int,reasoning: str,@@ -349,6 +345,8 @@ def _generate_docs_for_added_repo() -> int:"""Generate wiki pages for a newly-added workspace repo.+ With no *provider* the pages are built from code: templates, no model call.+Lives in this module (rather than importing from init_cmd) to avoidcircular imports — init_cmd is large and pulls in CLI UI helpers thatwould explode the import graph. Uses the same generation primitives@@ -382,8 +380,14 @@ def _generate_docs_for_added_repo(from repowise.core.repo_config import load_repo_configrepo_cfg = load_repo_config(repo_path)+ deterministic = provider is None+ if deterministic:+ from repowise.core.providers.llm.template import TemplateProvider++ provider = TemplateProvider()config = GenerationConfig.from_repo_config(repo_cfg,+ deterministic=deterministic,max_concurrency=concurrency,reasoning=reasoning,wiki_style=repo_cfg.get("wiki_style", "comprehensive"),diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/group.pyindex d56bc5b2d..e8ca439bf 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py@@ -121,9 +121,9 @@ def workspace_list(path: str | None) -> None:"run_docs",default=None,help=(- "Generate LLM documentation pages after indexing. Defaults to ON when a "- "provider is configured (in the primary repo's config or via env), OFF "- "otherwise. Skipped silently when --no-index is passed."+ "--docs writes the documentation with a model (the primary repo's "+ "provider, or --provider). --no-docs indexes only. Default: documentation "+ "built from code, with no model calls and no key. Ignored with --no-index."),)@click.option(@@ -162,17 +162,13 @@ def workspace_add(save_key: bool,verbose: bool,) -> None:- """Add a repo to the workspace and (by default) index + generate docs for it.+ """Add a repo to the workspace, index it and build its documentation.PATH is a relative or absolute path to a git repository.- Defaults are designed so the repo immediately appears with complete- intelligence in the web UI and MCP server:- - ``--index`` (default ON) runs the full ingestion pipeline- - ``--docs`` (auto) generates wiki pages when a provider is- available, otherwise skips with a notice- Use ``--no-index`` to only register the entry without indexing, or- ``--no-docs`` to index without LLM generation.+ By default the repo is indexed and its documentation is built from code,+ with no model calls. Pass --docs (or --provider) to have a model write it,+ --no-docs to index only, or --no-index to only register the entry."""configure_cli_logging(verbose=verbose)@@ -225,11 +221,8 @@ def workspace_add(return# Resolve whether docs should run.- resolved_docs, docs_skip_reason = _resolve_docs_flag(- run_docs=run_docs,- provider_name=provider_name,- ws_root=ws_root,- ws_config=ws_config,+ docs_mode, docs_skip_reason = _resolve_docs_flag(+ run_docs=run_docs, provider_name=provider_name)_run_index_for_repo(@@ -237,7 +230,7 @@ def workspace_add(alias,ws_root,ws_config,- generate_docs=resolved_docs,+ docs_mode=docs_mode,provider_name=provider_name,model=model,concurrency=concurrency,diff --git a/packages/cli/src/repowise/cli/ui/workspace_selection.py b/packages/cli/src/repowise/cli/ui/workspace_selection.pyindex 33313d477..c6794339d 100644--- a/packages/cli/src/repowise/cli/ui/workspace_selection.py+++ b/packages/cli/src/repowise/cli/ui/workspace_selection.py@@ -135,6 +135,38 @@ def parse_selection(raw: str, count: int) -> list[int] | None:return result+def match_repo_names(repos: list[Any], names: list[str], root: Any = None) -> list[Any]:+ """The repos *names* pick, in the order named.++ A name matches a repo's alias, its directory name, or its path relative to+ *root* (the column the picker shows), case-insensitively. A name two repos+ share is ambiguous: the path tells them apart. Raises ``ValueError`` with a+ message that names every bad name and what would work instead.+ """+ picked: list[Any] = []+ seen: set[str] = set()+ unknown: list[str] = []+ for raw in names:+ name = raw.replace("\\", "/").strip("/").casefold()+ hits = [+ r+ for r in repos+ if name in (r.alias.casefold(), r.name.casefold(), _display_path(r, root).casefold())+ ]+ if not hits:+ unknown.append(raw)+ elif len(hits) > 1:+ paths = ", ".join(_display_path(r, root) for r in hits)+ raise ValueError(f"'{raw}' matches {len(hits)} repos ({paths}). Name one by its path.")+ elif hits[0].alias not in seen:+ seen.add(hits[0].alias)+ picked.append(hits[0])+ if unknown:+ available = ", ".join(_display_path(r, root) for r in repos)+ raise ValueError(f"Unknown repo: {', '.join(unknown)}. Available: {available}.")+ return picked++def interactive_primary_select(console: Console,repos: list[Any],diff --git a/tests/unit/cli/test_workspace_add_defaults.py b/tests/unit/cli/test_workspace_add_defaults.pyindex 2ea8e9f57..8be1c69d4 100644--- a/tests/unit/cli/test_workspace_add_defaults.py+++ b/tests/unit/cli/test_workspace_add_defaults.py@@ -1,10 +1,8 @@-"""Tests for the new ``repowise workspace add`` defaults.+"""``repowise workspace add`` defaults.-The most important behavior shift in Phase A: ``workspace add`` now runs-index + docs by default, and surfaces an honest "no docs because ..."-notice when generation is skipped. These tests pin the decision matrix-in :func:`_resolve_docs_flag` so the auto-on/auto-off contract doesn't-silently regress.+By default an added repo gets documentation built from code: a configured+provider or a key in the environment never makes it spend unasked. These tests+pin the decision matrix in :func:`_resolve_docs_flag`."""from __future__ import annotations@@ -48,87 +46,30 @@ def _clear_provider_env(monkeypatch):monkeypatch.delenv(key, raising=False)-def test_explicit_yes_wins(ws):- ws_root, cfg = ws- docs, reason = _resolve_docs_flag(- run_docs=True,- provider_name=None,- ws_root=ws_root,- ws_config=cfg,- )- assert docs is True- assert reason is None-+def _mode(run_docs=None, provider_name=None):+ return _resolve_docs_flag(run_docs=run_docs, provider_name=provider_name)-def test_explicit_no_records_reason(ws):- ws_root, cfg = ws- docs, reason = _resolve_docs_flag(- run_docs=False,- provider_name=None,- ws_root=ws_root,- ws_config=cfg,- )- assert docs is False- assert reason == "--no-docs flag"+def test_explicit_docs_uses_the_model():+ assert _mode(run_docs=True) == ("llm", None)-def test_provider_flag_forces_on(ws):- ws_root, cfg = ws- docs, reason = _resolve_docs_flag(- run_docs=None,- provider_name="anthropic",- ws_root=ws_root,- ws_config=cfg,- )- assert docs is True- assert reason is None+def test_explicit_no_docs_records_reason():+ assert _mode(run_docs=False) == ("none", "--no-docs flag")-def test_inherits_primary_config(ws, monkeypatch):- ws_root, cfg = ws- # Drop a provider into the primary repo's config — that should be- # enough to flip the default to docs-on.- cfg_path = ws_root / "backend" / ".repowise" / "config.yaml"- cfg_path.write_text(- "provider: anthropic\nmodel: claude-sonnet-4-5\nembedder: gemini\n",- encoding="utf-8",- )- docs, reason = _resolve_docs_flag(- run_docs=None,- provider_name=None,- ws_root=ws_root,- ws_config=cfg,- )- assert docs is True- assert reason is None--[email protected]("env_var", ["ANTHROPIC_API_KEY", "KIMI_API_KEY"])-def test_env_provider_forces_on(ws, monkeypatch, env_var):- ws_root, cfg = ws- monkeypatch.setenv(env_var, "sk-fake")-- docs, reason = _resolve_docs_flag(- run_docs=None,- provider_name=None,- ws_root=ws_root,- ws_config=cfg,- )- assert docs is True- assert reason is None+def test_provider_flag_uses_the_model():+ assert _mode(provider_name="anthropic") == ("llm", None)-def test_no_provider_anywhere_returns_off(ws):- ws_root, cfg = ws- docs, reason = _resolve_docs_flag(- run_docs=None,- provider_name=None,- ws_root=ws_root,- ws_config=cfg,+def test_default_builds_from_code_even_with_a_configured_provider(ws, monkeypatch):+ ws_root, _cfg = ws+ (ws_root / "backend" / ".repowise" / "config.yaml").write_text(+ "provider: anthropic\nmodel: claude-sonnet-4-5\n", encoding="utf-8")- assert docs is False- assert reason == "no provider configured"+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-fake")+ monkeypatch.chdir(ws_root)+ assert _mode() == ("deterministic", None)# ---------------------------------------------------------------------------diff --git a/tests/unit/cli/test_workspace_add_index.py b/tests/unit/cli/test_workspace_add_index.pyindex d0d542824..52bcc690d 100644--- a/tests/unit/cli/test_workspace_add_index.py+++ b/tests/unit/cli/test_workspace_add_index.py@@ -1,8 +1,8 @@"""``workspace add``'s per-repo index step, with the pipeline and LLM stubbed.Pins what ``_run_index_for_repo`` writes and prints on each path: docs off,-docs on, a provider that fails to resolve, a generation error, and an index-failure.+built from code, written by a model, a provider that fails to resolve, a+generation error, and an index failure."""from __future__ import annotations@@ -85,7 +85,7 @@ def test_docs_on_records_the_provider(ws, monkeypatch, capsys):ws_root, cfg, calls = wsmonkeypatch.setattr("repowise.cli.helpers.resolve_provider", lambda *a, **k: _provider())monkeypatch.setattr(_index, "_generate_docs_for_added_repo", lambda **_k: 5)- _run(ws_root, cfg, generate_docs=True, save_key=False)+ _run(ws_root, cfg, docs_mode="llm", save_key=False)state = load_state(ws_root / "added")assert state["total_pages"] == 5@@ -96,24 +96,60 @@ def test_docs_on_records_the_provider(ws, monkeypatch, capsys):assert args[1:3] == ("fake", "fake-1")assert kwargs["save_key"] is Falseout = capsys.readouterr().out- assert "Generated 5 pages" in out+ assert "Documentation: 5 pages, written by fake-1" in outassert "indexed without docs" not in out-def test_provider_failure_falls_back_to_index_only(ws, monkeypatch, capsys):+def test_provider_failure_falls_back_to_built_from_code(ws, monkeypatch, capsys):ws_root, cfg, calls = wsdef boom(*_a, **_k):raise RuntimeError("no key")+ seen = {}++ def fake_generate(**kwargs):+ seen.update(kwargs)+ return 4+monkeypatch.setattr("repowise.cli.helpers.resolve_provider", boom)- _run(ws_root, cfg, generate_docs=True)+ monkeypatch.setattr(_index, "_generate_docs_for_added_repo", fake_generate)+ _run(ws_root, cfg, docs_mode="llm")++ assert seen["provider"] is None+ state = load_state(ws_root / "added")+ assert resolve_docs_mode(state) == "deterministic"+ assert "provider" not in state+ assert calls["save_config"] == []+ out = capsys.readouterr().out+ assert "Provider unavailable (no key); building documentation from code" in out+ assert "Documentation: 4 pages, built from code" in out+- assert resolve_docs_mode(load_state(ws_root / "added")) == "none"+def test_default_builds_from_code_without_a_model(ws, monkeypatch, capsys):+ ws_root, cfg, calls = ws++ def no_model(*_a, **_k):+ raise AssertionError("built from code must not resolve a provider")++ seen = {}++ def fake_generate(**kwargs):+ seen.update(kwargs)+ return 7++ monkeypatch.setattr("repowise.cli.helpers.resolve_provider", no_model)+ monkeypatch.setattr(_index, "_generate_docs_for_added_repo", fake_generate)+ _run(ws_root, cfg, docs_mode="deterministic")++ assert seen["provider"] is None+ state = load_state(ws_root / "added")+ assert state["total_pages"] == 7+ assert resolve_docs_mode(state) == "deterministic"assert calls["save_config"] == []out = capsys.readouterr().out- assert "Provider unavailable (no key)" in out- assert "indexed without docs (provider failure: no key)" in out+ assert "Documentation: 7 pages, built from code" in out+ assert "indexed without docs" not in outdef test_generation_error_keeps_the_provider_state(ws, monkeypatch, capsys):@@ -124,13 +160,13 @@ def test_generation_error_keeps_the_provider_state(ws, monkeypatch, capsys):raise RuntimeError("rate limited")monkeypatch.setattr(_index, "_generate_docs_for_added_repo", boom)- _run(ws_root, cfg, generate_docs=True)+ _run(ws_root, cfg, docs_mode="llm")state = load_state(ws_root / "added")assert state["provider"] == "fake"assert state["total_pages"] == 0assert len(calls["save_config"]) == 1- assert "Doc generation failed: rate limited" in capsys.readouterr().out+ assert "Documentation failed: rate limited" in capsys.readouterr().outdef test_index_failure_stops_before_any_state(ws, monkeypatch):diff --git a/tests/unit/cli/test_workspace_init_config.py b/tests/unit/cli/test_workspace_init_config.pyindex fb710272e..f3091fe1f 100644--- a/tests/unit/cli/test_workspace_init_config.py+++ b/tests/unit/cli/test_workspace_init_config.py@@ -13,11 +13,13 @@ from unittest.mock import patchimport yamlfrom rich.console import Console+from repowise.cli.commands.init_cmd import _workspace_reposfrom repowise.cli.commands.init_cmd import workspace as ws_modfrom repowise.cli.commands.init_cmd._workspace_config import (WorkspacePick,build_workspace_config,)+from repowise.cli.commands.init_cmd._workspace_repos import select_workspace_reposfrom repowise.cli.ui.workspace_selection import interactive_repo_selectfrom repowise.core.workspace import WorkspaceConfig@@ -181,9 +183,13 @@ def test_repo_whose_folder_is_gone_is_dropped_and_named(tmp_path: Path) -> None: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+ with (+ patch.object(_workspace_repos, "interactive_repo_select", return_value=scan.repos[:1]),+ patch("sys.stdin.isatty", return_value=True),+ ):+ pick = select_workspace_repos(scan, repo_names=[], select_all=False)+ assert pick.primary_picked is False+ assert select_workspace_repos(scan, repo_names=[], select_all=True).primary_picked is Falsedef test_a_malformed_config_is_replaced_with_a_note(tmp_path: Path) -> None:diff --git a/tests/unit/cli/test_workspace_repo_selection.py b/tests/unit/cli/test_workspace_repo_selection.pynew file mode 100644index 000000000..c195e9437--- /dev/null+++ b/tests/unit/cli/test_workspace_repo_selection.py@@ -0,0 +1,135 @@+"""Picking a workspace's repos without prompts: ``init --repos`` and the all-repos line."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import click+import pytest++from repowise.cli.commands.init_cmd import _workspace_repos+from repowise.cli.commands.init_cmd._workspace_repos import (+ all_repos_line,+ repos_primary_line,+ select_workspace_repos,+ split_repo_names,+)+from repowise.cli.ui.workspace_selection import match_repo_names++ROOT = Path("/ws")+++def _repo(rel: str, alias: str | None = None) -> SimpleNamespace:+ path = ROOT / rel+ return SimpleNamespace(path=path, name=path.name, alias=alias or path.name)+++def repos() -> list[SimpleNamespace]:+ return [_repo("alpha"), _repo("beta"), _repo("gamma")]+++def test_names_match_alias_in_the_order_given(repos):+ picked = match_repo_names(repos, ["gamma", "Alpha"], ROOT)+ assert [r.alias for r in picked] == ["gamma", "alpha"]+++def test_a_repeated_name_is_taken_once(repos):+ assert len(match_repo_names(repos, ["beta", "beta"], ROOT)) == 1+++def test_unknown_name_lists_every_available_repo(repos):+ with pytest.raises(ValueError) as exc:+ match_repo_names(repos, ["alpha", "nope", "zap"], ROOT)+ msg = str(exc.value)+ assert "Unknown repo: nope, zap." in msg+ assert "Available: alpha, beta, gamma." in msg+++def test_a_shared_name_is_ambiguous_and_the_path_settles_it():+ repos = [_repo("svc/api"), _repo("web/api", alias="api-2")]+ with pytest.raises(ValueError, match=r"'api' matches 2 repos \(svc/api, web/api\)"):+ match_repo_names(repos, ["api"], ROOT)+ assert match_repo_names(repos, ["web/api"], ROOT) == [repos[1]]+ assert match_repo_names(repos, ["svc\\api\\"], ROOT) == [repos[0]]+ assert match_repo_names(repos, ["api-2"], ROOT) == [repos[1]]+++def test_split_repo_names_drops_blanks():+ assert split_repo_names(" a, ,c ,") == ["a", "c"]+ assert split_repo_names(None) == []+++def test_repos_flag_skips_the_picker_and_makes_the_first_primary(repos, monkeypatch):+ def no_prompt(*_a, **_k):+ raise AssertionError("--repos must not prompt")++ monkeypatch.setattr(_workspace_repos, "interactive_repo_select", no_prompt)+ monkeypatch.setattr(_workspace_repos, "interactive_primary_select", no_prompt)+ scan = SimpleNamespace(root=ROOT, repos=repos)++ pick = select_workspace_repos(scan, repo_names=["gamma", "alpha"], select_all=True)++ assert [r.alias for r in pick.selected] == ["gamma", "alpha"]+ assert pick.primary_alias == "gamma"+ assert pick.primary_repo is repos[2]+ # An existing workspace keeps its primary; a new one takes the first listed.+ assert pick.primary_picked is False+++def test_repos_primary_line_says_where_the_primary_came_from(repos):+ pick = select_workspace_repos(+ SimpleNamespace(root=ROOT, repos=repos), repo_names=["gamma", "beta"], select_all=False+ )+ kept = repos_primary_line("beta", pick)+ assert "Primary: [bold]beta[/bold] (kept from the workspace)" in kept+ first = repos_primary_line("gamma", pick)+ assert "Primary: [bold]gamma[/bold] (first in --repos)" in first+ assert "(first in --repos)" in repos_primary_line(None, pick)+++def test_repos_flag_unknown_name_is_a_usage_error(repos):+ scan = SimpleNamespace(root=ROOT, repos=repos)+ with pytest.raises(click.UsageError, match="--repos: Unknown repo: delta"):+ select_workspace_repos(scan, repo_names=["delta"], select_all=False)+++def test_yes_takes_every_repo_and_says_which(repos, capsys):+ scan = SimpleNamespace(root=ROOT, repos=repos)+ pick = select_workspace_repos(scan, repo_names=[], select_all=True)++ assert pick.selected == repos+ assert pick.primary_alias == "alpha"+ out = capsys.readouterr().out+ assert "Indexing all 3 repos: alpha, beta, gamma." in out+ assert "Pick some with --repos alpha,beta" in out+++def test_all_repos_line_truncates_a_long_list():+ repos = [_repo(f"r{i:02d}") for i in range(13)]+ line = all_repos_line(repos)+ assert "Indexing all 13 repos: r00, r01" in line+ assert "r09 and 3 more." in line+ assert "r10" not in line+++def test_repos_on_a_single_repo_is_a_usage_error(tmp_path):+ from click.testing import CliRunner++ from repowise.cli.commands.init_cmd import init_command++ (tmp_path / ".git").mkdir()+ result = CliRunner().invoke(init_command, [str(tmp_path), "--repos", "x", "--no-editor-setup"])+ assert result.exit_code == 2+ assert "--repos picks repos in a folder that holds several" in result.output+++def test_repos_with_all_is_a_usage_error(tmp_path):+ from click.testing import CliRunner++ from repowise.cli.commands.init_cmd import init_command++ result = CliRunner().invoke(init_command, [str(tmp_path), "--repos", "x", "--all"])+ assert result.exit_code == 2+ assert "--repos and --all contradict each other" in result.output