Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(release): state migration safety + cost-gate UX (#156)
Raghav Chamadiyaa6527cb85116
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.pyindex 41680711c..858374287 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py@@ -33,6 +33,32 @@ from repowise.cli.ui import MaybeCountColumn# ---------------------------------------------------------------------------+class CostGateDeclined(Exception):+ """Raised when the user answers No at the LLM-cost confirmation prompt.++ Carries no payload — the caller just needs to know that generation was+ declined so it can persist state in index-only shape (no docs) and+ return cleanly. Using an exception (vs. a sentinel return value) lets+ us bail out of nested generation flows without rethreading return+ types through every helper.+ """+++def _confirm_cost_gate(message: str) -> bool:+ """Render the cost-gate `[y/N]` prompt with visual padding.++ Click's plain ``confirm`` interleaves with the trailing line of any+ prior Rich output (progress-bar frames, status spinners), making the+ `[y/N]` glyphs hard to spot — users have walked past it and approved+ a $14 bill thinking they were still in cost-estimate territory. A+ blank line + horizontal rule cleanly separates the prompt from+ whatever was printed above it.+ """+ console.line()+ console.rule(style="yellow")+ return click.confirm(message, default=False)++def _offer_hook_install(console_obj: Any,repo_paths: list[Path],@@ -359,10 +385,19 @@ def _run_workspace_generation(if (est.estimated_cost_usd > 2.00and not yes- and not click.confirm(f" Cost for {repo_path.name} exceeds $2.00. Continue?")+ and not _confirm_cost_gate(+ f" Cost for {repo_path.name} exceeds $2.00. Continue?"+ )):- console.print(" [yellow]Skipped.[/yellow]")- return []+ console.print(+ " [yellow]Skipped.[/yellow] "+ "[dim]Index will be saved without docs; "+ "future `repowise update` runs default to index-only.[/dim]"+ )+ # Sentinel — caller treats this exactly like an index-only run so+ # state.docs_enabled lands as False and the post-commit hook+ # doesn't surprise the user with LLM regen later.+ raise CostGateDeclined()# Cost tracker (DB-backed when possible)from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn@@ -627,7 +662,10 @@ def _workspace_init(console.print(f" [red]\u2717 Failed: {exc}[/red]\n")continue- # Generation phase (per-repo, only when not index-only)+ # Generation phase (per-repo, only when not index-only).+ # Track per-repo whether the user declined cost so state.docs_enabled+ # reflects the actual choice instead of the original init mode.+ repo_docs_enabled = not index_only and provider is not Noneif not index_only and provider is not None:if dry_run:console.print(" [yellow]Dry run — skipping generation for this repo.[/yellow]\n")@@ -650,6 +688,9 @@ def _workspace_init(console.print(f" [green]\u2713[/green] Generated {len(generated_pages)} pages\n")+ except CostGateDeclined:+ repo_docs_enabled = False+ result.generated_pages = []except Exception as gen_exc:console.print(f" [yellow]Generation failed: {gen_exc}[/yellow]\n")else:@@ -664,9 +705,9 @@ def _workspace_init(state: dict[str, Any] = {"last_sync_commit": head,"total_pages": pages_count,- "docs_enabled": not index_only and provider is not None,+ "docs_enabled": repo_docs_enabled,}- if not index_only and provider is not None:+ if repo_docs_enabled and provider is not None:state["provider"] = provider.provider_namestate["model"] = provider.model_namesave_state(repo.path, state)@@ -1077,6 +1118,11 @@ def init_command(# ---- Phase 1 & 2: Ingestion + Analysis (always) ----total_phases = 3 if index_only else 4+ # Tracks whether the user declined the LLM cost gate. When True we+ # skip generation but still persist the index/graph/git/dead-code so+ # the run isn't wasted, and propagate the choice to state.docs_enabled+ # so subsequent updates default to index-only.+ cost_declined = Falsellm_client = provider if not index_only else decision_providerfrom repowise.core.pipeline import run_pipeline@@ -1208,123 +1254,132 @@ def init_command(console.print("[yellow]Dry run — no pages generated.[/yellow]")return- if (+ cost_declined = (est.estimated_cost_usd > 2.00and not yes- and not click.confirm(" Estimated cost exceeds $2.00. Continue?")- ):- console.print("[yellow]Aborted.[/yellow]")- return+ and not _confirm_cost_gate(" Estimated cost exceeds $2.00. Continue?")+ )+ if cost_declined:+ console.print(+ "[yellow]Skipped LLM generation.[/yellow] "+ "[dim]Index/graph/git/dead-code will be saved; future "+ "`repowise update` runs default to index-only so the "+ "post-commit hook won't trigger LLM regen.[/dim]"+ )- # Build embedder + vector store- from repowise.core.persistence.vector_store import InMemoryVectorStore- from repowise.core.providers.embedding.base import MockEmbedder+ if not cost_declined:+ # Build embedder + vector store+ from repowise.core.persistence.vector_store import InMemoryVectorStore+ from repowise.core.providers.embedding.base import MockEmbedder- embedder_impl: Any- if embedder_name_resolved == "gemini":- try:- from repowise.core.providers.embedding.gemini import GeminiEmbedder+ embedder_impl: Any+ if embedder_name_resolved == "gemini":+ try:+ from repowise.core.providers.embedding.gemini import GeminiEmbedder- embedder_impl = GeminiEmbedder()- except Exception:+ embedder_impl = GeminiEmbedder()+ except Exception:+ embedder_impl = MockEmbedder()+ elif embedder_name_resolved == "openai":+ try:+ from repowise.core.providers.embedding.openai import OpenAIEmbedder++ embedder_impl = OpenAIEmbedder()+ except Exception:+ embedder_impl = MockEmbedder()+ else:embedder_impl = MockEmbedder()- elif embedder_name_resolved == "openai":++ lance_dir = repo_path / ".repowise" / "lancedb"try:- from repowise.core.providers.embedding.openai import OpenAIEmbedder+ from repowise.core.persistence.vector_store import LanceDBVectorStore- embedder_impl = OpenAIEmbedder()- except Exception:- embedder_impl = MockEmbedder()- else:- embedder_impl = MockEmbedder()+ lance_dir.mkdir(parents=True, exist_ok=True)+ vector_store: Any = LanceDBVectorStore(str(lance_dir), embedder=embedder_impl)+ except ImportError:+ vector_store = InMemoryVectorStore(embedder_impl)- lance_dir = repo_path / ".repowise" / "lancedb"- try:- from repowise.core.persistence.vector_store import LanceDBVectorStore+ # Run generation via the pipeline's generation function+ from repowise.core.pipeline import run_generation- lance_dir.mkdir(parents=True, exist_ok=True)- vector_store: Any = LanceDBVectorStore(str(lance_dir), embedder=embedder_impl)- except ImportError:- vector_store = InMemoryVectorStore(embedder_impl)-- # Run generation via the pipeline's generation function- from repowise.core.pipeline import run_generation-- with Progress(- SpinnerColumn(),- TextColumn("[progress.description]{task.description}"),- BarColumn(),- MaybeCountColumn(),- TimeElapsedColumn(),- TextColumn("[green]${task.fields[cost]:.3f}[/green]"),- console=console,- ) as gen_progress:- gen_callback = RichProgressCallback(gen_progress, console)-- # Construct a CostTracker backed by the real DB so every LLM call- # is persisted to the llm_costs table. We need the repo_id from the- # database row that was created/upserted during _persist_result- # (which has not run yet), so we look it up or fall back to in-memory.- from repowise.core.generation.cost_tracker import CostTracker- from repowise.cli.helpers import get_db_url_for_repo- from repowise.core.persistence import (- create_engine as _create_engine,- create_session_factory as _create_sf,- get_session as _get_session,- init_db as _init_db,- upsert_repository as _upsert_repo,- )+ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ MaybeCountColumn(),+ TimeElapsedColumn(),+ TextColumn("[green]${task.fields[cost]:.3f}[/green]"),+ console=console,+ ) as gen_progress:+ gen_callback = RichProgressCallback(gen_progress, console)++ # Construct a CostTracker backed by the real DB so every LLM call+ # is persisted to the llm_costs table. We need the repo_id from the+ # database row that was created/upserted during _persist_result+ # (which has not run yet), so we look it up or fall back to in-memory.+ from repowise.core.generation.cost_tracker import CostTracker+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ create_engine as _create_engine,+ create_session_factory as _create_sf,+ get_session as _get_session,+ init_db as _init_db,+ upsert_repository as _upsert_repo,+ )- async def _make_cost_tracker() -> CostTracker:- url = get_db_url_for_repo(repo_path)- engine = _create_engine(url)- await _init_db(engine)- sf = _create_sf(engine)- async with _get_session(sf) as _sess:- _repo = await _upsert_repo(- _sess,- name=result.repo_name,- local_path=str(repo_path),- )- _repo_id = _repo.id- # Keep engine alive for the duration of generation — it will be- # disposed by _persist_result's own engine later.- return CostTracker(session_factory=sf, repo_id=_repo_id)+ async def _make_cost_tracker() -> CostTracker:+ url = get_db_url_for_repo(repo_path)+ engine = _create_engine(url)+ await _init_db(engine)+ sf = _create_sf(engine)+ async with _get_session(sf) as _sess:+ _repo = await _upsert_repo(+ _sess,+ name=result.repo_name,+ local_path=str(repo_path),+ )+ _repo_id = _repo.id+ # Keep engine alive for the duration of generation — it will be+ # disposed by _persist_result's own engine later.+ return CostTracker(session_factory=sf, repo_id=_repo_id)- try:- cost_tracker = run_async(_make_cost_tracker())- except Exception:- # Fallback to in-memory tracker if DB setup fails- cost_tracker = CostTracker()-- # Attach tracker to provider unconditionally (all providers now- # accept _cost_tracker as an attribute)- provider._cost_tracker = cost_tracker-- generated_pages = run_async(- run_generation(- repo_path=repo_path,- parsed_files=result.parsed_files,- source_map=result.source_map,- graph_builder=result.graph_builder,- repo_structure=result.repo_structure,- git_meta_map=result.git_meta_map,- llm_client=provider,- embedder=embedder_impl,- vector_store=vector_store,- concurrency=concurrency,- progress=gen_callback,- resume=resume,- cost_tracker=cost_tracker,- generation_config=gen_config,+ try:+ cost_tracker = run_async(_make_cost_tracker())+ except Exception:+ # Fallback to in-memory tracker if DB setup fails+ cost_tracker = CostTracker()++ # Attach tracker to provider unconditionally (all providers now+ # accept _cost_tracker as an attribute)+ provider._cost_tracker = cost_tracker++ generated_pages = run_async(+ run_generation(+ repo_path=repo_path,+ parsed_files=result.parsed_files,+ source_map=result.source_map,+ graph_builder=result.graph_builder,+ repo_structure=result.repo_structure,+ git_meta_map=result.git_meta_map,+ llm_client=provider,+ embedder=embedder_impl,+ vector_store=vector_store,+ concurrency=concurrency,+ progress=gen_callback,+ resume=resume,+ cost_tracker=cost_tracker,+ generation_config=gen_config,+ ))- )- result.generated_pages = generated_pages- console.print(f" [green]✓[/green] Generated [bold]{len(generated_pages)}[/bold] pages")+ result.generated_pages = generated_pages+ console.print(f" [green]✓[/green] Generated [bold]{len(generated_pages)}[/bold] pages")# ---- Persistence ----- if index_only:+ # `cost_declined` short-circuits any further LLM work for the rest of+ # this run, so persistence/state below treat it as index-only.+ effective_index_only = index_only or cost_declined+ if effective_index_only:print_phase_header(console, 3, total_phases, "Persistence", "Saving to database")else:print_phase_header(@@ -1366,12 +1421,12 @@ def init_command(head = get_head_commit(repo_path)base_state = load_state(repo_path)base_state["last_sync_commit"] = head- base_state["docs_enabled"] = not index_only and provider is not None- if index_only or provider is None:+ base_state["docs_enabled"] = not effective_index_only and provider is not None+ if effective_index_only or provider is None:save_state(repo_path, base_state)# ---- State + config (full mode only) ----- if not index_only and provider:+ if not effective_index_only and provider:async def _count_db_pages() -> int:from sqlalchemy import func as sa_func@@ -1466,7 +1521,7 @@ def init_command(else:_lang_summary_final = str(len(result.languages))- if index_only:+ if effective_index_only:metrics: list[tuple[str, str]] = [("Files indexed", str(result.file_count)),("Symbols", f"{result.symbol_count:,}"),diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex f7d878395..5c6ca0754 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -28,6 +28,22 @@ from repowise.cli.helpers import (# ---------------------------------------------------------------------------+def _infer_legacy_docs_enabled(state: dict) -> bool:+ """Infer ``docs_enabled`` for state files written before the field existed.++ Pre-migration ``init`` only wrote ``provider`` / ``model`` to state when+ docs were generated; index-only init wrote nothing past ``last_sync_commit``.+ So absence of both fields is a reliable signal that the original run was+ index-only and we should default new updates to index-only too — this+ avoids surprising those users with a full LLM regen on first upgrade.+ Full-init users keep the old default (full mode) because their state+ has ``provider`` and ``model`` populated.+ """+ if state.get("provider") or state.get("model"):+ return True+ return False++def _resolve_index_only_mode(*,index_only: bool,@@ -37,18 +53,21 @@ def _resolve_index_only_mode("""Decide whether this update should skip LLM regeneration.Priority: explicit ``--index-only`` flag > ``--docs/--no-docs`` >- ``state.docs_enabled`` (default: True for backward compatibility with- state files written before the field existed). Encapsulated as a pure- function so the post-commit hook does the right thing without needing- any extra knobs at install time.+ ``state.docs_enabled`` > inferred default from legacy state shape.+ Encapsulated as a pure function so the post-commit hook does the right+ thing without needing any extra knobs at install time."""if index_only:return Trueif docs_flag is False:return True- if docs_flag is None and state.get("docs_enabled", True) is False:- return True- return False+ if docs_flag is True:+ return False+ # No explicit override — read state, falling back to a shape-based+ # inference for state files predating the docs_enabled field.+ if "docs_enabled" in state:+ return state["docs_enabled"] is False+ return _infer_legacy_docs_enabled(state) is False# ---------------------------------------------------------------------------@@ -238,6 +257,22 @@ def update_command(console.print("[green]Already up to date.[/green]")return+ # Backfill docs_enabled on legacy state files using the same+ # shape-based inference the resolver uses, so the post-commit hook+ # and future runs stop relying on the inference. Done before mode+ # resolution and only when no explicit override was passed, so a+ # one-off `--docs` / `--no-docs` doesn't lock anything in.+ explicit_override = (+ # The CLI default of index_only is False; treat it like an+ # override only when the user actually passed the flag, which we+ # can't distinguish here — but the conservative choice is fine:+ # index_only=True is always treated as an override.+ index_only or docs_flag is not None+ )+ if "docs_enabled" not in state and not explicit_override:+ state["docs_enabled"] = _infer_legacy_docs_enabled(state)+ save_state(repo_path, state)+# --- Resolve effective mode (index-only vs full LLM regen) ---index_only = _resolve_index_only_mode(index_only=index_only, docs_flag=docs_flag, state=statediff --git a/tests/unit/cli/test_update_mode_resolution.py b/tests/unit/cli/test_update_mode_resolution.pyindex bfc3f7899..481960c5c 100644--- a/tests/unit/cli/test_update_mode_resolution.py+++ b/tests/unit/cli/test_update_mode_resolution.py@@ -13,7 +13,10 @@ to know how the user originally indexed the repo.from __future__ import annotations-from repowise.cli.commands.update_cmd import _resolve_index_only_mode as _resolve_mode+from repowise.cli.commands.update_cmd import (+ _infer_legacy_docs_enabled,+ _resolve_index_only_mode as _resolve_mode,+)class TestModeResolution:@@ -44,9 +47,36 @@ class TestModeResolution:index_only=False, docs_flag=None, state={"docs_enabled": True}) is False- def test_missing_field_defaults_to_full(self):- # Backward compat: state files written before docs_enabled existed- # must continue to behave as full-mode (the original behavior).+ def test_missing_field_with_provider_defaults_to_full(self):+ # Pre-migration full init wrote provider/model into state. Those+ # users keep the full-mode default after upgrading — no surprise+ # change in behavior.assert _resolve_mode(- index_only=False, docs_flag=None, state={}+ index_only=False,+ docs_flag=None,+ state={"provider": "openai", "model": "gpt-5.4-mini"},) is False++ def test_missing_field_no_provider_defaults_to_index_only(self):+ # Pre-migration `init --index-only` skipped writing provider/model,+ # so absence of both signals "this was an index-only init" — and+ # we default future updates to index-only too. Critical for not+ # surprising those users with an LLM bill on first upgrade.+ assert _resolve_mode(+ index_only=False, docs_flag=None, state={"last_sync_commit": "abc"}+ ) is True+++class TestLegacyDocsEnabledInference:+ def test_provider_present_means_docs_were_enabled(self):+ assert _infer_legacy_docs_enabled({"provider": "openai"}) is True++ def test_model_present_means_docs_were_enabled(self):+ # Older code paths wrote model without provider in some flows.+ assert _infer_legacy_docs_enabled({"model": "gpt-5.4-mini"}) is True++ def test_neither_means_index_only(self):+ assert _infer_legacy_docs_enabled({"last_sync_commit": "x"}) is False++ def test_empty_state_means_index_only(self):+ assert _infer_legacy_docs_enabled({}) is False