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(init): degrade unanswerable prompts instead of ending the run (#1002)
Raghav Chamadiyab27dbf558772
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.pyindex 0f20bbc95..519845a37 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py@@ -68,7 +68,15 @@ def offer_distill_rewrite_hook(f" [dim]{scope}Each rewrite is shown for approval; raw output stays ""recoverable via `repowise expand`.[/dim]")- flag = click.confirm(" Install the Claude Code rewrite hook?", default=True)+ try:+ flag = click.confirm(" Install the Claude Code rewrite hook?", default=True)+ except (click.Abort, EOFError):+ # Same unanswerable-terminal case as the post-commit hook offer+ # above: decline an optional extra rather than fail a finished run.+ console_obj.print(+ "\n [dim]Skipped. Run 'repowise hook rewrite install' later to set up.[/dim]"+ )+ returnif flag:path = adapter.install_rewrite_hook()@@ -108,6 +116,25 @@ def offer_hook_install(if not sys.stdin.isatty():return # Non-interactive — skip+ try:+ _offer_hook_install_prompts(console_obj, repo_paths, aliases)+ except (click.Abort, EOFError):+ # isatty() claimed a terminal that cannot answer (Windows Git Bash+ # ``< /dev/null``, pty wrappers, ``docker run -t`` without -i). This is+ # the last step of a run whose index and wiki are already written, and+ # an optional hook is not worth failing it over: decline and exit+ # clean. Ctrl-C lands here too, which asks for the same outcome.+ console_obj.print(+ "\n [dim]Skipped the hook. Run 'repowise hook install' later to set it up.[/dim]"+ )+++def _offer_hook_install_prompts(+ console_obj: Any,+ repo_paths: list[Path],+ aliases: list[str] | None,+) -> None:+ """Ask which repos get a post-commit hook, and install it. Prompts."""from repowise.cli.hooks import install, status# Filter to repos that don't already have the hookdiff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex 93efcd8f9..3f9e6a7e2 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -333,12 +333,11 @@ def _run_generation_phase(console.print("[yellow]Dry run — no pages generated.[/yellow]")return True, False- if cost_gate_declined(est, yes=yes, message=" Estimated cost exceeds $2.00. Continue?"):+ if cost_gate_declined(est, yes=yes, message=" Write the wiki with the model at this cost?"):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]"+ "[yellow]Not writing it with the model.[/yellow] "+ "[dim]Future `repowise update` runs stay index-only, so the "+ "post-commit hook won't start a model run on its own.[/dim]")return False, True@@ -826,7 +825,26 @@ def init_command(with console.status(" Scanning repository…", spinner=OWL_SPINNER):scan_info = quick_repo_scan(repo_path)print_scan_summary(console, scan_info)- mode = interactive_mode_select(console)++ # ``sys.stdin.isatty()`` is not a reliable answer to "can I read from+ # stdin". On Windows under Git Bash, ``repowise init < /dev/null``+ # reports a TTY and then reads EOF on the first question; the same goes+ # for some pty wrappers and ``docker run -t`` without -i. Agents drive+ # init through exactly those shapes, so the first prompt is treated as+ # the probe: if it cannot be answered, drop to the non-interactive path+ # and carry on rather than dying on a question nobody can hear. Only+ # EOFError is caught. A real Ctrl-C raises KeyboardInterrupt/Abort and+ # must still stop the run.+ mode = None+ try:+ mode = interactive_mode_select(console)+ except EOFError:+ is_interactive = False+ console.print(+ "\n[yellow]No answer available on stdin[/yellow] "+ "[dim]— continuing with defaults. Pass --yes to skip the "+ "questions.[/dim]"+ )# Map the menu onto the two axes (docs on/off, customize yes/no):# full -> docs on, optional customize@@ -838,14 +856,17 @@ def init_command(elif mode == "advanced":generate_docs = interactive_generate_docs_toggle(console)customize = True- else: # full+ elif mode is not None: # fullgenerate_docs = Truecustomize = interactive_customize_offer(console, generate_docs=True)- index_only = not generate_docs+ if mode is not None:+ index_only = not generate_docs# Provider selection only when docs will be generated. Index-only runs# auto-detect a decision-extraction provider later without prompting.- if generate_docs:+ # ``is_interactive`` can have been cleared just above by an unanswerable+ # menu, in which case every remaining question here is unanswerable too.+ if generate_docs and is_interactive:selection = interactive_provider_config_select(console,model,@@ -897,7 +918,7 @@ def init_command(if run_mode == "fast":index_only = Truegenerate_docs = False- else:+ elif is_interactive:# No customization: still offer the fast first-index on large repos.# Default yes for an index-only run (docs already opted out), no for a# full run (the user explicitly asked for docs).@@ -913,7 +934,7 @@ def init_command(# Wiki style: prompt for a docs run when not already chosen (via the# --wiki-style flag or the advanced generation section). Index-only runs# generate no pages, so the question is skipped. --yes uses the default.- if generate_docs and wiki_style is None and not yes:+ if generate_docs and wiki_style is None and not yes and is_interactive:wiki_style = prompt_wiki_style(console)# Resolve the effective style (CLI flag > interactive prompt > default) anddiff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex 97ebfcc53..9b0537d37 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -488,9 +488,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtexclude_patterns=ctx.exclude_patterns if ctx.exclude_patterns else None,commit_limit=ctx.resolved_commit_limit if ctx.resolved_commit_limit else None,embedder=det_embedder,- embedding_model=(- resolve_embedding_model(det_embedder) if det_embedder else None- ),+ embedding_model=(resolve_embedding_model(det_embedder) if det_embedder else None),)return _RepoOutcome(@@ -566,8 +564,13 @@ def _workspace_init(console.print(f" Detected [bold]{len(scan.repos)}[/bold] repositories in {root}\n")# Step 1: Select repos to index- # --yes or --all: take every detected repo without prompting.- select_all = init_all or yes+ # --yes or --all: take every detected repo without prompting. So does a+ # non-terminal stdin: this is the first prompt in the workspace flow, it+ # runs before any indexing, and asking a pipe would end the run with an+ # EOFError before the tool had done anything at all. Agents drive init+ # this way routinely. "Every repo the scan found" is also what --all+ # means, so the fallback matches the flag a human would have passed.+ select_all = init_all or yes or not sys.stdin.isatty()selected = list(scan.repos) if select_all else interactive_repo_select(console, scan.repos)if not selected:diff --git a/packages/cli/src/repowise/cli/cost_gate.py b/packages/cli/src/repowise/cli/cost_gate.pyindex 578788d62..de0db226f 100644--- a/packages/cli/src/repowise/cli/cost_gate.py+++ b/packages/cli/src/repowise/cli/cost_gate.py@@ -9,6 +9,7 @@ the other's internals.from __future__ import annotations+import sysfrom typing import Anyimport click@@ -19,6 +20,12 @@ from repowise.cli.helpers import console# for confirmation (unless ``--yes``); below it generation proceeds silently.COST_GATE_USD = 2.00+# The point where Enter-through stops meaning yes. Between COST_GATE_USD and+# this, the gate is an FYI on a run the user just configured and the default+# continues it. Past it, a mis-keyed Enter is an expensive mistake, so the+# default flips and approval has to be typed.+COST_GATE_HARD_USD = 25.00+class CostGateDeclined(Exception): # noqa: N818 — a control-flow signal, not an error"""Raised when the user answers No at the LLM-cost confirmation prompt.@@ -31,8 +38,8 @@ class CostGateDeclined(Exception): # noqa: N818 — a control-flow signal, not"""-def confirm_cost_gate(message: str) -> bool:- """Render the cost-gate ``[Y/n]`` prompt with visual padding.+def confirm_cost_gate(message: str, *, estimated_usd: float | None = None) -> bool:+ """Render the cost-gate prompt with visual padding. True means "spend it".Click's plain ``confirm`` interleaves with the trailing line of anyprior Rich output (progress-bar frames, status spinners), making the@@ -44,11 +51,37 @@ def confirm_cost_gate(message: str) -> bool:Default is Yes: the user just picked a coverage tier with the costrange printed next to it, so Enter-through should continue the runthey configured — the gate exists to make the spend visible, not to- interrupt it.+ interrupt it. Above :data:`COST_GATE_HARD_USD` that reverses, because+ Enter-through approving a bill that size is the footgun the padding+ above was added to prevent, and a default cannot be the safe answer+ and the expensive one at the same time.++ Declining is not a dead end and the prompt now says so: the caller+ renders the wiki from templates instead, so No costs the user their+ model pages, not their wiki.++ Never prompts when stdin is not a terminal. There is nothing to read+ there, and ``click.confirm`` would raise ``Abort`` and throw away an+ index that is already built — which is the whole run, minutes of it."""console.line()console.rule(style="yellow")- return click.confirm(message, default=True)+ console.print(+ " [dim]No builds the same wiki from structure instead: no model, "+ "no spend. You can upgrade it later with [bold]repowise update "+ "--full[/bold].[/dim]"+ )+ if not sys.stdin.isatty():+ console.print(" [dim]Not a terminal, so nothing to ask: building from structure.[/dim]")+ return False+ default = True+ if estimated_usd is not None and estimated_usd > COST_GATE_HARD_USD:+ console.print(+ f" [yellow]This is over ${COST_GATE_HARD_USD:.0f}.[/yellow] "+ "[dim]Answer yes explicitly to approve it.[/dim]"+ )+ default = False+ return click.confirm(message, default=default)def cost_gate_declined(est: Any, *, yes: bool, message: str) -> bool:@@ -57,7 +90,9 @@ def cost_gate_declined(est: Any, *, yes: bool, message: str) -> bool:Only prompts when the estimate clears :data:`COST_GATE_USD` and ``--yes``was not passed; a declined prompt yields ``True``."""- return est.estimated_cost_usd > COST_GATE_USD and not yes and not confirm_cost_gate(message)+ if est.estimated_cost_usd <= COST_GATE_USD or yes:+ return False+ return not confirm_cost_gate(message, estimated_usd=est.estimated_cost_usd)def format_cost(est: Any) -> str:diff --git a/tests/unit/cli/test_init_noninteractive.py b/tests/unit/cli/test_init_noninteractive.pynew file mode 100644index 000000000..961ff56aa--- /dev/null+++ b/tests/unit/cli/test_init_noninteractive.py@@ -0,0 +1,95 @@+"""Prompts in `repowise init` that must degrade rather than end the run.++Agents set repowise up on a user's behalf, usually as `repowise init --yes` or+with stdin pointed at /dev/null. `sys.stdin.isatty()` is not a reliable guard:+on Windows under Git Bash, `init < /dev/null` reports a terminal and then reads+EOF on the first question.+"""++from __future__ import annotations++import sys+from types import SimpleNamespace++import click++from repowise.cli import cost_gate+from repowise.cli.commands.init_cmd._interactive import offer_hook_install+++def _est(usd: float) -> SimpleNamespace:+ """A stand-in for a cost estimate, which the gate only reads two fields of."""+ return SimpleNamespace(estimated_cost_usd=usd, cost_range=None, is_calibrated=False)+++class TestCostGate:+ def test_below_threshold_never_prompts(self, monkeypatch):+ """A cheap run is not worth interrupting, so the gate stays out of the way."""++ def _boom(*_a, **_k):+ raise AssertionError("prompted below the cost gate threshold")++ monkeypatch.setattr(click, "confirm", _boom)+ assert cost_gate.cost_gate_declined(_est(0.10), yes=False, message="m") is False++ def test_yes_never_prompts(self, monkeypatch):+ """--yes means the spend is pre-approved."""++ def _boom(*_a, **_k):+ raise AssertionError("prompted under --yes")++ monkeypatch.setattr(click, "confirm", _boom)+ assert cost_gate.cost_gate_declined(_est(999.0), yes=True, message="m") is False++ def test_non_tty_declines_without_prompting(self, monkeypatch):+ """No terminal means no answer. Decline, do not Abort.++ The gate is the only prompt that fires *after* a full index, so an+ Abort here throws away every minute already spent. Declining hands the+ caller back to the template renderer with the index intact.+ """+ monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False)++ def _boom(*_a, **_k):+ raise AssertionError("prompted with no terminal attached")++ monkeypatch.setattr(click, "confirm", _boom)+ assert cost_gate.cost_gate_declined(_est(50.0), yes=False, message="m") is True++ def test_default_is_yes_under_the_hard_ceiling(self, monkeypatch):+ """The user just configured this run; Enter-through continues it."""+ seen: dict = {}+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False)+ monkeypatch.setattr(+ click, "confirm", lambda _m, default=None: seen.setdefault("default", default) or True+ )+ cost_gate.confirm_cost_gate("m", estimated_usd=5.0)+ assert seen["default"] is True++ def test_default_flips_above_the_hard_ceiling(self, monkeypatch):+ """A bill this size must be typed, not defaulted into."""+ seen: dict = {}+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False)++ def _confirm(_m, default=None):+ seen["default"] = default+ return False++ monkeypatch.setattr(click, "confirm", _confirm)+ cost_gate.confirm_cost_gate("m", estimated_usd=cost_gate.COST_GATE_HARD_USD + 1)+ assert seen["default"] is False+++class TestHookOfferDegrades:+ def test_eof_on_hook_offer_does_not_raise(self, monkeypatch, tmp_path):+ """A finished run must not fail on an optional trailing question."""+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False)+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd._interactive.click.confirm",+ lambda *_a, **_k: (_ for _ in ()).throw(click.Abort()),+ )+ monkeypatch.setattr("repowise.cli.hooks.status", lambda _p: "missing")+ # Must not raise.+ offer_hook_install(+ SimpleNamespace(print=lambda *_a, **_k: None), [tmp_path], None, yes=False+ )