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.

refactor(cli): split helpers into focused modules behind the helpers facade (#3983)

Raghav Chamadiya90a567c3c539
diff --git a/packages/cli/src/repowise/cli/_helpers/__init__.py b/packages/cli/src/repowise/cli/_helpers/__init__.py
new file mode 100644
index 000000000..e1f9df97f
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/__init__.py
@@ -0,0 +1 @@
+"""Implementation modules behind the ``repowise.cli.helpers`` facade."""
diff --git a/packages/cli/src/repowise/cli/_helpers/config.py b/packages/cli/src/repowise/cli/_helpers/config.py
new file mode 100644
index 000000000..f151795ed
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/config.py
@@ -0,0 +1,330 @@
+"""``.repowise/config.yaml`` reads and writes, and provider key persistence."""
+
+from __future__ import annotations
+
+import contextlib
+import os
+from pathlib import Path
+from typing import Any
+
+from repowise.cli._helpers.paths import ensure_repowise_dir, get_repowise_dir
+from repowise.cli.errors import reasoned_error
+from repowise.core.reasoning import (
+ ReasoningMode,
+)
+from repowise.core.reasoning import (
+ resolve_reasoning as resolve_core_reasoning,
+)
+from repowise.core.repo_config import CONFIG_FILENAME, RepoConfigError, load_repo_config
+
+# Suppresses mirroring the provider key into `.repowise/.env`. The env
+# spelling of `init --no-save-key`, mirroring REPOWISE_SKIP_EDITOR_SETUP: CI
+# and shared machines configure the process, not the command line. It is also
+# how the interactive key prompt records a "no": that answer is taken at the
+# start of the run and has to survive until config is written at the end.
+NO_SAVE_KEY_ENV = "REPOWISE_NO_SAVE_KEY"
+
+
+def _clean_flag(value: str | None) -> bool:
+ """Whether an env var is set to something meaning "on"."""
+ return (value or "").strip().lower() not in ("", "0", "false", "no")
+
+# ---------------------------------------------------------------------------
+# Config (provider / model / embedder persisted after init)
+# ---------------------------------------------------------------------------
+
+
+def load_config(repo_path: Path) -> dict[str, Any]:
+ """Load ``.repowise/config.yaml`` or return an empty dict if absent.
+
+ A broken config is surfaced as a warning (to stderr, so ``--format json``
+ stays parseable) and degrades to an empty dict rather than crashing the
+ command or silently using defaults — issue #852: configuration errors must
+ be visible, not swallowed. Callers keep their current behaviour either
+ way; the warning is the fix.
+ """
+ from repowise.cli import helpers as _facade # patch point for tests
+
+ try:
+ return load_repo_config(repo_path)
+ except RepoConfigError as exc:
+ _facade.err_console.print(f"[yellow]Warning:[/yellow] {exc}")
+ return {}
+
+
+def resolve_reasoning(
+ reasoning: str | None = None,
+ config: dict[str, Any] | None = None,
+) -> ReasoningMode:
+ """Resolve generation reasoning from CLI flag, env, config, then default."""
+ try:
+ return resolve_core_reasoning(reasoning, config)
+ except ValueError as exc:
+ raise reasoned_error(str(exc), reason="invalid_reasoning") from exc
+
+
+def resolve_max_file_pages(
+ chosen: int | None = None,
+ config: dict[str, Any] | None = None,
+) -> int | None:
+ """Resolve the file-page cap: explicit choice, then config.yaml, then unset.
+
+ Three states reach ``GenerationConfig.max_file_pages`` (see its comment and
+ ``selection/selector.py``): ``None`` leaves the volume policy in charge, ``0``
+ is an explicit refusal to cap, and a positive value is a cap.
+
+ A negative or unparseable ``max_file_pages`` in config.yaml resolves to
+ ``None`` rather than to zero pages, so a typo hands the decision back to the
+ policy instead of silently deleting the file layer.
+ """
+ raw = chosen if chosen is not None else (config or {}).get("max_file_pages")
+ if raw is None:
+ return None
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ return None
+ if value == 0:
+ return 0 # "all of them", and it survives the policy
+ return value if value > 0 else None
+
+
+def _persist_provider_key(repo_path: Path, provider: str) -> None:
+ """Mirror ``provider``'s credential from the environment into ``.repowise/.env``.
+
+ Key persistence used to hang off the interactive key *prompt*, so it only
+ ran when the user typed a key. Supplying the key through the environment is
+ precisely the no-prompt case, which meant a scripted
+ ``init --provider openai --yes`` indexed fine and wrote ``provider:`` to
+ config.yaml but left no credential behind: ``repowise mcp`` against that
+ repo then answered ``degraded: "no-llm-provider"``. Scripted init is the
+ primary path for agents and CI, so a run that succeeds has to leave a repo
+ whose MCP server can actually answer.
+
+ The rule, stated out loud: a key that successfully indexed this repo is the
+ key this repo needs, so it is saved, with a notice naming the file and
+ ``--no-save-key`` to opt out. Nothing is written for a provider that needs
+ no credential.
+
+ Routed through :func:`save_repo_env_key` rather than writing the file here:
+ the ``.gitignore`` entry and the owner-only mode come with it, and a
+ hand-rolled write would leave a committable secret.
+
+ Best-effort by design. It runs at the tail of a completed init, after the
+ index has been paid for, and it is the first thing on that path to write
+ outside ``.repowise/``, so a read-only checkout or an unwritable
+ ``.gitignore`` must cost the user a warning, not the run.
+ """
+ from repowise.cli import helpers as _facade # patch point for tests
+ from repowise.core.providers.llm.registry import PROVIDER_API_KEY_ENVS
+ from repowise.core.repo_config import save_repo_env_key
+
+ if _clean_flag(os.environ.get(NO_SAVE_KEY_ENV)):
+ return
+
+ # Keys only. ``provider_required_envs`` would also hand back ollama's
+ # OLLAMA_BASE_URL, and pinning an endpoint into the repo is a different
+ # decision from saving a credential: a later run on another network
+ # would silently reuse the stale URL.
+ #
+ # Some providers accept either of two vars (gemini: GEMINI_API_KEY /
+ # GOOGLE_API_KEY). Persist the one actually carrying the value, not both,
+ # so the var written is the var `provider_kwargs` will read back.
+ for env_var in PROVIDER_API_KEY_ENVS.get(provider, ()):
+ value = (os.environ.get(env_var) or "").strip()
+ if not value:
+ continue
+ try:
+ save_repo_env_key(repo_path, env_var, value)
+ except (OSError, ValueError) as exc:
+ _facade.warn(
+ f"could not save {env_var} to "
+ f".repowise/.env ({exc}). The index is complete, but "
+ f"`repowise mcp` will need {env_var} in its environment."
+ )
+ return
+ _facade.console.print(
+ f"[dim]Saved {env_var} to .repowise/.env (gitignored). "
+ f"--no-save-key or {NO_SAVE_KEY_ENV}=1 to skip.[/dim]"
+ )
+ return
+
+
+def save_config(
+ repo_path: Path,
+ provider: str,
+ model: str,
+ embedder: str,
+ *,
+ embedding_model: str | None = None,
+ exclude_patterns: list[str] | None = None,
+ commit_limit: int | None = None,
+ reasoning: str | None = None,
+ save_key: bool = True,
+) -> None:
+ """Write provider/model/embedder (and optionally exclude_patterns) to ``.repowise/config.yaml``.
+
+ Performs a round-trip load so existing keys are preserved.
+
+ ``embedding_model`` is persisted so ``repowise serve`` can rebuild the same
+ embedder used at init time — without it the server silently falls back to a
+ provider default (e.g. ``text-embedding-3-small``), which mismatches the
+ indexed vectors and breaks chat/search retrieval (issue #426).
+
+ ``save_key`` also mirrors the provider's credential into ``.repowise/.env``.
+ It belongs here because this function *is* the "this run committed to this
+ provider for this repo" moment, shared by all three flows that reach it
+ (single-repo init, workspace init, ``workspace add``). All three otherwise
+ leave an indexed repo their MCP server cannot authenticate against.
+ """
+ from repowise.core.providers.llm.resolve import apply_llm_selection
+ from repowise.core.repo_config import save_repo_config
+
+ ensure_repowise_dir(repo_path)
+
+ # Round-trip: preserve any existing keys (e.g. exclude_patterns set via CLI).
+ # provider/model go through the writer the web UI uses too.
+ existing = apply_llm_selection(load_config(repo_path), provider, model)
+ existing["embedder"] = embedder
+ if embedding_model:
+ existing["embedding_model"] = embedding_model
+ else:
+ # No model was resolved this run: dropping the key beats leaving a
+ # stale one that names a different provider's model, or one this
+ # embedder was not actually built with (#2627).
+ existing.pop("embedding_model", None)
+ if exclude_patterns is not None:
+ existing["exclude_patterns"] = exclude_patterns
+ if commit_limit is not None:
+ existing["commit_limit"] = commit_limit
+ if reasoning is not None:
+ existing["reasoning"] = resolve_reasoning(reasoning)
+
+ save_repo_config(repo_path, existing)
+ _trust_configured_base_url(repo_path, existing, provider)
+
+ if save_key:
+ _persist_provider_key(repo_path, provider)
+
+
+def _trust_configured_base_url(repo_path: Path, config: dict[str, Any], provider: str) -> None:
+ """Record ``<provider>.base_url`` as confirmed: this init run chose to use it.
+
+ A config.yaml base URL only receives a key from outside the repo's own
+ ``.env`` once the user confirmed it on this machine; running ``init``
+ with it in place is that confirmation. An invalid URL is left unconfirmed,
+ and resolution reports it.
+ """
+ from repowise.core.providers.llm.resolve import trust_base_url, validate_base_url
+
+ section = config.get(provider)
+ if not isinstance(section, dict):
+ return
+ try:
+ url = validate_base_url(section.get("base_url"))
+ except ValueError:
+ return
+ if url:
+ with contextlib.suppress(OSError):
+ trust_base_url(repo_path, url)
+
+
+def save_config_partial(
+ repo_path: Path,
+ *,
+ exclude_patterns: list[str] | None = None,
+ commit_limit: int | None = None,
+ **extra: Any,
+) -> None:
+ """Merge optional keys into ``.repowise/config.yaml``, preserving existing keys.
+
+ ``exclude_patterns`` / ``commit_limit`` are explicit for the common case;
+ any other config keys (e.g. ``enable_onboarding=False``) can be passed as
+ keyword arguments. ``None`` values are skipped so callers can forward
+ optional flags without clobbering existing keys.
+
+ ``embedding_model`` is the one exception to "None is skipped": passed
+ explicitly as ``None``, it clears any pinned model instead of leaving it
+ alone, because that is the caller saying the model changed (or is no
+ longer known) for whatever embedder this call names. Merely *omitting*
+ ``embedding_model`` is not the same claim, so it does not clear anything
+ on its own -- ``reindex_cmd`` calls this after every reindex with only
+ ``embedder=``, having never had a model to pass, and a bare ``in extra``
+ check on ``embedder`` used to read that silence as "no model" and wipe a
+ real pin on every routine reindex (#2627, caught in review on the fix
+ itself). Distinguishing "not passed" from "passed as ``None``" needs the
+ raw ``extra`` dict, since a keyword default cannot do it: ``in extra``
+ only reports that once, but ``get`` cannot tell the two shapes apart
+ afterwards.
+ """
+ import yaml # type: ignore[import-untyped]
+
+ updates: dict[str, Any] = {}
+ if exclude_patterns is not None:
+ updates["exclude_patterns"] = exclude_patterns
+ if commit_limit is not None:
+ updates["commit_limit"] = commit_limit
+ updates.update({k: v for k, v in extra.items() if v is not None})
+ clear_embedding_model = "embedding_model" in extra and extra["embedding_model"] is None
+ if not updates and not clear_embedding_model:
+ return
+
+ ensure_repowise_dir(repo_path)
+ config_path = get_repowise_dir(repo_path) / CONFIG_FILENAME
+ existing = load_config(repo_path)
+ existing.update(updates)
+ if clear_embedding_model:
+ existing.pop("embedding_model", None)
+
+ config_path.write_text(
+ yaml.dump(existing, default_flow_style=False, sort_keys=False),
+ encoding="utf-8",
+ )
+
+
+def save_distill_commands_enabled(repo_path: Path, *, enabled: bool) -> None:
+ """Deep-merge ``distill.commands.enabled`` into ``.repowise/config.yaml``.
+
+ :func:`save_config_partial` merges shallowly at the top level, so the
+ ``distill`` block is merged here first to avoid clobbering sibling keys
+ like ``disabled_filters``.
+ """
+ cfg = load_config(repo_path)
+ distill = dict(cfg.get("distill") or {})
+ commands = dict(distill.get("commands") or {})
+ commands["enabled"] = enabled
+ distill["commands"] = commands
+ save_config_partial(repo_path, distill=distill)
+
+
+#: The hook surfaces that *replace* a tool result rather than adding to it.
+#: One consent turns them all on; each has its own ``repowise hook <name>``
+#: toggle afterwards, so a surface that turns out to be wrong can be dropped
+#: without taking the others with it.
+HOOK_REPLACEMENT_SURFACES = ("read_skeleton", "search_digest")
+
+
+def save_hook_surface_enabled(repo_path: Path, surface: str, *, enabled: bool) -> None:
+ """Deep-merge ``hooks.<surface>`` into ``.repowise/config.yaml``.
+
+ Same shape as :func:`save_distill_commands_enabled`, and written by the
+ same consent: the rewrite-hook prompt means "let repowise's hooks
+ intervene in your agent's tool calls", and rewriting a Bash command is a
+ larger intervention than serving a Read as its skeleton or a search as its
+ digest, not a smaller one. There is deliberately no second question.
+ """
+ cfg = load_config(repo_path)
+ hooks = dict(cfg.get("hooks") or {})
+ hooks[surface] = enabled
+ save_config_partial(repo_path, hooks=hooks)
+
+
+def config_fingerprint(repo_path: Path) -> str:
+ """SHA-256 hex of ``.repowise/config.yaml`` + ``health-rules.json`` content.
+
+ Delegates to the shared core implementation so CLI runs and server jobs
+ compute identical fingerprints for the same on-disk config.
+ """
+ from repowise.core.repo_config import config_fingerprint as _core_fingerprint
+
+ return _core_fingerprint(repo_path)
diff --git a/packages/cli/src/repowise/cli/_helpers/console.py b/packages/cli/src/repowise/cli/_helpers/console.py
new file mode 100644
index 000000000..4ec1b8ed2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/console.py
@@ -0,0 +1,143 @@
+"""Console streams, warnings, log silencing for machine output, and the async bridge."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import sys
+from typing import Any
+
+import click
+from rich.console import Console
+
+from repowise.cli.output import resolve_console_width
+
+# Width is pinned only when the stream is not a terminal — see
+# `output.resolve_console_width`. Without it rich renders a pipe at 80 columns
+# and ellipsises the very paths an agent needs to act on.
+console = Console(width=resolve_console_width(sys.stdout))
+err_console = Console(stderr=True, width=resolve_console_width(sys.stderr))
+
+
+def warn(text: str) -> None:
+ """Print a warning to stderr with the shared yellow ``Warning:`` prefix.
+
+ Every CLI warning funnels through this helper so warnings render on the
+ same ``err_console`` stream (never stdout) and use one ``[yellow]Warning:[/yellow]``
+ spelling instead of hand-synced copies scattered across commands.
+ """
+ from repowise.cli import helpers as _facade # patch point for tests
+
+ _facade.err_console.print(f"[yellow]Warning:[/yellow] {text}")
+
+# ---------------------------------------------------------------------------
+# Logging / structlog helpers
+# ---------------------------------------------------------------------------
+
+MACHINE_OUTPUT_LOGGER_NAMES = ("httpx", "httpcore", "repowise.core", "repowise.server")
+
+def silence_logs_for_machine_output():
+ """Suppress info/debug log output while stdout is machine-readable (JSON/md).
+
+ Structlog and stdlib loggers write to stdout by default. When a command
+ emits JSON or Markdown, those lines corrupt the output for downstream
+ consumers (e.g. ``repowise health --format json | jq .kpis``).
+
+ Context manager, not a bare call: logger levels and the structlog
+ wrapper class are process-global with no other owner, so a caller that
+ forgot to restore them would permanently silence its own process — the
+ case that mattered in practice was a test session, where the mutation
+ outlived the test that made it and broke unrelated caplog assertions
+ later in the same run (see #1976).
+
+ Use as:
+
+ with silence_logs_for_machine_output():
+ emit_json_or_markdown(...)
+ """
+ import logging
+
+ loggers = [logging.getLogger(name) for name in MACHINE_OUTPUT_LOGGER_NAMES]
+ previous_levels = [logger.level for logger in loggers]
+
+ previous_structlog_config: dict[str, Any] | None = None
+ try:
+ import structlog
+
+ previous_structlog_config = dict(structlog.get_config())
+ except ImportError:
+ pass
+
+ try:
+ for logger in loggers:
+ logger.setLevel(logging.ERROR)
+ if previous_structlog_config is not None:
+ import structlog
+
+ # cache_logger_on_first_use=False is required: module-level
+ # ``structlog.get_logger`` calls snapshot the logger before
+ # configure() runs and would bypass this filter without it.
+ structlog.configure(
+ wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR),
+ cache_logger_on_first_use=False,
+ )
+ yield
+ finally:
+ for logger, level in zip(loggers, previous_levels, strict=True):
+ logger.setLevel(level)
+ if previous_structlog_config is not None:
+ import structlog
+
+ structlog.configure(**previous_structlog_config)
+
+def silence_logs_for_machine_output_until_close() -> None:
+ """Enter ``silence_logs_for_machine_output`` and restore it when the
+ current click command finishes.
+
+ ``silence_logs_for_machine_output`` is a context manager because it must
+ always restore what it mutates — but not every call site has a single
+ lexical block to wrap it around. An option callback (see the ``--format``
+ and ``--json`` callbacks in ``output.py``) returns before the command body
+ even starts running, so a ``with`` block there would restore the levels
+ before the command does any work. Re-indenting an entire command
+ function's body under one ``with`` is also a large, easy-to-get-wrong
+ diff at call sites deep inside long functions.
+
+ Solved the same way ``update_cmd`` already solves it for restoring
+ ``console.file``: register the undo against click's context instead of a
+ lexical scope, so it fires when the command finishes regardless of how
+ much code runs in between or where the call sits.
+ """
+ from repowise.cli import helpers as _facade # patch point for tests
+
+ ctx = click.get_current_context()
+ cm = _facade.silence_logs_for_machine_output()
+ cm.__enter__()
+ ctx.call_on_close(lambda: cm.__exit__(None, None, None))
+
+
+# ---------------------------------------------------------------------------
+# Async bridge
+# ---------------------------------------------------------------------------
+
+
+def run_async(coro: Any) -> Any:
+ """Run an async coroutine from synchronous Click code.
+
+ Each call is its own event loop, and a command runs one LLM provider
+ through several of them. The provider's SDK client pools connections on
+ the loop that opened them, so they are closed here, before that loop goes
+ away: left pooled, they print ``Task exception was never retrieved ...
+ Event loop is closed`` from a later step (issue #2946). With no such
+ provider alive there is nothing to close.
+ """
+ from repowise.core.providers.llm.base import close_provider_clients
+
+ async def _run() -> Any:
+ try:
+ return await coro
+ finally:
+ await close_provider_clients()
+
+ return asyncio.run(_run())
diff --git a/packages/cli/src/repowise/cli/_helpers/db.py b/packages/cli/src/repowise/cli/_helpers/db.py
new file mode 100644
index 000000000..a59e6575a
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/db.py
@@ -0,0 +1,177 @@
+"""Repo-local store access: database URL, read sessions, schema reconcile."""
+
+from __future__ import annotations
+
+import contextlib
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import click
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator
+
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+
+# ---------------------------------------------------------------------------
+# Database
+# ---------------------------------------------------------------------------
+
+
+def get_db_url_for_repo(repo_path: Path) -> str:
+ """Return a database URL for this repo.
+
+ Prefers ``REPOWISE_DB_URL``, then the legacy ``REPOWISE_DATABASE_URL``.
+ Otherwise defaults to the repo-local ``<repo>/.repowise/wiki.db``.
+ """
+ from repowise.core.persistence.database import resolve_db_url
+
+ return resolve_db_url(repo_path)
+
+
+STALE_INDEX_MESSAGE = (
+ "This index was written by an older version of repowise; run `repowise update`."
+)
+
+
+class StaleIndexError(click.ClickException):
+ """The store lacks a table or column this version reads, and could not be repaired."""
+
+ def __init__(self) -> None:
+ super().__init__(STALE_INDEX_MESSAGE)
+
+
+async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, str] | None]:
+ """Open the repo-local store for reading, yielding ``(session, repo_id)`` or ``None``.
+
+ A scoring or scanning command must never fail because the index is absent
+ or locked, so every storage error yields ``None`` instead. The schema is
+ reconciled only when a catalogue read finds it behind the models: the
+ reconcile costs a read command 0.3 s and writes to the store, so a current
+ store skips it. A store still behind after it raises :class:`StaleIndexError`,
+ since every answer read from it would be missing what it lacks.
+ """
+ from sqlalchemy import select
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.cli import helpers as _facade # patch point for tests
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.crud import get_repository_by_path
+ from repowise.core.persistence.database import (
+ get_configured_db_url,
+ has_db_store,
+ schema_behind,
+ )
+ from repowise.core.persistence.models import Repository
+
+ # The configured store, which may live outside the repo (REPOWISE_DB_URL).
+ if not has_db_store(root):
+ yield None
+ return
+ # The stack keeps the session open across the yield and disposes the engine
+ # on the way out, whether the caller left the block or raised inside it.
+ async with contextlib.AsyncExitStack() as stack:
+ opened: tuple[AsyncSession, str] | None = None
+ try:
+ url = _facade.get_db_url_for_repo(root)
+ engine = create_engine(url)
+ stack.push_async_callback(engine.dispose)
+ if await schema_behind(engine):
+ await _facade.reconcile_schema_best_effort(url)
+ if await schema_behind(engine):
+ raise StaleIndexError
+ factory = create_session_factory(engine)
+ session = await stack.enter_async_context(get_session(factory))
+ repo = await get_repository_by_path(session, str(root))
+ if repo is None and get_configured_db_url() is None:
+ # A moved repo carries its local store but retains the old
+ # local_path. Never infer identity in a configured/shared store
+ # or when the local store contains more than one repository.
+ repos = (await session.scalars(select(Repository).limit(2))).all()
+ if len(repos) == 1:
+ repo = repos[0]
+ if repo is not None:
+ opened = (session, repo.id)
+ except (SQLAlchemyError, OSError, LookupError):
+ opened = None
+ yield opened
+
+
+#: Busy timeout for the reconcile's own connection. The engine default is 30s,
+#: sized for bulk graph-edge writes; inheriting it here is a trap, because a
+#: read command opens several engines (``status`` four, ``doctor`` five) and a
+#: store locked by a concurrent ``repowise update`` would stall each one in
+#: turn — measured at 133s of silence for ``status`` before this was bounded.
+#: The reconcile is a best-effort secondary write, so it takes the same lever
+#: issue #326 gave the cost tracker: fail fast and be dropped rather than block.
+_RECONCILE_BUSY_TIMEOUT_MS = 2000
+
+
+async def reconcile_schema_best_effort(db_url: str) -> None:
+ """Back-fill additive schema drift on the store at *db_url*, best-effort.
+
+ An index built by an older repowise is missing whatever columns the models
+ have gained since, and the ORM then fails with a raw ``no such column`` on
+ the first query — which for a read command means every read. ``init_db``
+ back-fills those columns in place and is idempotent, so the CLI pairs it
+ with ``create_engine`` where a command opens a store, the way the MCP
+ server, the workspace registry and the FastAPI app already do in their
+ lifespans. :func:`repo_index_session` runs it only on a store found behind.
+
+ Opportunistic, not a precondition, which is the part worth having in one
+ place. Reconciling needs a write, and a store can be read-only or
+ exclusively locked by a concurrent ``repowise update``. Aborting there would
+ be a regression twice over: a store already on the current schema needs no
+ DDL and would have read fine, and where the drift is real the following
+ query fails with the ``no such column`` that the failure shield turns into
+ "this index predates the installed repowise, run repowise update" — a
+ better answer than whichever write error stopped the repair.
+
+ Takes a URL rather than an engine so the repair runs on its own short-timeout
+ connection: the caller's engine keeps the full 30s window for the work it was
+ opened to do, and a contended repair gives up in two seconds instead of
+ stalling the command behind it.
+
+ Never CREATES a store. ``init_db`` on a fresh path would materialise a
+ 42-table file, so a read command run in a repo that was never indexed would
+ leave a database behind where the user expects "not indexed yet".
+ """
+ from repowise.core.persistence import create_engine, init_db
+
+ if _missing_sqlite_file(db_url):
+ return
+
+ engine = create_engine(db_url, busy_timeout_ms=_RECONCILE_BUSY_TIMEOUT_MS)
+ try:
+ with contextlib.suppress(Exception):
+ await init_db(engine)
+ finally:
+ with contextlib.suppress(Exception):
+ await engine.dispose()
+
+
+def _missing_sqlite_file(db_url: str) -> bool:
+ """True when *db_url* names a SQLite file that does not exist yet.
+
+ Only SQLite is checked: a server-backed URL has no file to create, and the
+ caller is not the component that decides whether that database should exist.
+ """
+ if not db_url.startswith("sqlite"):
+ return False
+ _, sep, tail = db_url.partition(":///")
+ if not sep or not tail or tail.startswith(":memory:"):
+ return False
+ return not Path(tail).exists()
+
+
+def db_configured() -> bool:
+ """True when ``REPOWISE_DB_URL`` or ``REPOWISE_DATABASE_URL`` is set.
+
+ The DB may still be the repo-local ``wiki.db`` default — the file
+ existence check the callers pair this with decides that.
+ """
+ from repowise.core.persistence import get_configured_db_url
+
+ return get_configured_db_url() is not None
diff --git a/packages/cli/src/repowise/cli/_helpers/git.py b/packages/cli/src/repowise/cli/_helpers/git.py
new file mode 100644
index 000000000..553961ab3
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/git.py
@@ -0,0 +1,60 @@
+"""Git commit-id validation and HEAD lookups."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+# ---------------------------------------------------------------------------
+# Git helpers
+# ---------------------------------------------------------------------------
+
+
+_COMMIT_ID_RE = re.compile(r"[0-9a-fA-F]{7,40}")
+
+
+def as_commit_id(value: object) -> str | None:
+ """*value* when it is a full or abbreviated hex commit id, else ``None``.
+
+ Commit ids read back from ``.repowise/state.json`` (or a file beside it)
+ can be edited by anyone who can commit that file, so they are checked
+ before they reach a ``git`` argument list, where a leading ``-`` would be
+ read as an option.
+ """
+ if isinstance(value, str) and _COMMIT_ID_RE.fullmatch(value):
+ return value
+ return None
+
+
+def get_head_commit(repo_path: Path) -> str | None:
+ """Return the HEAD commit SHA or ``None`` if not a git repo.
+
+ Delegates to the core implementation (``git rev-parse HEAD``) so the CLI
+ and the workspace updater resolve HEAD identically — the old gitpython
+ version here could diverge on worktree/detached-HEAD edge cases.
+ """
+ from repowise.core.workspace.update import get_head_commit as _core_head
+
+ return _core_head(Path(repo_path))
+
+
+def head_commit_ts(repo_path: Path) -> float | None:
+ """Committer timestamp of the repo's HEAD, or None when git is unavailable.
+
+ Anchors the periodic idle-file health re-score gate (#728) to repo time
+ rather than wall clock, the same anchor the git history windows use, so
+ the cadence is deterministic and correct for historical checkouts.
+
+ Shared with ``init`` so a fresh index can stamp ``last_full_rescore_at`` in
+ the same units the gate reads it back in.
+ """
+ try:
+ import git
+
+ repo = git.Repo(repo_path, search_parent_directories=True)
+ try:
+ return float(repo.head.commit.committed_date)
+ finally:
+ repo.close()
+ except Exception:
+ return None
diff --git a/packages/cli/src/repowise/cli/_helpers/markers.py b/packages/cli/src/repowise/cli/_helpers/markers.py
new file mode 100644
index 000000000..037b49c99
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/markers.py
@@ -0,0 +1,218 @@
+"""Update queued/pending markers and the capped hook output log."""
+
+from __future__ import annotations
+
+import contextlib
+import json
+from pathlib import Path
+from typing import Any
+
+from repowise.cli._helpers.git import as_commit_id
+from repowise.cli._helpers.paths import ensure_repowise_dir, get_repowise_dir
+
+# ---------------------------------------------------------------------------
+# Queued / pending markers — coordinate the post-commit hook with a running
+# update so rapid-fire commits don't spawn N concurrent updates that race
+# on save_state. Two distinct markers, deliberately:
+#
+# ``.update.queued`` : written by the hook BEFORE backgrounding repowise
+# update. Closes the race window between commit and
+# lock acquisition — the augment hook reads this
+# and suppresses its warning the moment the queued
+# file appears, not 30+ seconds later when the
+# actual lock file lands on disk.
+#
+# ``.update.pending`` : written by a *new* update_cmd invocation when it
+# finds an in-flight lock. Carries the latest HEAD
+# so the running update can roll forward to it at
+# the end of its current pass instead of stopping
+# at a stale commit.
+#
+# Both markers are best-effort: failure to write/read them must never break
+# update_cmd itself, only degrade the coalescing behaviour to "spawn but
+# bail" (slightly noisier in the augment hook but still correct).
+# ---------------------------------------------------------------------------
+
+UPDATE_QUEUED_FILENAME = ".update.queued"
+UPDATE_PENDING_FILENAME = ".update.pending"
+
+# A ``.update.queued`` marker older than this is treated as stale — most
+# likely a crashed hook that wrote the marker but never spawned the update.
+# Short enough to avoid suppressing genuinely-stale warnings indefinitely.
+UPDATE_QUEUED_STALE_AFTER_SECONDS = 5 * 60
+
+
+def _update_queued_path(repo_path: Path) -> Path:
+ return get_repowise_dir(repo_path) / UPDATE_QUEUED_FILENAME
+
+
+def _update_pending_path(repo_path: Path) -> Path:
+ return get_repowise_dir(repo_path) / UPDATE_PENDING_FILENAME
+
+
+def write_update_queued(repo_path: Path, head: str | None) -> None:
+ """Mark that an update has been spawned for ``head``.
+
+ Called from the post-commit hook *before* backgrounding ``repowise
+ update`` so the augment hook can suppress its stale-wiki warning during
+ the brief window where the actual update process is still starting up
+ (Python import, DB open, etc.) and hasn't yet written its own lock file.
+ """
+ import time
+
+ try:
+ ensure_repowise_dir(repo_path)
+ except OSError:
+ return
+ payload = {"target_commit": head, "queued_at": time.time()}
+ with contextlib.suppress(OSError):
+ _update_queued_path(repo_path).write_text(json.dumps(payload), encoding="utf-8")
+
+
+def read_update_queued(repo_path: Path) -> dict[str, Any] | None:
+ """Return queued payload if fresh (≤ ``UPDATE_QUEUED_STALE_AFTER_SECONDS``)."""
+ import time
+
+ path = _update_queued_path(repo_path)
+ if not path.exists():
+ return None
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ return None
+ queued_at = payload.get("queued_at")
+ if not isinstance(queued_at, (int, float)):
+ return None
+ if time.time() - queued_at > UPDATE_QUEUED_STALE_AFTER_SECONDS:
+ return None
+ return payload
+
+
+def clear_update_queued(repo_path: Path) -> None:
+ """Drop the queued marker. Called by update_cmd once it owns the real lock."""
+ with contextlib.suppress(OSError):
+ _update_queued_path(repo_path).unlink(missing_ok=True)
+
+
+def write_update_pending(repo_path: Path, head: str | None) -> None:
+ """Record that another commit landed while an update was in flight.
+
+ The running update reads this at the end of its pass and rolls forward
+ to the new HEAD in one extra round, avoiding the failure mode where a
+ rapid burst of commits leaves the wiki indexed to an outdated commit.
+ """
+ if head is None:
+ return
+ try:
+ ensure_repowise_dir(repo_path)
+ except OSError:
+ return
+ with contextlib.suppress(OSError):
+ _update_pending_path(repo_path).write_text(head, encoding="utf-8")
+
+
+def read_update_pending(repo_path: Path) -> str | None:
+ """Return the pending HEAD if any, else None."""
+ path = _update_pending_path(repo_path)
+ if not path.exists():
+ return None
+ try:
+ head = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+ return head or None
+
+
+def clear_update_pending(repo_path: Path) -> None:
+ """Drop the pending marker once the rolled-forward update has consumed it."""
+ with contextlib.suppress(OSError):
+ _update_pending_path(repo_path).unlink(missing_ok=True)
+
+
+def _pending_commit_still_ahead(
+ repo_path: Path, pending_head: str, indexed_head: str | None
+) -> bool:
+ """True only when ``pending_head`` is a resolvable commit strictly ahead of
+ ``indexed_head`` — a newer commit the index has not caught up to yet.
+
+ Equal commits, ancestors of ``indexed_head``, and commits that no longer
+ resolve (rebased or gc'd away) all return ``False``, so the caller clears
+ them instead of leaving the marker behind forever.
+ """
+ if not indexed_head or pending_head == indexed_head:
+ return False
+ import subprocess
+
+ if as_commit_id(indexed_head) is None or as_commit_id(pending_head) is None:
+ return False
+ try:
+ # ``indexed_head`` is an ancestor of ``pending_head`` => pending is
+ # newer than what we indexed and worth keeping. A non-zero exit
+ # (including an unresolvable pending commit) means "not ahead".
+ result = subprocess.run(
+ ["git", "merge-base", "--is-ancestor", "--end-of-options", indexed_head, pending_head],
+ cwd=str(repo_path),
+ capture_output=True,
+ timeout=10,
+ )
+ return result.returncode == 0
+ except Exception:
+ return False
+
+
+def consume_update_pending(repo_path: Path, indexed_head: str | None) -> None:
+ """Clear the ``.update.pending`` marker once the index has caught up to it.
+
+ A bailed update writes the latest HEAD to ``.update.pending`` (see
+ :func:`write_update_pending`) so the in-flight update can tell more commits
+ landed. The update that actually holds the lock calls this when it
+ finishes: the marker is obsolete unless it points to a commit strictly
+ *ahead* of the one just indexed. The previous consumer only cleared on an
+ exact ``pending == head`` match, so once HEAD advanced past the pending
+ commit (or that commit was rebased away) the marker leaked indefinitely.
+ """
+ pending_head = read_update_pending(repo_path)
+ if pending_head is None:
+ return
+ if not _pending_commit_still_ahead(repo_path, pending_head, indexed_head):
+ clear_update_pending(repo_path)
+
+
+# ---------------------------------------------------------------------------
+# Hook output log — capped, single-file rotation so the user can diagnose
+# why the post-commit hook didn't catch up without needing to chase down a
+# silent subprocess. Cap is deliberately small: a few recent runs is enough
+# context, and we don't want a runaway log to fill the .repowise/ dir.
+# ---------------------------------------------------------------------------
+
+UPDATE_LOG_FILENAME = ".update.log"
+
+# Truncate the log when it grows past this size, keeping the tail.
+UPDATE_LOG_MAX_BYTES = 256 * 1024
+# After truncation, retain at most this much of the prior tail.
+UPDATE_LOG_KEEP_TAIL_BYTES = 64 * 1024
+
+
+def update_log_path(repo_path: Path) -> Path:
+ return get_repowise_dir(repo_path) / UPDATE_LOG_FILENAME
+
+
+def rotate_update_log_if_needed(repo_path: Path) -> None:
+ """Truncate ``.update.log`` if it has grown past the size cap.
+
+ Called opportunistically from the hook before piping a new run's output
+ in. We use simple in-place truncation (rewrite the tail) rather than
+ renaming, because the post-commit hook can fire in parallel with a
+ `repowise update` that may still be writing — a rename would orphan
+ the writer's file descriptor on POSIX and outright fail on Windows.
+ """
+ path = update_log_path(repo_path)
+ try:
+ if not path.exists() or path.stat().st_size <= UPDATE_LOG_MAX_BYTES:
+ return
+ with path.open("rb") as f:
+ f.seek(-UPDATE_LOG_KEEP_TAIL_BYTES, 2)
+ tail = f.read()
+ path.write_bytes(b"... (log truncated) ...\n" + tail)
+ except OSError:
+ pass
diff --git a/packages/cli/src/repowise/cli/_helpers/paths.py b/packages/cli/src/repowise/cli/_helpers/paths.py
new file mode 100644
index 000000000..18af84db1
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/paths.py
@@ -0,0 +1,78 @@
+"""Repository, workspace and ``.repowise/`` path resolution."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+STATE_FILENAME = "state.json"
+REPOWISE_DIR = ".repowise"
+
+# ---------------------------------------------------------------------------
+# Path resolution
+# ---------------------------------------------------------------------------
+
+
+def resolve_repo_path(path: str | None) -> Path:
+ """Resolve the repository root path from a CLI argument.
+
+ If *path* is ``None``, defaults to the current working directory.
+ Always returns an absolute, resolved ``Path``.
+ """
+ if path is None:
+ return Path.cwd().resolve()
+ return Path(path).resolve()
+
+
+def find_repowise_repo_root(start: Path | None = None) -> Path | None:
+ """Walk upward from *start* looking for a repo with ``.repowise``."""
+
+ current = (start or Path.cwd()).resolve()
+ home = Path.home().resolve()
+ for candidate in (current, *current.parents):
+ if _same_path(candidate, home):
+ return None
+ if (candidate / REPOWISE_DIR).is_dir():
+ return candidate
+ return None
+
+
+def _same_path(left: Path, right: Path) -> bool:
+ try:
+ return left.samefile(right)
+ except OSError:
+ return left == right
+
+
+def find_workspace_root(start: Path | None = None) -> Path | None:
+ """Walk up from *start* (default: cwd) looking for ``.repowise-workspace.yaml``.
+
+ Returns the directory containing the file, or ``None`` if not found.
+ Delegates to :func:`repowise.core.workspace.config.find_workspace_root`.
+ """
+ from repowise.core.workspace.config import find_workspace_root as _find
+
+ return _find(start)
+
+
+def get_repowise_dir(repo_path: Path) -> Path:
+ """Return the ``.repowise/`` directory for a given repo root."""
+ return repo_path / REPOWISE_DIR
+
+
+def user_global_dir() -> Path:
+ """Return the user-global ``~/.repowise`` dir (created), for cross-repo state.
+
+ Home to machine-wide, repo-independent artifacts: the cached web bundle, the
+ PyPI update-check cache, and the last-seen release marker. Distinct from a
+ repo's local ``.repowise/`` store.
+ """
+ d = Path.home() / REPOWISE_DIR
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def ensure_repowise_dir(repo_path: Path) -> Path:
+ """Create the ``.repowise/`` directory if it does not exist and return it."""
+ d = get_repowise_dir(repo_path)
+ d.mkdir(parents=True, exist_ok=True)
+ return d
diff --git a/packages/cli/src/repowise/cli/_helpers/providers.py b/packages/cli/src/repowise/cli/_helpers/providers.py
new file mode 100644
index 000000000..aa56a467a
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/providers.py
@@ -0,0 +1,291 @@
+"""LLM provider resolution, interactive fallbacks, and config validation."""
+
+from __future__ import annotations
+
+import contextlib
+import os
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli._helpers.config import save_config_partial
+from repowise.cli.errors import reasoned_error
+
+# ---------------------------------------------------------------------------
+# Provider resolution
+# ---------------------------------------------------------------------------
+
+
+def resolve_provider(
+ provider_name: str | None,
+ model: str | None,
+ repo_path: Path | None = None,
+) -> Any:
+ """Resolve a provider instance from CLI flags, the repo config, or env.
+
+ The order is the shared one in :mod:`repowise.core.providers.llm.resolve`:
+ ``--provider`` / ``--model`` > ``.repowise/config.yaml`` > the global
+ default in ``provider_config.json`` > ``REPOWISE_PROVIDER`` /
+ ``REPOWISE_MODEL`` > auto-detection from API keys.
+ """
+ from repowise.core.providers.llm.resolve import resolve_llm
+
+ selection = resolve_llm(repo_path, provider=provider_name, model=model)
+ if selection.provider is None:
+ # Not fatal on every path: `init` catches this and renders a template
+ # wiki instead, so the reason must not be recorded until it ends a
+ # command.
+ raise reasoned_error(_no_provider_message(), reason="no_provider_configured")
+ return _build_provider(selection, _provider_kwargs_or_error(selection, repo_path))
+
+
+def _provider_kwargs_or_error(selection: Any, repo_path: Path | None) -> dict[str, Any]:
+ """Constructor kwargs, warning when a configured provider has no key anywhere."""
+ from repowise.cli import helpers as _facade # patch point for tests
+ from repowise.core.providers.llm.resolve import llm_provider_kwargs
+
+ try:
+ kwargs = llm_provider_kwargs(selection, repo_path)
+ except ValueError as exc:
+ # A base URL the repo's config.yaml sets that is malformed, or that
+ # nobody on this machine confirmed for a key from elsewhere.
+ raise reasoned_error(str(exc), reason="provider_setup_failed") from exc
+ if selection.provider_source != "autodetect" and "api_key" not in kwargs:
+ # A configured provider whose key is nowhere still gets built: the
+ # constructor says what it needs. Agent CLIs are checked for install.
+ for warning in _facade.validate_provider_config(selection.provider):
+ _facade.warn(warning)
+ return kwargs
+
+
+def _build_provider(selection: Any, kwargs: dict[str, Any]) -> Any:
+ """Construct the provider, turning a setup failure into a config error."""
+ from repowise.core.providers import get_provider
+
+ try:
+ return get_provider(selection.provider, **kwargs)
+ except click.ClickException:
+ raise
+ except Exception as exc:
+ # Everything this constructor reads is user input: env vars and
+ # .repowise/config.yaml, base_url above all. A typo there is a
+ # configuration error, not a repowise bug, but it used to surface as
+ # a raw traceback that escaped every caller's handler.
+ raise reasoned_error(
+ f"Could not set up the {selection.provider} provider: {exc}. "
+ f"Resolved {selection.describe()}. Check those settings.",
+ reason="provider_setup_failed",
+ ) from exc
+
+
+def _no_provider_message() -> str:
+ """The no-provider error, listing every env var that would configure one."""
+ from repowise.core.providers.llm.registry import (
+ PROVIDER_AUTODETECT_ORDER,
+ provider_required_envs,
+ )
+
+ env_vars = [var for name in PROVIDER_AUTODETECT_ORDER for var in provider_required_envs(name)]
+ return (
+ "No provider configured. Use --provider, set provider in .repowise/config.yaml or "
+ f"REPOWISE_PROVIDER, or set one of {' / '.join(env_vars)}. Use "
+ "REPOWISE_PROVIDER=claude_cli to use an authenticated Claude Code subscription, "
+ "REPOWISE_PROVIDER=codex_cli to use an authenticated Codex CLI subscription, or "
+ "REPOWISE_PROVIDER=opencode to use opencode."
+ )
+
+
+def resolve_explicit_provider_or_prompt(
+ provider_name: str | None,
+ model: str | None,
+ repo_path: Path,
+ *,
+ interactive: bool,
+ save_key: bool = True,
+) -> Any:
+ """Resolve an explicit provider, onboarding missing credentials in a TTY.
+
+ ``resolve_provider`` stays non-interactive because hooks, CI, and library
+ callers must never block on stdin. ``init`` can opt into this wrapper when
+ it has a real terminal: a missing explicit provider key gets the same
+ inline setup as the provider picker, and an explicit OpenAI provider also
+ gets the endpoint question used by local gateways.
+ """
+ from repowise.cli import helpers as _facade # patch point for tests
+ from repowise.cli.ui.provider_selection import interactive_provider_credentials
+
+ if interactive and provider_name == "openai":
+ # A pty can report TTY while stdin is not readable. Let the normal
+ # resolution below produce the actionable provider error instead of
+ # replacing it with Abort.
+ with contextlib.suppress(EOFError, click.Abort):
+ interactive_provider_credentials(
+ _facade.console,
+ provider_name,
+ repo_path=repo_path,
+ save_key=save_key,
+ )
+
+ return _facade.resolve_provider(provider_name, model, repo_path=repo_path)
+
+ try:
+ return _facade.resolve_provider(provider_name, model, repo_path=repo_path)
+ except click.ClickException as original_error:
+ if not interactive or provider_name is None:
+ raise
+
+ try:
+ configured = interactive_provider_credentials(
+ _facade.console,
+ provider_name,
+ repo_path=repo_path,
+ save_key=save_key,
+ )
+ except (EOFError, click.Abort):
+ # A pty can report TTY while stdin is not readable. Preserve the
+ # actionable provider error instead of replacing it with Abort.
+ raise original_error from None
+
+ if not configured:
+ raise original_error
+ return _facade.resolve_provider(provider_name, model, repo_path=repo_path)
+
+
+def resolve_provider_or_prompt(
+ provider_name: str | None,
+ model: str | None,
+ repo_path: Path,
+ *,
+ reasoning: str | None = None,
+ interactive: bool,
+) -> Any:
+ """Resolve a provider, falling back to init's interactive setup on a miss.
+
+ Ordinary resolution is :func:`resolve_provider`. When that fails because no
+ provider/key is configured and ``interactive`` is set (an interactive
+ terminal, not a hook / CI / ``--progress json`` run), reuse init's exact
+ provider + API-key prompt, persist the choice, and retry — so a docs run
+ that only just asked for LLM pages onboards the same way ``init`` does
+ instead of dying with "No provider configured".
+
+ When ``interactive`` is False the original error propagates unchanged, so
+ background runs (post-commit hook, CI, machine-driven ``--progress json``)
+ keep their clean, non-blocking failure.
+
+ Persistence reuses init's helpers: the key lands in ``.repowise/.env`` (from
+ the prompt) and provider/model in ``.repowise/config.yaml`` here, so the
+ prompt only ever appears once per repo.
+ """
+ from repowise.cli import helpers as _facade # patch point for tests
+
+ try:
+ return _facade.resolve_provider(provider_name, model, repo_path=repo_path)
+ except Exception as original_error:
+ if not interactive:
+ raise
+ from repowise.cli.ui import interactive_provider_config_select
+
+ # ``interactive`` rests on ``isatty()``, which lies: under Git Bash,
+ # some pty wrappers, and ``docker run -t`` without -i it claims a
+ # terminal it cannot read from, and agents drive us through exactly
+ # those shapes. Treat the prompt as the probe (as init does): if stdin
+ # cannot answer, click raises EOFError/Abort, so fall back to the clean,
+ # actionable "No provider configured" error instead of a bare "Aborted!".
+ try:
+ selection = interactive_provider_config_select(
+ _facade.console, model, reasoning, repo_path=repo_path
+ )
+ except (EOFError, click.Abort):
+ raise original_error from None
+
+ # Persist provider/model so future runs resolve without re-prompting.
+ # The API key was already persisted to .repowise/.env by the prompt.
+ save_config_partial(
+ repo_path,
+ provider=selection.provider_name,
+ model=selection.model,
+ )
+ return _facade.resolve_provider(selection.provider_name, selection.model, repo_path=repo_path)
+
+
+# ---------------------------------------------------------------------------
+# Provider validation
+# ---------------------------------------------------------------------------
+
+
+def validate_provider_config(
+ provider_name: str | None = None, repo_path: Path | None = None
+) -> list[str]:
+ """Validate that required API keys/environment variables are set for the provider.
+
+ Args:
+ provider_name: The provider name to validate. If None, checks all possible providers.
+ repo_path: The repo whose configured provider counts as explicitly requested.
+
+ Returns:
+ List of warning messages for missing or invalid configuration.
+ Empty list means all required config is present.
+ """
+ warnings = []
+
+ def _is_env_var_set(var_name: str) -> bool:
+ """Check if environment variable is set and non-empty."""
+ value = os.environ.get(var_name)
+ return value is not None and value.strip() != ""
+
+ def _is_env_var_exists(var_name: str) -> bool:
+ """Check if environment variable exists (even if empty)."""
+ return var_name in os.environ
+
+ # Required environment variables per provider, read from the registry that
+ # also drives resolution, so a provider added there is validated here without
+ # a second edit. The agent-CLI providers need no env var; the check for them
+ # is whether their CLI is installed.
+ from repowise.core.agents.identity import identity_for_provider
+ from repowise.core.providers.llm.registry import provider_required_envs
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+ provider_env_vars = {
+ name: list(provider_required_envs(name))
+ for name in PROVIDER_SPECS
+ if provider_required_envs(name)
+ }
+
+ if provider_name:
+ agent = identity_for_provider(provider_name)
+ if agent is not None:
+ if not agent.is_installed():
+ warnings.append(
+ f"Provider '{provider_name}' requires the {agent.display_name} CLI.\n"
+ f" Install: {agent.install_hint}\n"
+ f" Setup: {agent.login_hint}"
+ )
+ return warnings
+
+ # Validate specific provider
+ if provider_name not in provider_env_vars:
+ warnings.append(f"Unknown provider '{provider_name}' - cannot validate configuration")
+ return warnings
+
+ # Any one of a provider's env vars satisfies it (GEMINI_API_KEY or
+ # GOOGLE_API_KEY), the same rule resolution applies.
+ env_vars = provider_env_vars[provider_name]
+ if not any(_is_env_var_set(var) for var in env_vars):
+ warnings.append(f"Provider '{provider_name}' requires {' or '.join(env_vars)}")
+ else:
+ # Check all providers - warn about any that could be configured but are missing keys
+ from repowise.core.providers.llm.resolve import resolve_llm
+
+ configured = resolve_llm(repo_path, autodetect=False).provider
+ for name, env_vars in provider_env_vars.items():
+ if any(_is_env_var_set(var) for var in env_vars):
+ continue
+ # Only warn if this provider is explicitly requested OR
+ # if the env var exists but is invalid (empty)
+ env_var_exists = any(_is_env_var_exists(var) for var in env_vars)
+ explicitly_requested = configured == name
+ if explicitly_requested or env_var_exists:
+ warnings.append(f"Provider '{name}' requires {' or '.join(env_vars)}")
+
+ return warnings
diff --git a/packages/cli/src/repowise/cli/_helpers/state.py b/packages/cli/src/repowise/cli/_helpers/state.py
new file mode 100644
index 000000000..0a501aaed
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/state.py
@@ -0,0 +1,93 @@
+"""``.repowise/state.json`` persistence."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from repowise.cli._helpers.paths import STATE_FILENAME, ensure_repowise_dir, get_repowise_dir
+
+# ---------------------------------------------------------------------------
+# State file
+# ---------------------------------------------------------------------------
+
+
+def load_state(repo_path: Path) -> dict[str, Any]:
+ """Load ``.repowise/state.json`` or return an empty dict if absent."""
+ state_path = get_repowise_dir(repo_path) / STATE_FILENAME
+ if state_path.exists():
+ return json.loads(state_path.read_text(encoding="utf-8"))
+ return {}
+
+
+#: Slots the last whole-repo generation put in front of this repository's
+#: signals, which is not the same as the slots that produced a page. The two
+#: differ, and only the first answers "has this index ever been offered a
+#: Glossary?".
+ONBOARDING_SLOTS_OFFERED_KEY = "onboarding_slots_offered"
+
+
+def stamp_offered_slots(state: dict[str, Any], *, enabled: bool = True) -> None:
+ """Record which onboarding slots this whole-repo run evaluated.
+
+ Only a run that generates the whole repository may call this: the slot
+ gates read whole-repo signals, so a scoped run that saw one changed file
+ has not offered anything to anything.
+
+ Written because a missing onboarding row has two causes that look identical
+ in a store and want opposite responses. A slot registered after this index
+ was built has never been evaluated here, and ``update --full`` would build
+ it; a slot that *was* evaluated and whose gate refused the repository will
+ be refused again by the same signals, and telling the user to spend a model
+ run on it is a lie. Measured on ``test-repos/microdot``: of the five
+ registered slots, two produce pages and three (``getting_started``,
+ ``active_landscape``, ``glossary``) are gate-skipped on every run, full or
+ fresh. A notice driven by the rows alone would name all three, forever, and
+ none of them would ever arrive.
+
+ ``enabled`` is the run's ``enable_onboarding``. A run with onboarding off
+ offered nothing, and recording otherwise would silence the notice for a
+ user who later turns it on.
+ """
+ from repowise.core.generation.onboarding import iter_specs
+
+ state[ONBOARDING_SLOTS_OFFERED_KEY] = (
+ sorted(spec.slot for spec in iter_specs()) if enabled else []
+ )
+
+
+def save_state(repo_path: Path, state: dict[str, Any], *, full_index: bool = False) -> None:
+ """Write *state* to ``.repowise/state.json``.
+
+ Every persist stamps the store-format markers (``store_format_version`` and
+ the ``written_by_version`` package version that wrote it) so the upgrade
+ layer always has a current record of the store's shape and provenance.
+
+ ``full_index`` marks a persist that follows a full-repo (re)generation, so
+ the store may be stamped to the terminal store-format version. A routine
+ incremental persist leaves it False and the version clamps below any
+ ``REINDEX_RECOMMENDED`` gate, keeping a reindex recommendation alive until
+ an actual re-index clears it.
+
+ A write that changes ``last_sync_commit`` moves the repository row's
+ ``head_commit`` to the same commit, so the two stamps never disagree.
+ """
+ from repowise.core.workspace.update import read_state_commit, restamp_changed_sync_commit
+
+ ensure_repowise_dir(repo_path)
+ previous = read_state_commit(Path(repo_path))
+ try:
+ from repowise.cli import __version__ as _pkg_version
+ from repowise.core.upgrade import stamp as _stamp_store_version
+
+ _stamp_store_version(state, package_version=_pkg_version, full_index=full_index)
+ except Exception: # never let stamping block a persist
+ pass
+ from repowise.core.fsutils import atomic_write_text
+
+ # Atomic so a crash mid-write can never leave a truncated state.json —
+ # every later update would fail to parse it and demand a full re-init.
+ state_path = get_repowise_dir(repo_path) / STATE_FILENAME
+ atomic_write_text(state_path, json.dumps(state, indent=2))
+ restamp_changed_sync_commit(Path(repo_path), previous, state.get("last_sync_commit"))
diff --git a/packages/cli/src/repowise/cli/_helpers/target.py b/packages/cli/src/repowise/cli/_helpers/target.py
new file mode 100644
index 000000000..8d331fda1
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_helpers/target.py
@@ -0,0 +1,329 @@
+"""Command target resolution: single repo or workspace."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Literal
+
+import click
+from rich.console import Console
+
+from repowise.cli._helpers.paths import (
+ STATE_FILENAME,
+ find_workspace_root,
+ get_repowise_dir,
+ resolve_repo_path,
+)
+
+# ---------------------------------------------------------------------------
+# Command target resolution — auto-detect single-repo vs workspace mode
+# ---------------------------------------------------------------------------
+#
+# Many CLI commands (``update``, ``status``, ``watch``, ``generate-claude-md``,
+# ``doctor``, ``costs``, ``search``, ``dead-code``, ``decision``, hooks) need
+# to decide whether the user means "this one repo" or "the surrounding
+# workspace". Historically each command did its own ad-hoc detection (or
+# none), which produced the Phase A bug where ``repowise update`` from a
+# workspace root errored with a misleading "No previous sync found" message
+# and left a stray ``.repowise/`` directory behind.
+#
+# ``resolve_command_target`` is the single source of truth. Every command
+# should call it before doing any work. See ``docs/WORKSPACE_ROBUSTNESS.md``
+# for the UX principles.
+
+
+@dataclass
+class CommandTarget:
+ """Resolved target for a CLI invocation — single repo or workspace.
+
+ Attributes:
+ mode: ``"single"`` or ``"workspace"``.
+ repo_path: For single mode, the resolved repo path. For workspace
+ mode, ``None`` (use ``ws_root`` + ``ws_config`` instead, or the
+ ``primary_path()`` helper).
+ ws_root: Workspace root path. Set in workspace mode; also set in
+ single mode when a workspace exists *upstream* of the chosen
+ repo, so commands can surface that context.
+ ws_config: Loaded workspace config (workspace mode only).
+ repo_filter: Optional alias filter for workspace mode (e.g.
+ ``--repo backend``). ``None`` means "all repos".
+ reason: Short human-readable explanation of why this target was
+ chosen. Surfaced via :meth:`notice`.
+ auto_detected: ``True`` when the workspace context was inferred
+ rather than requested via an explicit flag. Used to decide
+ whether to print a transparency notice.
+ """
+
+ mode: Literal["single", "workspace"]
+ repo_path: Path | None = None
+ ws_root: Path | None = None
+ ws_config: Any | None = None # WorkspaceConfig (avoid hard import here)
+ repo_filter: str | None = None
+ reason: str = ""
+ auto_detected: bool = False
+
+ # ------------------------------------------------------------------
+ # Convenience accessors
+ # ------------------------------------------------------------------
+
+ @property
+ def is_workspace(self) -> bool:
+ return self.mode == "workspace"
+
+ def primary_path(self) -> Path | None:
+ """Return the workspace's primary repo path, if known."""
+ if self.ws_config is None or self.ws_root is None:
+ return None
+ primary = self.ws_config.get_primary()
+ if primary is None:
+ return None
+ return (self.ws_root / primary.path).resolve()
+
+ def resolve_repo_alias(self, alias: str | None) -> Path | None:
+ """Resolve an alias to an absolute repo path within the workspace.
+
+ Returns ``None`` if the workspace is not loaded or the alias is
+ unknown. Used by commands that accept ``--repo <alias>``.
+ """
+ if self.ws_config is None or self.ws_root is None or alias is None:
+ return None
+ entry = self.ws_config.get_repo(alias)
+ if entry is None:
+ return None
+ return (self.ws_root / entry.path).resolve()
+
+ def single_repo_path(self) -> Path:
+ """The one repository to read, narrowing workspace mode to a repo.
+
+ ``--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`.
+
+ Raises ``click.ClickException`` when the alias is unknown or the
+ workspace declares no primary.
+ """
+ if not self.is_workspace:
+ assert self.repo_path is not None
+ return self.repo_path
+ if self.repo_filter is not None:
+ picked = self.resolve_repo_alias(self.repo_filter)
+ if picked is None:
+ raise click.ClickException(f"Unknown repo alias: {self.repo_filter}")
+ return picked
+ primary = self.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ return primary
+
+ # ------------------------------------------------------------------
+ # Notice rendering — every command should call this so users always
+ # know which mode they ended up in.
+ # ------------------------------------------------------------------
+
+ def notice(self, console_obj: Console, *, command: str = "") -> None:
+ """Print a one-line transparency notice describing the chosen target.
+
+ - Always printed when ``auto_detected`` is True.
+ - Also printed when in workspace mode (even if flagged explicitly)
+ so the repo list is visible at the top of the command output.
+ - Silent when single-repo mode was explicitly requested.
+ """
+ if self.mode == "workspace":
+ ws_root = self.ws_root.name if self.ws_root else "?"
+ 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"[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"[cyan]{repos}[/cyan] repos in [cyan]{ws_root}[/cyan]"
+ )
+ if self.reason and self.auto_detected:
+ console_obj.print(f"[dim] ({self.reason})[/dim]")
+ return
+
+ # Single-repo mode — only narrate when the resolution was non-obvious.
+ 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"[cyan]{self.repo_path}[/cyan] "
+ f"(workspace also detected at [cyan]{self.ws_root}[/cyan]; "
+ f"pass --workspace to run across all repos)"
+ )
+
+
+class WorkspaceNotFound(click.ClickException):
+ """Raised when ``--workspace`` was requested but no workspace was found."""
+
+
+def resolve_command_target(
+ *,
+ path: str | None = None,
+ workspace_flag: bool = False,
+ no_workspace_flag: bool = False,
+ repo_alias: str | None = None,
+) -> CommandTarget:
+ """Resolve whether a command should operate on a single repo or workspace.
+
+ The resolution rules (first match wins):
+
+ 1. ``--no-workspace`` → single-repo targeting ``path`` (or cwd). Hard
+ override for users who want the old behavior.
+ 2. ``--workspace`` or ``--repo <alias>`` → workspace mode. Raises
+ :class:`WorkspaceNotFound` if no workspace can be located.
+ 3. Explicit ``path`` argument:
+ - If the path itself contains ``.repowise-workspace.yaml`` →
+ workspace mode (treats the path as the workspace root).
+ - Otherwise → single-repo mode targeting that path. We do *not*
+ auto-promote to workspace when the user has explicitly typed a
+ path — explicit beats implicit.
+ 4. No ``path``, no flags → start from cwd and:
+ - If cwd is itself a workspace root → workspace mode.
+ - If cwd has its own ``.repowise/state.json`` (i.e. it's a repo
+ that has been indexed before) → single-repo mode, even if a
+ workspace exists upstream. cd-into-the-repo is the strongest
+ signal of user intent.
+ - If a workspace exists upstream of cwd → workspace mode.
+ - Otherwise → single-repo mode (cwd, even if not indexed).
+
+ The returned :class:`CommandTarget` carries a ``reason`` string and an
+ ``auto_detected`` flag so commands can render a transparent notice.
+ """
+ if workspace_flag and no_workspace_flag:
+ raise click.UsageError("--workspace and --no-workspace are mutually exclusive.")
+
+ if repo_alias is not None and no_workspace_flag:
+ raise click.UsageError(
+ "--repo <alias> implies workspace mode, but --no-workspace was passed."
+ )
+
+ explicit_path = path is not None
+ base_path = resolve_repo_path(path)
+
+ # Local import — avoids a circular import (core.workspace pulls in providers
+ # which pull in CLI helpers in some edge cases).
+ from repowise.core.workspace.config import (
+ WORKSPACE_CONFIG_FILENAME,
+ WorkspaceConfig,
+ )
+
+ def _load_ws(root: Path) -> Any | None:
+ try:
+ return WorkspaceConfig.load(root)
+ except Exception:
+ return None
+
+ # ----- Rule 1: explicit --no-workspace -----
+ if no_workspace_flag:
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ reason="forced via --no-workspace",
+ auto_detected=False,
+ )
+
+ # ----- Rule 2: --workspace or --repo -----
+ if workspace_flag or repo_alias is not None:
+ ws_root = find_workspace_root(base_path)
+ if ws_root is None:
+ raise WorkspaceNotFound(
+ "No .repowise-workspace.yaml found at or above "
+ f"{base_path}. Run 'repowise init <workspace-dir>' to "
+ "create a workspace, or drop the --workspace flag."
+ )
+ ws_config = _load_ws(ws_root)
+ if ws_config is None:
+ raise WorkspaceNotFound(
+ f"Found workspace config at {ws_root} but couldn't load it. Is it valid YAML?"
+ )
+ if repo_alias is not None and ws_config.get_repo(repo_alias) is None:
+ available = ", ".join(ws_config.repo_aliases()) or "(none)"
+ raise click.UsageError(
+ f"Unknown repo alias '{repo_alias}' in workspace. Available: {available}"
+ )
+ reason = "via --workspace flag" if workspace_flag else f"via --repo {repo_alias}"
+ return CommandTarget(
+ mode="workspace",
+ ws_root=ws_root,
+ ws_config=ws_config,
+ repo_filter=repo_alias,
+ reason=reason,
+ auto_detected=False,
+ )
+
+ # ----- Rule 3: explicit path argument -----
+ if explicit_path:
+ # Is the path itself a workspace root?
+ if (base_path / WORKSPACE_CONFIG_FILENAME).is_file():
+ ws_config = _load_ws(base_path)
+ if ws_config is not None:
+ return CommandTarget(
+ mode="workspace",
+ ws_root=base_path,
+ ws_config=ws_config,
+ reason="path argument is a workspace root",
+ auto_detected=True,
+ )
+ # Otherwise treat as single-repo. Surface workspace context if any.
+ upstream = find_workspace_root(base_path)
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ ws_root=upstream,
+ reason="explicit path argument",
+ auto_detected=False,
+ )
+
+ # ----- Rule 4: no path, no flags -----
+ # 4a: cwd is itself a workspace root
+ if (base_path / WORKSPACE_CONFIG_FILENAME).is_file():
+ ws_config = _load_ws(base_path)
+ if ws_config is not None:
+ return CommandTarget(
+ mode="workspace",
+ ws_root=base_path,
+ ws_config=ws_config,
+ reason="cwd is the workspace root",
+ auto_detected=True,
+ )
+
+ # 4b: cwd is an indexed repo — respect that even if a workspace exists upstream
+ cwd_state = get_repowise_dir(base_path) / STATE_FILENAME
+ if cwd_state.exists():
+ upstream = find_workspace_root(base_path.parent if base_path.parent != base_path else None)
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ ws_root=upstream,
+ reason="cwd has its own .repowise/state.json (cd-into-repo wins)",
+ auto_detected=upstream is not None,
+ )
+
+ # 4c: workspace exists upstream of cwd → workspace mode
+ upstream = find_workspace_root(base_path)
+ if upstream is not None:
+ ws_config = _load_ws(upstream)
+ if ws_config is not None:
+ return CommandTarget(
+ mode="workspace",
+ ws_root=upstream,
+ ws_config=ws_config,
+ reason=f"workspace detected upstream at {upstream}",
+ auto_detected=True,
+ )
+
+ # 4d: plain single-repo mode (likely uninitialized).
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ reason="no workspace nearby",
+ auto_detected=False,
+ )
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index add3e5e71..1a98d570a 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -1,29 +1,234 @@
-"""Shared CLI utilities — async bridge, path resolution, state, DB setup."""
+"""Shared CLI utilities: a facade over ``repowise.cli._helpers``.
-from __future__ import annotations
+Every name lives in a focused module under ``_helpers/`` and is re-exported
+here. Moved code looks names that tests patch on this module up through it at
+call time, so ``monkeypatch.setattr(helpers, ...)`` keeps reaching them.
+"""
-import asyncio
-import contextlib
-import json
-import os
-import re
-import sys
-from dataclasses import dataclass
-from pathlib import Path
-from typing import TYPE_CHECKING, Any, Literal, TypeVar
+from __future__ import annotations
-import click
-from rich.console import Console
+from typing import TypeVar
-from repowise.cli.errors import reasoned_error
-from repowise.cli.output import resolve_console_width
-from repowise.core.reasoning import (
- ReasoningMode,
+from repowise.cli._helpers.config import (
+ HOOK_REPLACEMENT_SURFACES as HOOK_REPLACEMENT_SURFACES,
+)
+from repowise.cli._helpers.config import (
+ NO_SAVE_KEY_ENV as NO_SAVE_KEY_ENV,
+)
+from repowise.cli._helpers.config import (
+ _clean_flag as _clean_flag,
+)
+from repowise.cli._helpers.config import (
+ _persist_provider_key as _persist_provider_key,
+)
+from repowise.cli._helpers.config import (
+ _trust_configured_base_url as _trust_configured_base_url,
+)
+from repowise.cli._helpers.config import (
+ config_fingerprint as config_fingerprint,
+)
+from repowise.cli._helpers.config import (
+ load_config as load_config,
+)
+from repowise.cli._helpers.config import (
+ resolve_max_file_pages as resolve_max_file_pages,
+)
+from repowise.cli._helpers.config import (
+ resolve_reasoning as resolve_reasoning,
+)
+from repowise.cli._helpers.config import (
+ save_config as save_config,
+)
+from repowise.cli._helpers.config import (
+ save_config_partial as save_config_partial,
+)
+from repowise.cli._helpers.config import (
+ save_distill_commands_enabled as save_distill_commands_enabled,
+)
+from repowise.cli._helpers.config import (
+ save_hook_surface_enabled as save_hook_surface_enabled,
+)
+from repowise.cli._helpers.console import (
+ MACHINE_OUTPUT_LOGGER_NAMES as MACHINE_OUTPUT_LOGGER_NAMES,
+)
+from repowise.cli._helpers.console import (
+ console as console,
+)
+from repowise.cli._helpers.console import (
+ err_console as err_console,
+)
+from repowise.cli._helpers.console import (
+ run_async as run_async,
+)
+from repowise.cli._helpers.console import (
+ silence_logs_for_machine_output as silence_logs_for_machine_output,
+)
+from repowise.cli._helpers.console import (
+ silence_logs_for_machine_output_until_close as silence_logs_for_machine_output_until_close,
+)
+from repowise.cli._helpers.console import (
+ warn as warn,
+)
+from repowise.cli._helpers.db import (
+ _RECONCILE_BUSY_TIMEOUT_MS as _RECONCILE_BUSY_TIMEOUT_MS,
+)
+from repowise.cli._helpers.db import (
+ STALE_INDEX_MESSAGE as STALE_INDEX_MESSAGE,
+)
+from repowise.cli._helpers.db import (
+ StaleIndexError as StaleIndexError,
+)
+from repowise.cli._helpers.db import (
+ _missing_sqlite_file as _missing_sqlite_file,
+)
+from repowise.cli._helpers.db import (
+ db_configured as db_configured,
+)
+from repowise.cli._helpers.db import (
+ get_db_url_for_repo as get_db_url_for_repo,
+)
+from repowise.cli._helpers.db import (
+ reconcile_schema_best_effort as reconcile_schema_best_effort,
+)
+from repowise.cli._helpers.db import (
+ repo_index_session as repo_index_session,
+)
+from repowise.cli._helpers.git import (
+ _COMMIT_ID_RE as _COMMIT_ID_RE,
+)
+from repowise.cli._helpers.git import (
+ as_commit_id as as_commit_id,
+)
+from repowise.cli._helpers.git import (
+ get_head_commit as get_head_commit,
+)
+from repowise.cli._helpers.git import (
+ head_commit_ts as head_commit_ts,
+)
+from repowise.cli._helpers.markers import (
+ UPDATE_LOG_FILENAME as UPDATE_LOG_FILENAME,
+)
+from repowise.cli._helpers.markers import (
+ UPDATE_LOG_KEEP_TAIL_BYTES as UPDATE_LOG_KEEP_TAIL_BYTES,
+)
+from repowise.cli._helpers.markers import (
+ UPDATE_LOG_MAX_BYTES as UPDATE_LOG_MAX_BYTES,
+)
+from repowise.cli._helpers.markers import (
+ UPDATE_PENDING_FILENAME as UPDATE_PENDING_FILENAME,
+)
+from repowise.cli._helpers.markers import (
+ UPDATE_QUEUED_FILENAME as UPDATE_QUEUED_FILENAME,
+)
+from repowise.cli._helpers.markers import (
+ UPDATE_QUEUED_STALE_AFTER_SECONDS as UPDATE_QUEUED_STALE_AFTER_SECONDS,
+)
+from repowise.cli._helpers.markers import (
+ _pending_commit_still_ahead as _pending_commit_still_ahead,
+)
+from repowise.cli._helpers.markers import (
+ _update_pending_path as _update_pending_path,
+)
+from repowise.cli._helpers.markers import (
+ _update_queued_path as _update_queued_path,
+)
+from repowise.cli._helpers.markers import (
+ clear_update_pending as clear_update_pending,
+)
+from repowise.cli._helpers.markers import (
+ clear_update_queued as clear_update_queued,
+)
+from repowise.cli._helpers.markers import (
+ consume_update_pending as consume_update_pending,
+)
+from repowise.cli._helpers.markers import (
+ read_update_pending as read_update_pending,
+)
+from repowise.cli._helpers.markers import (
+ read_update_queued as read_update_queued,
)
-from repowise.core.reasoning import (
- resolve_reasoning as resolve_core_reasoning,
+from repowise.cli._helpers.markers import (
+ rotate_update_log_if_needed as rotate_update_log_if_needed,
)
-from repowise.core.repo_config import CONFIG_FILENAME, RepoConfigError, load_repo_config
+from repowise.cli._helpers.markers import (
+ update_log_path as update_log_path,
+)
+from repowise.cli._helpers.markers import (
+ write_update_pending as write_update_pending,
+)
+from repowise.cli._helpers.markers import (
+ write_update_queued as write_update_queued,
+)
+from repowise.cli._helpers.paths import (
+ REPOWISE_DIR as REPOWISE_DIR,
+)
+from repowise.cli._helpers.paths import (
+ STATE_FILENAME as STATE_FILENAME,
+)
+from repowise.cli._helpers.paths import (
+ _same_path as _same_path,
+)
+from repowise.cli._helpers.paths import (
+ ensure_repowise_dir as ensure_repowise_dir,
+)
+from repowise.cli._helpers.paths import (
+ find_repowise_repo_root as find_repowise_repo_root,
+)
+from repowise.cli._helpers.paths import (
+ find_workspace_root as find_workspace_root,
+)
+from repowise.cli._helpers.paths import (
+ get_repowise_dir as get_repowise_dir,
+)
+from repowise.cli._helpers.paths import (
+ resolve_repo_path as resolve_repo_path,
+)
+from repowise.cli._helpers.paths import (
+ user_global_dir as user_global_dir,
+)
+from repowise.cli._helpers.providers import (
+ _build_provider as _build_provider,
+)
+from repowise.cli._helpers.providers import (
+ _no_provider_message as _no_provider_message,
+)
+from repowise.cli._helpers.providers import (
+ _provider_kwargs_or_error as _provider_kwargs_or_error,
+)
+from repowise.cli._helpers.providers import (
+ resolve_explicit_provider_or_prompt as resolve_explicit_provider_or_prompt,
+)
+from repowise.cli._helpers.providers import (
+ resolve_provider as resolve_provider,
+)
+from repowise.cli._helpers.providers import (
+ resolve_provider_or_prompt as resolve_provider_or_prompt,
+)
+from repowise.cli._helpers.providers import (
+ validate_provider_config as validate_provider_config,
+)
+from repowise.cli._helpers.state import (
+ ONBOARDING_SLOTS_OFFERED_KEY as ONBOARDING_SLOTS_OFFERED_KEY,
+)
+from repowise.cli._helpers.state import (
+ load_state as load_state,
+)
+from repowise.cli._helpers.state import (
+ save_state as save_state,
+)
+from repowise.cli._helpers.state import (
+ stamp_offered_slots as stamp_offered_slots,
+)
+from repowise.cli._helpers.target import (
+ CommandTarget as CommandTarget,
+)
+from repowise.cli._helpers.target import (
+ WorkspaceNotFound as WorkspaceNotFound,
+)
+from repowise.cli._helpers.target import (
+ resolve_command_target as resolve_command_target,
+)
+from repowise.core.repo_config import CONFIG_FILENAME as CONFIG_FILENAME
# Update lock — coordinates concurrent `repowise update` invocations and lets
# the augment hook suppress stale-wiki warnings while a refresh is in flight.
@@ -45,1619 +250,4 @@ from repowise.core.update_lock import (
try_acquire_update_lock as try_acquire_update_lock,
)
-if TYPE_CHECKING:
- from collections.abc import AsyncIterator
-
- from sqlalchemy.ext.asyncio import AsyncSession
-
T = TypeVar("T")
-
-# Width is pinned only when the stream is not a terminal — see
-# `output.resolve_console_width`. Without it rich renders a pipe at 80 columns
-# and ellipsises the very paths an agent needs to act on.
-console = Console(width=resolve_console_width(sys.stdout))
-err_console = Console(stderr=True, width=resolve_console_width(sys.stderr))
-
-
-def warn(text: str) -> None:
- """Print a warning to stderr with the shared yellow ``Warning:`` prefix.
-
- Every CLI warning funnels through this helper so warnings render on the
- same ``err_console`` stream (never stdout) and use one ``[yellow]Warning:[/yellow]``
- spelling instead of hand-synced copies scattered across commands.
- """
- err_console.print(f"[yellow]Warning:[/yellow] {text}")
-
-
-STATE_FILENAME = "state.json"
-REPOWISE_DIR = ".repowise"
-
-# Suppresses mirroring the provider key into `.repowise/.env`. The env
-# spelling of `init --no-save-key`, mirroring REPOWISE_SKIP_EDITOR_SETUP: CI
-# and shared machines configure the process, not the command line. It is also
-# how the interactive key prompt records a "no": that answer is taken at the
-# start of the run and has to survive until config is written at the end.
-NO_SAVE_KEY_ENV = "REPOWISE_NO_SAVE_KEY"
-
-
-def _clean_flag(value: str | None) -> bool:
- """Whether an env var is set to something meaning "on"."""
- return (value or "").strip().lower() not in ("", "0", "false", "no")
-
-
-# ---------------------------------------------------------------------------
-# Logging / structlog helpers
-# ---------------------------------------------------------------------------
-
-MACHINE_OUTPUT_LOGGER_NAMES = ("httpx", "httpcore", "repowise.core", "repowise.server")
-
-def silence_logs_for_machine_output():
- """Suppress info/debug log output while stdout is machine-readable (JSON/md).
-
- Structlog and stdlib loggers write to stdout by default. When a command
- emits JSON or Markdown, those lines corrupt the output for downstream
- consumers (e.g. ``repowise health --format json | jq .kpis``).
-
- Context manager, not a bare call: logger levels and the structlog
- wrapper class are process-global with no other owner, so a caller that
- forgot to restore them would permanently silence its own process — the
- case that mattered in practice was a test session, where the mutation
- outlived the test that made it and broke unrelated caplog assertions
- later in the same run (see #1976).
-
- Use as:
-
- with silence_logs_for_machine_output():
- emit_json_or_markdown(...)
- """
- import logging
-
- loggers = [logging.getLogger(name) for name in MACHINE_OUTPUT_LOGGER_NAMES]
- previous_levels = [logger.level for logger in loggers]
-
- previous_structlog_config: dict[str, Any] | None = None
- try:
- import structlog
-
- previous_structlog_config = dict(structlog.get_config())
- except ImportError:
- pass
-
- try:
- for logger in loggers:
- logger.setLevel(logging.ERROR)
- if previous_structlog_config is not None:
- import structlog
-
- # cache_logger_on_first_use=False is required: module-level
- # ``structlog.get_logger`` calls snapshot the logger before
- # configure() runs and would bypass this filter without it.
- structlog.configure(
- wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR),
- cache_logger_on_first_use=False,
- )
- yield
- finally:
- for logger, level in zip(loggers, previous_levels, strict=True):
- logger.setLevel(level)
- if previous_structlog_config is not None:
- import structlog
-
- structlog.configure(**previous_structlog_config)
-
-def silence_logs_for_machine_output_until_close() -> None:
- """Enter ``silence_logs_for_machine_output`` and restore it when the
- current click command finishes.
-
- ``silence_logs_for_machine_output`` is a context manager because it must
- always restore what it mutates — but not every call site has a single
- lexical block to wrap it around. An option callback (see the ``--format``
- and ``--json`` callbacks in ``output.py``) returns before the command body
- even starts running, so a ``with`` block there would restore the levels
- before the command does any work. Re-indenting an entire command
- function's body under one ``with`` is also a large, easy-to-get-wrong
- diff at call sites deep inside long functions.
-
- Solved the same way ``update_cmd`` already solves it for restoring
- ``console.file``: register the undo against click's context instead of a
- lexical scope, so it fires when the command finishes regardless of how
- much code runs in between or where the call sits.
- """
- ctx = click.get_current_context()
- cm = silence_logs_for_machine_output()
- cm.__enter__()
- ctx.call_on_close(lambda: cm.__exit__(None, None, None))
-
-
-# ---------------------------------------------------------------------------
-# Async bridge
-# ---------------------------------------------------------------------------
-
-
-def run_async(coro: Any) -> Any:
- """Run an async coroutine from synchronous Click code.
-
- Each call is its own event loop, and a command runs one LLM provider
- through several of them. The provider's SDK client pools connections on
- the loop that opened them, so they are closed here, before that loop goes
- away: left pooled, they print ``Task exception was never retrieved ...
- Event loop is closed`` from a later step (issue #2946). With no such
- provider alive there is nothing to close.
- """
- from repowise.core.providers.llm.base import close_provider_clients
-
- async def _run() -> Any:
- try:
- return await coro
- finally:
- await close_provider_clients()
-
- return asyncio.run(_run())
-
-
-# ---------------------------------------------------------------------------
-# Path resolution
-# ---------------------------------------------------------------------------
-
-
-def resolve_repo_path(path: str | None) -> Path:
- """Resolve the repository root path from a CLI argument.
-
- If *path* is ``None``, defaults to the current working directory.
- Always returns an absolute, resolved ``Path``.
- """
- if path is None:
- return Path.cwd().resolve()
- return Path(path).resolve()
-
-
-def find_repowise_repo_root(start: Path | None = None) -> Path | None:
- """Walk upward from *start* looking for a repo with ``.repowise``."""
-
- current = (start or Path.cwd()).resolve()
- home = Path.home().resolve()
- for candidate in (current, *current.parents):
- if _same_path(candidate, home):
- return None
- if (candidate / REPOWISE_DIR).is_dir():
- return candidate
- return None
-
-
-def _same_path(left: Path, right: Path) -> bool:
- try:
- return left.samefile(right)
- except OSError:
- return left == right
-
-
-def find_workspace_root(start: Path | None = None) -> Path | None:
- """Walk up from *start* (default: cwd) looking for ``.repowise-workspace.yaml``.
-
- Returns the directory containing the file, or ``None`` if not found.
- Delegates to :func:`repowise.core.workspace.config.find_workspace_root`.
- """
- from repowise.core.workspace.config import find_workspace_root as _find
-
- return _find(start)
-
-
-def get_repowise_dir(repo_path: Path) -> Path:
- """Return the ``.repowise/`` directory for a given repo root."""
- return repo_path / REPOWISE_DIR
-
-
-def user_global_dir() -> Path:
- """Return the user-global ``~/.repowise`` dir (created), for cross-repo state.
-
- Home to machine-wide, repo-independent artifacts: the cached web bundle, the
- PyPI update-check cache, and the last-seen release marker. Distinct from a
- repo's local ``.repowise/`` store.
- """
- d = Path.home() / REPOWISE_DIR
- d.mkdir(parents=True, exist_ok=True)
- return d
-
-
-def ensure_repowise_dir(repo_path: Path) -> Path:
- """Create the ``.repowise/`` directory if it does not exist and return it."""
- d = get_repowise_dir(repo_path)
- d.mkdir(parents=True, exist_ok=True)
- return d
-
-
-# ---------------------------------------------------------------------------
-# Database
-# ---------------------------------------------------------------------------
-
-
-def get_db_url_for_repo(repo_path: Path) -> str:
- """Return a database URL for this repo.
-
- Prefers ``REPOWISE_DB_URL``, then the legacy ``REPOWISE_DATABASE_URL``.
- Otherwise defaults to the repo-local ``<repo>/.repowise/wiki.db``.
- """
- from repowise.core.persistence.database import resolve_db_url
-
- return resolve_db_url(repo_path)
-
-
-STALE_INDEX_MESSAGE = (
- "This index was written by an older version of repowise; run `repowise update`."
-)
-
-
-class StaleIndexError(click.ClickException):
- """The store lacks a table or column this version reads, and could not be repaired."""
-
- def __init__(self) -> None:
- super().__init__(STALE_INDEX_MESSAGE)
-
-
-async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, str] | None]:
- """Open the repo-local store for reading, yielding ``(session, repo_id)`` or ``None``.
-
- A scoring or scanning command must never fail because the index is absent
- or locked, so every storage error yields ``None`` instead. The schema is
- reconciled only when a catalogue read finds it behind the models: the
- reconcile costs a read command 0.3 s and writes to the store, so a current
- store skips it. A store still behind after it raises :class:`StaleIndexError`,
- since every answer read from it would be missing what it lacks.
- """
- from sqlalchemy import select
- from sqlalchemy.exc import SQLAlchemyError
-
- from repowise.core.persistence import create_engine, create_session_factory, get_session
- from repowise.core.persistence.crud import get_repository_by_path
- from repowise.core.persistence.database import (
- get_configured_db_url,
- has_db_store,
- schema_behind,
- )
- from repowise.core.persistence.models import Repository
-
- # The configured store, which may live outside the repo (REPOWISE_DB_URL).
- if not has_db_store(root):
- yield None
- return
- # The stack keeps the session open across the yield and disposes the engine
- # on the way out, whether the caller left the block or raised inside it.
- async with contextlib.AsyncExitStack() as stack:
- opened: tuple[AsyncSession, str] | None = None
- try:
- url = get_db_url_for_repo(root)
- engine = create_engine(url)
- stack.push_async_callback(engine.dispose)
- if await schema_behind(engine):
- await reconcile_schema_best_effort(url)
- if await schema_behind(engine):
- raise StaleIndexError
- factory = create_session_factory(engine)
- session = await stack.enter_async_context(get_session(factory))
- repo = await get_repository_by_path(session, str(root))
- if repo is None and get_configured_db_url() is None:
- # A moved repo carries its local store but retains the old
- # local_path. Never infer identity in a configured/shared store
- # or when the local store contains more than one repository.
- repos = (await session.scalars(select(Repository).limit(2))).all()
- if len(repos) == 1:
- repo = repos[0]
- if repo is not None:
- opened = (session, repo.id)
- except (SQLAlchemyError, OSError, LookupError):
- opened = None
- yield opened
-
-
-#: Busy timeout for the reconcile's own connection. The engine default is 30s,
-#: sized for bulk graph-edge writes; inheriting it here is a trap, because a
-#: read command opens several engines (``status`` four, ``doctor`` five) and a
-#: store locked by a concurrent ``repowise update`` would stall each one in
-#: turn — measured at 133s of silence for ``status`` before this was bounded.
-#: The reconcile is a best-effort secondary write, so it takes the same lever
-#: issue #326 gave the cost tracker: fail fast and be dropped rather than block.
-_RECONCILE_BUSY_TIMEOUT_MS = 2000
-
-
-async def reconcile_schema_best_effort(db_url: str) -> None:
- """Back-fill additive schema drift on the store at *db_url*, best-effort.
-
- An index built by an older repowise is missing whatever columns the models
- have gained since, and the ORM then fails with a raw ``no such column`` on
- the first query — which for a read command means every read. ``init_db``
- back-fills those columns in place and is idempotent, so the CLI pairs it
- with ``create_engine`` where a command opens a store, the way the MCP
- server, the workspace registry and the FastAPI app already do in their
- lifespans. :func:`repo_index_session` runs it only on a store found behind.
-
- Opportunistic, not a precondition, which is the part worth having in one
- place. Reconciling needs a write, and a store can be read-only or
- exclusively locked by a concurrent ``repowise update``. Aborting there would
- be a regression twice over: a store already on the current schema needs no
- DDL and would have read fine, and where the drift is real the following
- query fails with the ``no such column`` that the failure shield turns into
- "this index predates the installed repowise, run repowise update" — a
- better answer than whichever write error stopped the repair.
-
- Takes a URL rather than an engine so the repair runs on its own short-timeout
- connection: the caller's engine keeps the full 30s window for the work it was
- opened to do, and a contended repair gives up in two seconds instead of
- stalling the command behind it.
-
- Never CREATES a store. ``init_db`` on a fresh path would materialise a
- 42-table file, so a read command run in a repo that was never indexed would
- leave a database behind where the user expects "not indexed yet".
- """
- from repowise.core.persistence import create_engine, init_db
-
- if _missing_sqlite_file(db_url):
- return
-
- engine = create_engine(db_url, busy_timeout_ms=_RECONCILE_BUSY_TIMEOUT_MS)
- try:
- with contextlib.suppress(Exception):
- await init_db(engine)
- finally:
- with contextlib.suppress(Exception):
- await engine.dispose()
-
-
-def _missing_sqlite_file(db_url: str) -> bool:
- """True when *db_url* names a SQLite file that does not exist yet.
-
- Only SQLite is checked: a server-backed URL has no file to create, and the
- caller is not the component that decides whether that database should exist.
- """
- if not db_url.startswith("sqlite"):
- return False
- _, sep, tail = db_url.partition(":///")
- if not sep or not tail or tail.startswith(":memory:"):
- return False
- return not Path(tail).exists()
-
-
-def db_configured() -> bool:
- """True when ``REPOWISE_DB_URL`` or ``REPOWISE_DATABASE_URL`` is set.
-
- The DB may still be the repo-local ``wiki.db`` default — the file
- existence check the callers pair this with decides that.
- """
- from repowise.core.persistence import get_configured_db_url
-
- return get_configured_db_url() is not None
-
-
-# ---------------------------------------------------------------------------
-# State file
-# ---------------------------------------------------------------------------
-
-
-def load_state(repo_path: Path) -> dict[str, Any]:
- """Load ``.repowise/state.json`` or return an empty dict if absent."""
- state_path = get_repowise_dir(repo_path) / STATE_FILENAME
- if state_path.exists():
- return json.loads(state_path.read_text(encoding="utf-8"))
- return {}
-
-
-#: Slots the last whole-repo generation put in front of this repository's
-#: signals, which is not the same as the slots that produced a page. The two
-#: differ, and only the first answers "has this index ever been offered a
-#: Glossary?".
-ONBOARDING_SLOTS_OFFERED_KEY = "onboarding_slots_offered"
-
-
-def stamp_offered_slots(state: dict[str, Any], *, enabled: bool = True) -> None:
- """Record which onboarding slots this whole-repo run evaluated.
-
- Only a run that generates the whole repository may call this: the slot
- gates read whole-repo signals, so a scoped run that saw one changed file
- has not offered anything to anything.
-
- Written because a missing onboarding row has two causes that look identical
- in a store and want opposite responses. A slot registered after this index
- was built has never been evaluated here, and ``update --full`` would build
- it; a slot that *was* evaluated and whose gate refused the repository will
- be refused again by the same signals, and telling the user to spend a model
- run on it is a lie. Measured on ``test-repos/microdot``: of the five
- registered slots, two produce pages and three (``getting_started``,
- ``active_landscape``, ``glossary``) are gate-skipped on every run, full or
- fresh. A notice driven by the rows alone would name all three, forever, and
- none of them would ever arrive.
-
- ``enabled`` is the run's ``enable_onboarding``. A run with onboarding off
- offered nothing, and recording otherwise would silence the notice for a
- user who later turns it on.
- """
- from repowise.core.generation.onboarding import iter_specs
-
- state[ONBOARDING_SLOTS_OFFERED_KEY] = (
- sorted(spec.slot for spec in iter_specs()) if enabled else []
- )
-
-
-def save_state(repo_path: Path, state: dict[str, Any], *, full_index: bool = False) -> None:
- """Write *state* to ``.repowise/state.json``.
-
- Every persist stamps the store-format markers (``store_format_version`` and
- the ``written_by_version`` package version that wrote it) so the upgrade
- layer always has a current record of the store's shape and provenance.
-
- ``full_index`` marks a persist that follows a full-repo (re)generation, so
- the store may be stamped to the terminal store-format version. A routine
- incremental persist leaves it False and the version clamps below any
- ``REINDEX_RECOMMENDED`` gate, keeping a reindex recommendation alive until
- an actual re-index clears it.
-
- A write that changes ``last_sync_commit`` moves the repository row's
- ``head_commit`` to the same commit, so the two stamps never disagree.
- """
- from repowise.core.workspace.update import read_state_commit, restamp_changed_sync_commit
-
- ensure_repowise_dir(repo_path)
- previous = read_state_commit(Path(repo_path))
- try:
- from repowise.cli import __version__ as _pkg_version
- from repowise.core.upgrade import stamp as _stamp_store_version
-
- _stamp_store_version(state, package_version=_pkg_version, full_index=full_index)
- except Exception: # never let stamping block a persist
- pass
- from repowise.core.fsutils import atomic_write_text
-
- # Atomic so a crash mid-write can never leave a truncated state.json —
- # every later update would fail to parse it and demand a full re-init.
- state_path = get_repowise_dir(repo_path) / STATE_FILENAME
- atomic_write_text(state_path, json.dumps(state, indent=2))
- restamp_changed_sync_commit(Path(repo_path), previous, state.get("last_sync_commit"))
-
-
-# ---------------------------------------------------------------------------
-# Queued / pending markers — coordinate the post-commit hook with a running
-# update so rapid-fire commits don't spawn N concurrent updates that race
-# on save_state. Two distinct markers, deliberately:
-#
-# ``.update.queued`` : written by the hook BEFORE backgrounding repowise
-# update. Closes the race window between commit and
-# lock acquisition — the augment hook reads this
-# and suppresses its warning the moment the queued
-# file appears, not 30+ seconds later when the
-# actual lock file lands on disk.
-#
-# ``.update.pending`` : written by a *new* update_cmd invocation when it
-# finds an in-flight lock. Carries the latest HEAD
-# so the running update can roll forward to it at
-# the end of its current pass instead of stopping
-# at a stale commit.
-#
-# Both markers are best-effort: failure to write/read them must never break
-# update_cmd itself, only degrade the coalescing behaviour to "spawn but
-# bail" (slightly noisier in the augment hook but still correct).
-# ---------------------------------------------------------------------------
-
-UPDATE_QUEUED_FILENAME = ".update.queued"
-UPDATE_PENDING_FILENAME = ".update.pending"
-
-# A ``.update.queued`` marker older than this is treated as stale — most
-# likely a crashed hook that wrote the marker but never spawned the update.
-# Short enough to avoid suppressing genuinely-stale warnings indefinitely.
-UPDATE_QUEUED_STALE_AFTER_SECONDS = 5 * 60
-
-
-def _update_queued_path(repo_path: Path) -> Path:
- return get_repowise_dir(repo_path) / UPDATE_QUEUED_FILENAME
-
-
-def _update_pending_path(repo_path: Path) -> Path:
- return get_repowise_dir(repo_path) / UPDATE_PENDING_FILENAME
-
-
-def write_update_queued(repo_path: Path, head: str | None) -> None:
- """Mark that an update has been spawned for ``head``.
-
- Called from the post-commit hook *before* backgrounding ``repowise
- update`` so the augment hook can suppress its stale-wiki warning during
- the brief window where the actual update process is still starting up
- (Python import, DB open, etc.) and hasn't yet written its own lock file.
- """
- import time
-
- try:
- ensure_repowise_dir(repo_path)
- except OSError:
- return
- payload = {"target_commit": head, "queued_at": time.time()}
- with contextlib.suppress(OSError):
- _update_queued_path(repo_path).write_text(json.dumps(payload), encoding="utf-8")
-
-
-def read_update_queued(repo_path: Path) -> dict[str, Any] | None:
- """Return queued payload if fresh (≤ ``UPDATE_QUEUED_STALE_AFTER_SECONDS``)."""
- import time
-
- path = _update_queued_path(repo_path)
- if not path.exists():
- return None
- try:
- payload = json.loads(path.read_text(encoding="utf-8"))
- except (json.JSONDecodeError, OSError):
- return None
- queued_at = payload.get("queued_at")
- if not isinstance(queued_at, (int, float)):
- return None
- if time.time() - queued_at > UPDATE_QUEUED_STALE_AFTER_SECONDS:
- return None
- return payload
-
-
-def clear_update_queued(repo_path: Path) -> None:
- """Drop the queued marker. Called by update_cmd once it owns the real lock."""
- with contextlib.suppress(OSError):
- _update_queued_path(repo_path).unlink(missing_ok=True)
-
-
-def write_update_pending(repo_path: Path, head: str | None) -> None:
- """Record that another commit landed while an update was in flight.
-
- The running update reads this at the end of its pass and rolls forward
- to the new HEAD in one extra round, avoiding the failure mode where a
- rapid burst of commits leaves the wiki indexed to an outdated commit.
- """
- if head is None:
- return
- try:
- ensure_repowise_dir(repo_path)
- except OSError:
- return
- with contextlib.suppress(OSError):
- _update_pending_path(repo_path).write_text(head, encoding="utf-8")
-
-
-def read_update_pending(repo_path: Path) -> str | None:
- """Return the pending HEAD if any, else None."""
- path = _update_pending_path(repo_path)
- if not path.exists():
- return None
- try:
- head = path.read_text(encoding="utf-8").strip()
- except OSError:
- return None
- return head or None
-
-
-def clear_update_pending(repo_path: Path) -> None:
- """Drop the pending marker once the rolled-forward update has consumed it."""
- with contextlib.suppress(OSError):
- _update_pending_path(repo_path).unlink(missing_ok=True)
-
-
-def _pending_commit_still_ahead(
- repo_path: Path, pending_head: str, indexed_head: str | None
-) -> bool:
- """True only when ``pending_head`` is a resolvable commit strictly ahead of
- ``indexed_head`` — a newer commit the index has not caught up to yet.
-
- Equal commits, ancestors of ``indexed_head``, and commits that no longer
- resolve (rebased or gc'd away) all return ``False``, so the caller clears
- them instead of leaving the marker behind forever.
- """
- if not indexed_head or pending_head == indexed_head:
- return False
- import subprocess
-
- if as_commit_id(indexed_head) is None or as_commit_id(pending_head) is None:
- return False
- try:
- # ``indexed_head`` is an ancestor of ``pending_head`` => pending is
- # newer than what we indexed and worth keeping. A non-zero exit
- # (including an unresolvable pending commit) means "not ahead".
- result = subprocess.run(
- ["git", "merge-base", "--is-ancestor", "--end-of-options", indexed_head, pending_head],
- cwd=str(repo_path),
- capture_output=True,
- timeout=10,
- )
- return result.returncode == 0
- except Exception:
- return False
-
-
-def consume_update_pending(repo_path: Path, indexed_head: str | None) -> None:
- """Clear the ``.update.pending`` marker once the index has caught up to it.
-
- A bailed update writes the latest HEAD to ``.update.pending`` (see
- :func:`write_update_pending`) so the in-flight update can tell more commits
- landed. The update that actually holds the lock calls this when it
- finishes: the marker is obsolete unless it points to a commit strictly
- *ahead* of the one just indexed. The previous consumer only cleared on an
- exact ``pending == head`` match, so once HEAD advanced past the pending
- commit (or that commit was rebased away) the marker leaked indefinitely.
- """
- pending_head = read_update_pending(repo_path)
- if pending_head is None:
- return
- if not _pending_commit_still_ahead(repo_path, pending_head, indexed_head):
- clear_update_pending(repo_path)
-
-
-# ---------------------------------------------------------------------------
-# Hook output log — capped, single-file rotation so the user can diagnose
-# why the post-commit hook didn't catch up without needing to chase down a
-# silent subprocess. Cap is deliberately small: a few recent runs is enough
-# context, and we don't want a runaway log to fill the .repowise/ dir.
-# ---------------------------------------------------------------------------
-
-UPDATE_LOG_FILENAME = ".update.log"
-
-# Truncate the log when it grows past this size, keeping the tail.
-UPDATE_LOG_MAX_BYTES = 256 * 1024
-# After truncation, retain at most this much of the prior tail.
-UPDATE_LOG_KEEP_TAIL_BYTES = 64 * 1024
-
-
-def update_log_path(repo_path: Path) -> Path:
- return get_repowise_dir(repo_path) / UPDATE_LOG_FILENAME
-
-
-def rotate_update_log_if_needed(repo_path: Path) -> None:
- """Truncate ``.update.log`` if it has grown past the size cap.
-
- Called opportunistically from the hook before piping a new run's output
- in. We use simple in-place truncation (rewrite the tail) rather than
- renaming, because the post-commit hook can fire in parallel with a
- `repowise update` that may still be writing — a rename would orphan
- the writer's file descriptor on POSIX and outright fail on Windows.
- """
- path = update_log_path(repo_path)
- try:
- if not path.exists() or path.stat().st_size <= UPDATE_LOG_MAX_BYTES:
- return
- with path.open("rb") as f:
- f.seek(-UPDATE_LOG_KEEP_TAIL_BYTES, 2)
- tail = f.read()
- path.write_bytes(b"... (log truncated) ...\n" + tail)
- except OSError:
- pass
-
-
-# ---------------------------------------------------------------------------
-# Git helpers
-# ---------------------------------------------------------------------------
-
-
-_COMMIT_ID_RE = re.compile(r"[0-9a-fA-F]{7,40}")
-
-
-def as_commit_id(value: object) -> str | None:
- """*value* when it is a full or abbreviated hex commit id, else ``None``.
-
- Commit ids read back from ``.repowise/state.json`` (or a file beside it)
- can be edited by anyone who can commit that file, so they are checked
- before they reach a ``git`` argument list, where a leading ``-`` would be
- read as an option.
- """
- if isinstance(value, str) and _COMMIT_ID_RE.fullmatch(value):
- return value
- return None
-
-
-def get_head_commit(repo_path: Path) -> str | None:
- """Return the HEAD commit SHA or ``None`` if not a git repo.
-
- Delegates to the core implementation (``git rev-parse HEAD``) so the CLI
- and the workspace updater resolve HEAD identically — the old gitpython
- version here could diverge on worktree/detached-HEAD edge cases.
- """
- from repowise.core.workspace.update import get_head_commit as _core_head
-
- return _core_head(Path(repo_path))
-
-
-def head_commit_ts(repo_path: Path) -> float | None:
- """Committer timestamp of the repo's HEAD, or None when git is unavailable.
-
- Anchors the periodic idle-file health re-score gate (#728) to repo time
- rather than wall clock, the same anchor the git history windows use, so
- the cadence is deterministic and correct for historical checkouts.
-
- Shared with ``init`` so a fresh index can stamp ``last_full_rescore_at`` in
- the same units the gate reads it back in.
- """
- try:
- import git
-
- repo = git.Repo(repo_path, search_parent_directories=True)
- try:
- return float(repo.head.commit.committed_date)
- finally:
- repo.close()
- except Exception:
- return None
-
-
-# ---------------------------------------------------------------------------
-# Config (provider / model / embedder persisted after init)
-# ---------------------------------------------------------------------------
-
-
-def load_config(repo_path: Path) -> dict[str, Any]:
- """Load ``.repowise/config.yaml`` or return an empty dict if absent.
-
- A broken config is surfaced as a warning (to stderr, so ``--format json``
- stays parseable) and degrades to an empty dict rather than crashing the
- command or silently using defaults — issue #852: configuration errors must
- be visible, not swallowed. Callers keep their current behaviour either
- way; the warning is the fix.
- """
- try:
- return load_repo_config(repo_path)
- except RepoConfigError as exc:
- err_console.print(f"[yellow]Warning:[/yellow] {exc}")
- return {}
-
-
-def resolve_reasoning(
- reasoning: str | None = None,
- config: dict[str, Any] | None = None,
-) -> ReasoningMode:
- """Resolve generation reasoning from CLI flag, env, config, then default."""
- try:
- return resolve_core_reasoning(reasoning, config)
- except ValueError as exc:
- raise reasoned_error(str(exc), reason="invalid_reasoning") from exc
-
-
-def resolve_max_file_pages(
- chosen: int | None = None,
- config: dict[str, Any] | None = None,
-) -> int | None:
- """Resolve the file-page cap: explicit choice, then config.yaml, then unset.
-
- Three states reach ``GenerationConfig.max_file_pages`` (see its comment and
- ``selection/selector.py``): ``None`` leaves the volume policy in charge, ``0``
- is an explicit refusal to cap, and a positive value is a cap.
-
- A negative or unparseable ``max_file_pages`` in config.yaml resolves to
- ``None`` rather than to zero pages, so a typo hands the decision back to the
- policy instead of silently deleting the file layer.
- """
- raw = chosen if chosen is not None else (config or {}).get("max_file_pages")
- if raw is None:
- return None
- try:
- value = int(raw)
- except (TypeError, ValueError):
- return None
- if value == 0:
- return 0 # "all of them", and it survives the policy
- return value if value > 0 else None
-
-
-def _persist_provider_key(repo_path: Path, provider: str) -> None:
- """Mirror ``provider``'s credential from the environment into ``.repowise/.env``.
-
- Key persistence used to hang off the interactive key *prompt*, so it only
- ran when the user typed a key. Supplying the key through the environment is
- precisely the no-prompt case, which meant a scripted
- ``init --provider openai --yes`` indexed fine and wrote ``provider:`` to
- config.yaml but left no credential behind: ``repowise mcp`` against that
- repo then answered ``degraded: "no-llm-provider"``. Scripted init is the
- primary path for agents and CI, so a run that succeeds has to leave a repo
- whose MCP server can actually answer.
-
- The rule, stated out loud: a key that successfully indexed this repo is the
- key this repo needs, so it is saved, with a notice naming the file and
- ``--no-save-key`` to opt out. Nothing is written for a provider that needs
- no credential.
-
- Routed through :func:`save_repo_env_key` rather than writing the file here:
- the ``.gitignore`` entry and the owner-only mode come with it, and a
- hand-rolled write would leave a committable secret.
-
- Best-effort by design. It runs at the tail of a completed init, after the
- index has been paid for, and it is the first thing on that path to write
- outside ``.repowise/``, so a read-only checkout or an unwritable
- ``.gitignore`` must cost the user a warning, not the run.
- """
- from repowise.core.providers.llm.registry import PROVIDER_API_KEY_ENVS
- from repowise.core.repo_config import save_repo_env_key
-
- if _clean_flag(os.environ.get(NO_SAVE_KEY_ENV)):
- return
-
- # Keys only. ``provider_required_envs`` would also hand back ollama's
- # OLLAMA_BASE_URL, and pinning an endpoint into the repo is a different
- # decision from saving a credential: a later run on another network
- # would silently reuse the stale URL.
- #
- # Some providers accept either of two vars (gemini: GEMINI_API_KEY /
- # GOOGLE_API_KEY). Persist the one actually carrying the value, not both,
- # so the var written is the var `provider_kwargs` will read back.
- for env_var in PROVIDER_API_KEY_ENVS.get(provider, ()):
- value = (os.environ.get(env_var) or "").strip()
- if not value:
- continue
- try:
- save_repo_env_key(repo_path, env_var, value)
- except (OSError, ValueError) as exc:
- warn(
- f"could not save {env_var} to "
- f".repowise/.env ({exc}). The index is complete, but "
- f"`repowise mcp` will need {env_var} in its environment."
- )
- return
- console.print(
- f"[dim]Saved {env_var} to .repowise/.env (gitignored). "
- f"--no-save-key or {NO_SAVE_KEY_ENV}=1 to skip.[/dim]"
- )
- return
-
-
-def save_config(
- repo_path: Path,
- provider: str,
- model: str,
- embedder: str,
- *,
- embedding_model: str | None = None,
- exclude_patterns: list[str] | None = None,
- commit_limit: int | None = None,
- reasoning: str | None = None,
- save_key: bool = True,
-) -> None:
- """Write provider/model/embedder (and optionally exclude_patterns) to ``.repowise/config.yaml``.
-
- Performs a round-trip load so existing keys are preserved.
-
- ``embedding_model`` is persisted so ``repowise serve`` can rebuild the same
- embedder used at init time — without it the server silently falls back to a
- provider default (e.g. ``text-embedding-3-small``), which mismatches the
- indexed vectors and breaks chat/search retrieval (issue #426).
-
- ``save_key`` also mirrors the provider's credential into ``.repowise/.env``.
- It belongs here because this function *is* the "this run committed to this
- provider for this repo" moment, shared by all three flows that reach it
- (single-repo init, workspace init, ``workspace add``). All three otherwise
- leave an indexed repo their MCP server cannot authenticate against.
- """
- from repowise.core.providers.llm.resolve import apply_llm_selection
- from repowise.core.repo_config import save_repo_config
-
- ensure_repowise_dir(repo_path)
-
- # Round-trip: preserve any existing keys (e.g. exclude_patterns set via CLI).
- # provider/model go through the writer the web UI uses too.
- existing = apply_llm_selection(load_config(repo_path), provider, model)
- existing["embedder"] = embedder
- if embedding_model:
- existing["embedding_model"] = embedding_model
- else:
- # No model was resolved this run: dropping the key beats leaving a
- # stale one that names a different provider's model, or one this
- # embedder was not actually built with (#2627).
- existing.pop("embedding_model", None)
- if exclude_patterns is not None:
- existing["exclude_patterns"] = exclude_patterns
- if commit_limit is not None:
- existing["commit_limit"] = commit_limit
- if reasoning is not None:
- existing["reasoning"] = resolve_reasoning(reasoning)
-
- save_repo_config(repo_path, existing)
- _trust_configured_base_url(repo_path, existing, provider)
-
- if save_key:
- _persist_provider_key(repo_path, provider)
-
-
-def _trust_configured_base_url(repo_path: Path, config: dict[str, Any], provider: str) -> None:
- """Record ``<provider>.base_url`` as confirmed: this init run chose to use it.
-
- A config.yaml base URL only receives a key from outside the repo's own
- ``.env`` once the user confirmed it on this machine; running ``init``
- with it in place is that confirmation. An invalid URL is left unconfirmed,
- and resolution reports it.
- """
- from repowise.core.providers.llm.resolve import trust_base_url, validate_base_url
-
- section = config.get(provider)
- if not isinstance(section, dict):
- return
- try:
- url = validate_base_url(section.get("base_url"))
- except ValueError:
- return
- if url:
- with contextlib.suppress(OSError):
- trust_base_url(repo_path, url)
-
-
-def save_config_partial(
- repo_path: Path,
- *,
- exclude_patterns: list[str] | None = None,
- commit_limit: int | None = None,
- **extra: Any,
-) -> None:
- """Merge optional keys into ``.repowise/config.yaml``, preserving existing keys.
-
- ``exclude_patterns`` / ``commit_limit`` are explicit for the common case;
- any other config keys (e.g. ``enable_onboarding=False``) can be passed as
- keyword arguments. ``None`` values are skipped so callers can forward
- optional flags without clobbering existing keys.
-
- ``embedding_model`` is the one exception to "None is skipped": passed
- explicitly as ``None``, it clears any pinned model instead of leaving it
- alone, because that is the caller saying the model changed (or is no
- longer known) for whatever embedder this call names. Merely *omitting*
- ``embedding_model`` is not the same claim, so it does not clear anything
- on its own -- ``reindex_cmd`` calls this after every reindex with only
- ``embedder=``, having never had a model to pass, and a bare ``in extra``
- check on ``embedder`` used to read that silence as "no model" and wipe a
- real pin on every routine reindex (#2627, caught in review on the fix
- itself). Distinguishing "not passed" from "passed as ``None``" needs the
- raw ``extra`` dict, since a keyword default cannot do it: ``in extra``
- only reports that once, but ``get`` cannot tell the two shapes apart
- afterwards.
- """
- import yaml # type: ignore[import-untyped]
-
- updates: dict[str, Any] = {}
- if exclude_patterns is not None:
- updates["exclude_patterns"] = exclude_patterns
- if commit_limit is not None:
- updates["commit_limit"] = commit_limit
- updates.update({k: v for k, v in extra.items() if v is not None})
- clear_embedding_model = "embedding_model" in extra and extra["embedding_model"] is None
- if not updates and not clear_embedding_model:
- return
-
- ensure_repowise_dir(repo_path)
- config_path = get_repowise_dir(repo_path) / CONFIG_FILENAME
- existing = load_config(repo_path)
- existing.update(updates)
- if clear_embedding_model:
- existing.pop("embedding_model", None)
-
- config_path.write_text(
- yaml.dump(existing, default_flow_style=False, sort_keys=False),
- encoding="utf-8",
- )
-
-
-def save_distill_commands_enabled(repo_path: Path, *, enabled: bool) -> None:
- """Deep-merge ``distill.commands.enabled`` into ``.repowise/config.yaml``.
-
- :func:`save_config_partial` merges shallowly at the top level, so the
- ``distill`` block is merged here first to avoid clobbering sibling keys
- like ``disabled_filters``.
- """
- cfg = load_config(repo_path)
- distill = dict(cfg.get("distill") or {})
- commands = dict(distill.get("commands") or {})
- commands["enabled"] = enabled
- distill["commands"] = commands
- save_config_partial(repo_path, distill=distill)
-
-
-#: The hook surfaces that *replace* a tool result rather than adding to it.
-#: One consent turns them all on; each has its own ``repowise hook <name>``
-#: toggle afterwards, so a surface that turns out to be wrong can be dropped
-#: without taking the others with it.
-HOOK_REPLACEMENT_SURFACES = ("read_skeleton", "search_digest")
-
-
-def save_hook_surface_enabled(repo_path: Path, surface: str, *, enabled: bool) -> None:
- """Deep-merge ``hooks.<surface>`` into ``.repowise/config.yaml``.
-
- Same shape as :func:`save_distill_commands_enabled`, and written by the
- same consent: the rewrite-hook prompt means "let repowise's hooks
- intervene in your agent's tool calls", and rewriting a Bash command is a
- larger intervention than serving a Read as its skeleton or a search as its
- digest, not a smaller one. There is deliberately no second question.
- """
- cfg = load_config(repo_path)
- hooks = dict(cfg.get("hooks") or {})
- hooks[surface] = enabled
- save_config_partial(repo_path, hooks=hooks)
-
-
-def config_fingerprint(repo_path: Path) -> str:
- """SHA-256 hex of ``.repowise/config.yaml`` + ``health-rules.json`` content.
-
- Delegates to the shared core implementation so CLI runs and server jobs
- compute identical fingerprints for the same on-disk config.
- """
- from repowise.core.repo_config import config_fingerprint as _core_fingerprint
-
- return _core_fingerprint(repo_path)
-
-
-# ---------------------------------------------------------------------------
-# Provider resolution
-# ---------------------------------------------------------------------------
-
-
-def resolve_provider(
- provider_name: str | None,
- model: str | None,
- repo_path: Path | None = None,
-) -> Any:
- """Resolve a provider instance from CLI flags, the repo config, or env.
-
- The order is the shared one in :mod:`repowise.core.providers.llm.resolve`:
- ``--provider`` / ``--model`` > ``.repowise/config.yaml`` > the global
- default in ``provider_config.json`` > ``REPOWISE_PROVIDER`` /
- ``REPOWISE_MODEL`` > auto-detection from API keys.
- """
- from repowise.core.providers.llm.resolve import resolve_llm
-
- selection = resolve_llm(repo_path, provider=provider_name, model=model)
- if selection.provider is None:
- # Not fatal on every path: `init` catches this and renders a template
- # wiki instead, so the reason must not be recorded until it ends a
- # command.
- raise reasoned_error(_no_provider_message(), reason="no_provider_configured")
- return _build_provider(selection, _provider_kwargs_or_error(selection, repo_path))
-
-
-def _provider_kwargs_or_error(selection: Any, repo_path: Path | None) -> dict[str, Any]:
- """Constructor kwargs, warning when a configured provider has no key anywhere."""
- from repowise.core.providers.llm.resolve import llm_provider_kwargs
-
- try:
- kwargs = llm_provider_kwargs(selection, repo_path)
- except ValueError as exc:
- # A base URL the repo's config.yaml sets that is malformed, or that
- # nobody on this machine confirmed for a key from elsewhere.
- raise reasoned_error(str(exc), reason="provider_setup_failed") from exc
- if selection.provider_source != "autodetect" and "api_key" not in kwargs:
- # A configured provider whose key is nowhere still gets built: the
- # constructor says what it needs. Agent CLIs are checked for install.
- for warning in validate_provider_config(selection.provider):
- warn(warning)
- return kwargs
-
-
-def _build_provider(selection: Any, kwargs: dict[str, Any]) -> Any:
- """Construct the provider, turning a setup failure into a config error."""
- from repowise.core.providers import get_provider
-
- try:
- return get_provider(selection.provider, **kwargs)
- except click.ClickException:
- raise
- except Exception as exc:
- # Everything this constructor reads is user input: env vars and
- # .repowise/config.yaml, base_url above all. A typo there is a
- # configuration error, not a repowise bug, but it used to surface as
- # a raw traceback that escaped every caller's handler.
- raise reasoned_error(
- f"Could not set up the {selection.provider} provider: {exc}. "
- f"Resolved {selection.describe()}. Check those settings.",
- reason="provider_setup_failed",
- ) from exc
-
-
-def _no_provider_message() -> str:
- """The no-provider error, listing every env var that would configure one."""
- from repowise.core.providers.llm.registry import (
- PROVIDER_AUTODETECT_ORDER,
- provider_required_envs,
- )
-
- env_vars = [var for name in PROVIDER_AUTODETECT_ORDER for var in provider_required_envs(name)]
- return (
- "No provider configured. Use --provider, set provider in .repowise/config.yaml or "
- f"REPOWISE_PROVIDER, or set one of {' / '.join(env_vars)}. Use "
- "REPOWISE_PROVIDER=claude_cli to use an authenticated Claude Code subscription, "
- "REPOWISE_PROVIDER=codex_cli to use an authenticated Codex CLI subscription, or "
- "REPOWISE_PROVIDER=opencode to use opencode."
- )
-
-
-def resolve_explicit_provider_or_prompt(
- provider_name: str | None,
- model: str | None,
- repo_path: Path,
- *,
- interactive: bool,
- save_key: bool = True,
-) -> Any:
- """Resolve an explicit provider, onboarding missing credentials in a TTY.
-
- ``resolve_provider`` stays non-interactive because hooks, CI, and library
- callers must never block on stdin. ``init`` can opt into this wrapper when
- it has a real terminal: a missing explicit provider key gets the same
- inline setup as the provider picker, and an explicit OpenAI provider also
- gets the endpoint question used by local gateways.
- """
- from repowise.cli.ui.provider_selection import interactive_provider_credentials
-
- if interactive and provider_name == "openai":
- # A pty can report TTY while stdin is not readable. Let the normal
- # resolution below produce the actionable provider error instead of
- # replacing it with Abort.
- with contextlib.suppress(EOFError, click.Abort):
- interactive_provider_credentials(
- console,
- provider_name,
- repo_path=repo_path,
- save_key=save_key,
- )
-
- return resolve_provider(provider_name, model, repo_path=repo_path)
-
- try:
- return resolve_provider(provider_name, model, repo_path=repo_path)
- except click.ClickException as original_error:
- if not interactive or provider_name is None:
- raise
-
- try:
- configured = interactive_provider_credentials(
- console,
- provider_name,
- repo_path=repo_path,
- save_key=save_key,
- )
- except (EOFError, click.Abort):
- # A pty can report TTY while stdin is not readable. Preserve the
- # actionable provider error instead of replacing it with Abort.
- raise original_error from None
-
- if not configured:
- raise original_error
- return resolve_provider(provider_name, model, repo_path=repo_path)
-
-
-def resolve_provider_or_prompt(
- provider_name: str | None,
- model: str | None,
- repo_path: Path,
- *,
- reasoning: str | None = None,
- interactive: bool,
-) -> Any:
- """Resolve a provider, falling back to init's interactive setup on a miss.
-
- Ordinary resolution is :func:`resolve_provider`. When that fails because no
- provider/key is configured and ``interactive`` is set (an interactive
- terminal, not a hook / CI / ``--progress json`` run), reuse init's exact
- provider + API-key prompt, persist the choice, and retry — so a docs run
- that only just asked for LLM pages onboards the same way ``init`` does
- instead of dying with "No provider configured".
-
- When ``interactive`` is False the original error propagates unchanged, so
- background runs (post-commit hook, CI, machine-driven ``--progress json``)
- keep their clean, non-blocking failure.
-
- Persistence reuses init's helpers: the key lands in ``.repowise/.env`` (from
- the prompt) and provider/model in ``.repowise/config.yaml`` here, so the
- prompt only ever appears once per repo.
- """
- try:
- return resolve_provider(provider_name, model, repo_path=repo_path)
- except Exception as original_error:
- if not interactive:
- raise
- from repowise.cli.ui import interactive_provider_config_select
-
- # ``interactive`` rests on ``isatty()``, which lies: under Git Bash,
- # some pty wrappers, and ``docker run -t`` without -i it claims a
- # terminal it cannot read from, and agents drive us through exactly
- # those shapes. Treat the prompt as the probe (as init does): if stdin
- # cannot answer, click raises EOFError/Abort, so fall back to the clean,
- # actionable "No provider configured" error instead of a bare "Aborted!".
- try:
- selection = interactive_provider_config_select(
- console, model, reasoning, repo_path=repo_path
- )
- except (EOFError, click.Abort):
- raise original_error from None
-
- # Persist provider/model so future runs resolve without re-prompting.
- # The API key was already persisted to .repowise/.env by the prompt.
- save_config_partial(
- repo_path,
- provider=selection.provider_name,
- model=selection.model,
- )
- return resolve_provider(selection.provider_name, selection.model, repo_path=repo_path)
-
-
-# ---------------------------------------------------------------------------
-# Provider validation
-# ---------------------------------------------------------------------------
-
-
-def validate_provider_config(
- provider_name: str | None = None, repo_path: Path | None = None
-) -> list[str]:
- """Validate that required API keys/environment variables are set for the provider.
-
- Args:
- provider_name: The provider name to validate. If None, checks all possible providers.
- repo_path: The repo whose configured provider counts as explicitly requested.
-
- Returns:
- List of warning messages for missing or invalid configuration.
- Empty list means all required config is present.
- """
- warnings = []
-
- def _is_env_var_set(var_name: str) -> bool:
- """Check if environment variable is set and non-empty."""
- value = os.environ.get(var_name)
- return value is not None and value.strip() != ""
-
- def _is_env_var_exists(var_name: str) -> bool:
- """Check if environment variable exists (even if empty)."""
- return var_name in os.environ
-
- # Required environment variables per provider, read from the registry that
- # also drives resolution, so a provider added there is validated here without
- # a second edit. The agent-CLI providers need no env var; the check for them
- # is whether their CLI is installed.
- from repowise.core.agents.identity import identity_for_provider
- from repowise.core.providers.llm.registry import provider_required_envs
- from repowise.core.providers.llm.specs import PROVIDER_SPECS
-
- provider_env_vars = {
- name: list(provider_required_envs(name))
- for name in PROVIDER_SPECS
- if provider_required_envs(name)
- }
-
- if provider_name:
- agent = identity_for_provider(provider_name)
- if agent is not None:
- if not agent.is_installed():
- warnings.append(
- f"Provider '{provider_name}' requires the {agent.display_name} CLI.\n"
- f" Install: {agent.install_hint}\n"
- f" Setup: {agent.login_hint}"
- )
- return warnings
-
- # Validate specific provider
- if provider_name not in provider_env_vars:
- warnings.append(f"Unknown provider '{provider_name}' - cannot validate configuration")
- return warnings
-
- # Any one of a provider's env vars satisfies it (GEMINI_API_KEY or
- # GOOGLE_API_KEY), the same rule resolution applies.
- env_vars = provider_env_vars[provider_name]
- if not any(_is_env_var_set(var) for var in env_vars):
- warnings.append(f"Provider '{provider_name}' requires {' or '.join(env_vars)}")
- else:
- # Check all providers - warn about any that could be configured but are missing keys
- from repowise.core.providers.llm.resolve import resolve_llm
-
- configured = resolve_llm(repo_path, autodetect=False).provider
- for name, env_vars in provider_env_vars.items():
- if any(_is_env_var_set(var) for var in env_vars):
- continue
- # Only warn if this provider is explicitly requested OR
- # if the env var exists but is invalid (empty)
- env_var_exists = any(_is_env_var_exists(var) for var in env_vars)
- explicitly_requested = configured == name
- if explicitly_requested or env_var_exists:
- warnings.append(f"Provider '{name}' requires {' or '.join(env_vars)}")
-
- return warnings
-
-
-# ---------------------------------------------------------------------------
-# Command target resolution — auto-detect single-repo vs workspace mode
-# ---------------------------------------------------------------------------
-#
-# Many CLI commands (``update``, ``status``, ``watch``, ``generate-claude-md``,
-# ``doctor``, ``costs``, ``search``, ``dead-code``, ``decision``, hooks) need
-# to decide whether the user means "this one repo" or "the surrounding
-# workspace". Historically each command did its own ad-hoc detection (or
-# none), which produced the Phase A bug where ``repowise update`` from a
-# workspace root errored with a misleading "No previous sync found" message
-# and left a stray ``.repowise/`` directory behind.
-#
-# ``resolve_command_target`` is the single source of truth. Every command
-# should call it before doing any work. See ``docs/WORKSPACE_ROBUSTNESS.md``
-# for the UX principles.
-
-
-@dataclass
-class CommandTarget:
- """Resolved target for a CLI invocation — single repo or workspace.
-
- Attributes:
- mode: ``"single"`` or ``"workspace"``.
- repo_path: For single mode, the resolved repo path. For workspace
- mode, ``None`` (use ``ws_root`` + ``ws_config`` instead, or the
- ``primary_path()`` helper).
- ws_root: Workspace root path. Set in workspace mode; also set in
- single mode when a workspace exists *upstream* of the chosen
- repo, so commands can surface that context.
- ws_config: Loaded workspace config (workspace mode only).
- repo_filter: Optional alias filter for workspace mode (e.g.
- ``--repo backend``). ``None`` means "all repos".
- reason: Short human-readable explanation of why this target was
- chosen. Surfaced via :meth:`notice`.
- auto_detected: ``True`` when the workspace context was inferred
- rather than requested via an explicit flag. Used to decide
- whether to print a transparency notice.
- """
-
- mode: Literal["single", "workspace"]
- repo_path: Path | None = None
- ws_root: Path | None = None
- ws_config: Any | None = None # WorkspaceConfig (avoid hard import here)
- repo_filter: str | None = None
- reason: str = ""
- auto_detected: bool = False
-
- # ------------------------------------------------------------------
- # Convenience accessors
- # ------------------------------------------------------------------
-
- @property
- def is_workspace(self) -> bool:
- return self.mode == "workspace"
-
- def primary_path(self) -> Path | None:
- """Return the workspace's primary repo path, if known."""
- if self.ws_config is None or self.ws_root is None:
- return None
- primary = self.ws_config.get_primary()
- if primary is None:
- return None
- return (self.ws_root / primary.path).resolve()
-
- def resolve_repo_alias(self, alias: str | None) -> Path | None:
- """Resolve an alias to an absolute repo path within the workspace.
-
- Returns ``None`` if the workspace is not loaded or the alias is
- unknown. Used by commands that accept ``--repo <alias>``.
- """
- if self.ws_config is None or self.ws_root is None or alias is None:
- return None
- entry = self.ws_config.get_repo(alias)
- if entry is None:
- return None
- return (self.ws_root / entry.path).resolve()
-
- def single_repo_path(self) -> Path:
- """The one repository to read, narrowing workspace mode to a repo.
-
- ``--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`.
-
- Raises ``click.ClickException`` when the alias is unknown or the
- workspace declares no primary.
- """
- if not self.is_workspace:
- assert self.repo_path is not None
- return self.repo_path
- if self.repo_filter is not None:
- picked = self.resolve_repo_alias(self.repo_filter)
- if picked is None:
- raise click.ClickException(f"Unknown repo alias: {self.repo_filter}")
- return picked
- primary = self.primary_path()
- if primary is None:
- raise click.ClickException("Workspace has no primary repo configured.")
- return primary
-
- # ------------------------------------------------------------------
- # Notice rendering — every command should call this so users always
- # know which mode they ended up in.
- # ------------------------------------------------------------------
-
- def notice(self, console_obj: Console, *, command: str = "") -> None:
- """Print a one-line transparency notice describing the chosen target.
-
- - Always printed when ``auto_detected`` is True.
- - Also printed when in workspace mode (even if flagged explicitly)
- so the repo list is visible at the top of the command output.
- - Silent when single-repo mode was explicitly requested.
- """
- if self.mode == "workspace":
- ws_root = self.ws_root.name if self.ws_root else "?"
- 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"[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"[cyan]{repos}[/cyan] repos in [cyan]{ws_root}[/cyan]"
- )
- if self.reason and self.auto_detected:
- console_obj.print(f"[dim] ({self.reason})[/dim]")
- return
-
- # Single-repo mode — only narrate when the resolution was non-obvious.
- 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"[cyan]{self.repo_path}[/cyan] "
- f"(workspace also detected at [cyan]{self.ws_root}[/cyan]; "
- f"pass --workspace to run across all repos)"
- )
-
-
-class WorkspaceNotFound(click.ClickException):
- """Raised when ``--workspace`` was requested but no workspace was found."""
-
-
-def resolve_command_target(
- *,
- path: str | None = None,
- workspace_flag: bool = False,
- no_workspace_flag: bool = False,
- repo_alias: str | None = None,
-) -> CommandTarget:
- """Resolve whether a command should operate on a single repo or workspace.
-
- The resolution rules (first match wins):
-
- 1. ``--no-workspace`` → single-repo targeting ``path`` (or cwd). Hard
- override for users who want the old behavior.
- 2. ``--workspace`` or ``--repo <alias>`` → workspace mode. Raises
- :class:`WorkspaceNotFound` if no workspace can be located.
- 3. Explicit ``path`` argument:
- - If the path itself contains ``.repowise-workspace.yaml`` →
- workspace mode (treats the path as the workspace root).
- - Otherwise → single-repo mode targeting that path. We do *not*
- auto-promote to workspace when the user has explicitly typed a
- path — explicit beats implicit.
- 4. No ``path``, no flags → start from cwd and:
- - If cwd is itself a workspace root → workspace mode.
- - If cwd has its own ``.repowise/state.json`` (i.e. it's a repo
- that has been indexed before) → single-repo mode, even if a
- workspace exists upstream. cd-into-the-repo is the strongest
- signal of user intent.
- - If a workspace exists upstream of cwd → workspace mode.
- - Otherwise → single-repo mode (cwd, even if not indexed).
-
- The returned :class:`CommandTarget` carries a ``reason`` string and an
- ``auto_detected`` flag so commands can render a transparent notice.
- """
- if workspace_flag and no_workspace_flag:
- raise click.UsageError("--workspace and --no-workspace are mutually exclusive.")
-
- if repo_alias is not None and no_workspace_flag:
- raise click.UsageError(
- "--repo <alias> implies workspace mode, but --no-workspace was passed."
- )
-
- explicit_path = path is not None
- base_path = resolve_repo_path(path)
-
- # Local import — avoids a circular import (core.workspace pulls in providers
- # which pull in CLI helpers in some edge cases).
- from repowise.core.workspace.config import (
- WORKSPACE_CONFIG_FILENAME,
- WorkspaceConfig,
- )
-
- def _load_ws(root: Path) -> Any | None:
- try:
- return WorkspaceConfig.load(root)
- except Exception:
- return None
-
- # ----- Rule 1: explicit --no-workspace -----
- if no_workspace_flag:
- return CommandTarget(
- mode="single",
- repo_path=base_path,
- reason="forced via --no-workspace",
- auto_detected=False,
- )
-
- # ----- Rule 2: --workspace or --repo -----
- if workspace_flag or repo_alias is not None:
- ws_root = find_workspace_root(base_path)
- if ws_root is None:
- raise WorkspaceNotFound(
- "No .repowise-workspace.yaml found at or above "
- f"{base_path}. Run 'repowise init <workspace-dir>' to "
- "create a workspace, or drop the --workspace flag."
- )
- ws_config = _load_ws(ws_root)
- if ws_config is None:
- raise WorkspaceNotFound(
- f"Found workspace config at {ws_root} but couldn't load it. Is it valid YAML?"
- )
- if repo_alias is not None and ws_config.get_repo(repo_alias) is None:
- available = ", ".join(ws_config.repo_aliases()) or "(none)"
- raise click.UsageError(
- f"Unknown repo alias '{repo_alias}' in workspace. Available: {available}"
- )
- reason = "via --workspace flag" if workspace_flag else f"via --repo {repo_alias}"
- return CommandTarget(
- mode="workspace",
- ws_root=ws_root,
- ws_config=ws_config,
- repo_filter=repo_alias,
- reason=reason,
- auto_detected=False,
- )
-
- # ----- Rule 3: explicit path argument -----
- if explicit_path:
- # Is the path itself a workspace root?
- if (base_path / WORKSPACE_CONFIG_FILENAME).is_file():
- ws_config = _load_ws(base_path)
- if ws_config is not None:
- return CommandTarget(
- mode="workspace",
- ws_root=base_path,
- ws_config=ws_config,
- reason="path argument is a workspace root",
- auto_detected=True,
- )
- # Otherwise treat as single-repo. Surface workspace context if any.
- upstream = find_workspace_root(base_path)
- return CommandTarget(
- mode="single",
- repo_path=base_path,
- ws_root=upstream,
- reason="explicit path argument",
- auto_detected=False,
- )
-
- # ----- Rule 4: no path, no flags -----
- # 4a: cwd is itself a workspace root
- if (base_path / WORKSPACE_CONFIG_FILENAME).is_file():
- ws_config = _load_ws(base_path)
- if ws_config is not None:
- return CommandTarget(
- mode="workspace",
- ws_root=base_path,
- ws_config=ws_config,
- reason="cwd is the workspace root",
- auto_detected=True,
- )
-
- # 4b: cwd is an indexed repo — respect that even if a workspace exists upstream
- cwd_state = get_repowise_dir(base_path) / STATE_FILENAME
- if cwd_state.exists():
- upstream = find_workspace_root(base_path.parent if base_path.parent != base_path else None)
- return CommandTarget(
- mode="single",
- repo_path=base_path,
- ws_root=upstream,
- reason="cwd has its own .repowise/state.json (cd-into-repo wins)",
- auto_detected=upstream is not None,
- )
-
- # 4c: workspace exists upstream of cwd → workspace mode
- upstream = find_workspace_root(base_path)
- if upstream is not None:
- ws_config = _load_ws(upstream)
- if ws_config is not None:
- return CommandTarget(
- mode="workspace",
- ws_root=upstream,
- ws_config=ws_config,
- reason=f"workspace detected upstream at {upstream}",
- auto_detected=True,
- )
-
- # 4d: plain single-repo mode (likely uninitialized).
- return CommandTarget(
- mode="single",
- repo_path=base_path,
- reason="no workspace nearby",
- auto_detected=False,
- )