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.

fix(init): exit 2 when a run finishes with gaps and 130 when interrupted (#4242)

Raghav Chamadiya8cecdcf94979
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 45f385961..c9d5f8d05 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -216,13 +216,20 @@ repowise init . --no-prose -x "node_modules/" # workspace, no LLM
repowise init . --no-workspace # force single-repo, even in a workspace root
```
-**Exit status when embedding fails.** With a real embedder (anything but
-`mock`), a run whose page vectors fail to write, for example because the
-LanceDB install is broken, still saves its pages and full-text index but
-exits `1`, records `search.semantic: unavailable` in the index scope, and names
-the fix: reinstall the dependency, then `repowise reindex`. `update` follows the
-same rule, and a workspace `init` exits `1` after saving every repo, naming the
-repos whose embed failed. The keyless `mock` embedder never fails a run this way.
+**Exit codes.** `0` ready. `2` finished with gaps: everything is saved, and the
+last line names what is missing and the command that adds it (for example
+documentation built from code because the cost estimate needed confirmation and
+there was no terminal, so re-run with `--yes`). `130` interrupted: run
+`repowise init --resume` to continue. Any other non-zero code is a failure; a
+usage error (a bad flag) also exits `2`, before anything runs.
+
+With a real embedder (anything but `mock`), a run whose page vectors fail to
+write, for example because the LanceDB install is broken, keeps its pages and
+full-text index, records `search.semantic: unavailable` in the index scope, and
+exits `2` naming the fix: reinstall the dependency, then `repowise reindex`. A
+workspace `init` exits `2` after saving every repo, naming the repos with gaps.
+`update` exits `1` on a failed embed. The keyless `mock` embedder never fails a
+run this way.
**Documentation output limit.** Set `max_tokens` in
`.repowise/config.yaml` to bound each model-written page. It is persistent, not
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_exit.py b/packages/cli/src/repowise/cli/commands/init_cmd/_exit.py
new file mode 100644
index 000000000..b74a88344
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_exit.py
@@ -0,0 +1,52 @@
+"""How ``repowise init`` ends: ready, finished with gaps, or interrupted."""
+
+from __future__ import annotations
+
+from typing import NoReturn
+
+from repowise.cli.exit_codes import EXIT_DEGRADED, EXIT_INTERRUPTED
+from repowise.cli.helpers import console
+from repowise.cli.ui import WARN
+
+_NO_TERMINAL = (
+ "because the estimate needed confirmation and there was no terminal. "
+ "Re-run with --yes to accept the cost"
+)
+#: The cost gate could not ask, so the model did not run.
+COST_UNCONFIRMED_BUILT = f"documentation built from code, {_NO_TERMINAL}"
+COST_UNCONFIRMED_KEPT = f"documentation kept as it was, {_NO_TERMINAL}"
+
+
+def exit_interrupted() -> NoReturn:
+ """Ctrl-C at any point: one line, then the shell's interrupt code."""
+ from repowise.cli.hints import maybe_hint
+ from repowise.cli.ui.mascot import EYES_SLEEPY, mini
+
+ console.print(
+ f"\n{mini(EYES_SLEEPY)} [{WARN}]Interrupted.[/] "
+ "Run [bold]repowise init --resume[/] to continue."
+ )
+ maybe_hint("interrupt")
+ raise SystemExit(EXIT_INTERRUPTED)
+
+
+def exit_on_gaps(gaps: list[str]) -> None:
+ """Exit degraded when any gap is left; everything is already saved."""
+ if not gaps:
+ return
+ console.print(f"[{WARN}]Finished with gaps:[/] {'; '.join(gaps)}.", highlight=False)
+ raise SystemExit(EXIT_DEGRADED)
+
+
+def run_gaps(
+ *,
+ failed_pages: int,
+ embed_error: str | None,
+) -> list[str]:
+ """What a finished run was asked for and did not get, one phrase each."""
+ gaps = []
+ if failed_pages:
+ gaps.append(f"{failed_pages:,} page(s) failed to generate")
+ if embed_error:
+ gaps.append(embed_error.rstrip("."))
+ return gaps
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
index f904ba1bd..3ab40aafe 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
@@ -6,7 +6,6 @@ import sys
from pathlib import Path
from typing import Any
-import click
from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
from repowise.cli.commands._index_outcome import record_index_outcome, refresh_read_snapshots
@@ -431,12 +430,19 @@ def complete_setup(run: InitRun) -> None:
)
-def raise_on_embed_failure(run: InitRun) -> None:
- """Exit non-zero when embedding failed; raised last so everything else is kept."""
+def exit_with_gaps(run: InitRun) -> None:
+ """Exit degraded when the run left a gap; last, so everything else is kept."""
from repowise.cli.providers import embed_failure_message
- embed_error = embed_failure_message(
- run.scope_embedder, getattr(run.result, "embed_failed_pages", 0)
+ from ._exit import exit_on_gaps, run_gaps
+
+ result = run.result
+ exit_on_gaps(
+ run.gaps
+ + run_gaps(
+ failed_pages=len(getattr(result, "failed_page_ids", None) or []),
+ embed_error=embed_failure_message(
+ run.scope_embedder, getattr(result, "embed_failed_pages", 0)
+ ),
+ )
)
- if embed_error:
- raise click.ClickException(embed_error)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py b/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py
index d346bcfde..cc8d6fe47 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import sys
from pathlib import Path
from typing import Any
@@ -11,6 +12,7 @@ from repowise.cli.helpers import console, load_config, warn
from repowise.cli.ui import BRAND, VALUE, print_phase_header
from repowise.core.generation.styles import DEFAULT_STYLE
+from ._exit import COST_UNCONFIRMED_BUILT, COST_UNCONFIRMED_KEPT
from ._options import InitRun
from .generation import (
concept_page_count,
@@ -364,22 +366,31 @@ def _generate_with_model(run: InitRun) -> bool:
)
if gen_stop:
return True
- if cost_declined and run.prior_docs_mode == "llm":
+ if cost_declined:
+ _after_cost_declined(run)
+ return False
+
+
+def _after_cost_declined(run: InitRun) -> None:
+ """Keep model-written pages, or build from code; a gap when nobody could say no."""
+ kept = run.prior_docs_mode == "llm"
+ if not sys.stdin.isatty():
+ run.gaps.append(COST_UNCONFIRMED_KEPT if kept else COST_UNCONFIRMED_BUILT)
+ if kept:
# Declining new pages is no request to replace the written ones.
console.print(
" [dim]Keeping the wiki this repo already has. Nothing was "
"generated and nothing was replaced.[/dim]"
)
- elif cost_declined:
- run.cost_declined = True
- console.print(
- " [dim]Building the wiki from structure instead. Run "
- "[bold]repowise update --full[/bold] to write it with a "
- "model later.[/dim]"
- )
- # Declining the bill keeps the configured embedder.
- _render_template_wiki(run, embedder_was_requested=True)
- return False
+ return
+ run.cost_declined = True
+ console.print(
+ " [dim]Building the wiki from structure instead. Run "
+ "[bold]repowise update --full[/bold] to write it with a "
+ "model later.[/dim]"
+ )
+ # Declining the bill keeps the configured embedder.
+ _render_template_wiki(run, embedder_was_requested=True)
def _generate(run: InitRun) -> bool:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py b/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py
index c1fd2c2c7..770e86c81 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py
@@ -12,7 +12,6 @@ from repowise.cli.ui import (
BRAND_STYLE,
OK,
OWL_SPINNER,
- WARN,
MaybeCountColumn,
RichProgressCallback,
)
@@ -120,8 +119,8 @@ async def _index_with_resume(
await engine.dispose()
-def index_repository(run: InitRun) -> bool:
- """Phases 1 and 2, without docs (generation follows the cost gate). False if interrupted."""
+def index_repository(run: InitRun) -> None:
+ """Phases 1 and 2, without docs (generation follows the cost gate). Exits 130 if interrupted."""
opts = run.opts
# Fast mode skips generation, so it has three phases.
run.total_phases = 3 if opts.run_mode == "fast" else 4
@@ -165,18 +164,10 @@ def index_repository(run: InitRun) -> bool:
)
)
except (PipelineCancelled, KeyboardInterrupt):
- from repowise.cli.ui.mascot import EYES_SLEEPY, mini
+ from ._exit import exit_interrupted
- console.print(
- f"\n{mini(EYES_SLEEPY)} [{WARN}]Interrupted.[/] Indexed work so far has been "
- "saved — run [bold]repowise init --resume[/] to continue where it stopped."
- )
- from repowise.cli.hints import maybe_hint
-
- maybe_hint("interrupt")
- return False
+ exit_interrupted()
run.result = result
run.recorder = callback
run.run_warnings = list(rich_callback.warnings)
- return True
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
index c7b686d0e..473f68698 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
@@ -102,6 +102,8 @@ class InitRun:
# Embedder of the template wiki, None when none was rendered.
index_only_embedder: str | None = None
cost_declined: bool = False
+ # Asked-for work a stage could not do; any entry makes init exit degraded.
+ gaps: list[str] = field(default_factory=list)
effective_index_only: bool = False
phase_timings: dict[str, float] = field(default_factory=dict)
scope_embedder: str | None = None
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py b/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
index daf353546..f5e6aec7d 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
@@ -191,7 +191,7 @@ def _confirm_wiki_overwrite(run: InitRun) -> bool:
if not sys.stdin.isatty():
raise reasoned_error(
"Refusing to replace a model-written wiki with template pages. "
- "Re-run with --yes to confirm, or drop --index-only.",
+ "Re-run with --yes to confirm, or drop --no-prose.",
reason="wiki_overwrite_unconfirmed",
)
if not click.confirm(" Replace the written wiki with template pages?", default=False):
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index ee2ad669a..c9efa522e 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -17,6 +17,7 @@ from typing import Any
import click
from repowise.cli.errors import reasoned_error
+from repowise.cli.exit_codes import EXIT_CODES_HELP
from repowise.cli.helpers import resolve_repo_path
from repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS
from repowise.core.generation.languages import SUPPORTED_LANGUAGES
@@ -24,11 +25,12 @@ from repowise.core.generation.styles import list_styles, resolve_style
from repowise.core.reasoning import REASONING_MODES
from repowise.core.update_lock import init_in_progress
+from ._exit import exit_interrupted
from ._finish import (
catch_up_savings,
complete_setup,
+ exit_with_gaps,
persist_index,
- raise_on_embed_failure,
register_clients,
save_run_config,
write_run_state,
@@ -125,7 +127,7 @@ def _run_workspace_init(opts: InitOptions, scan: Any) -> None:
)
[email protected]("init", epilog=EXIT_CODES_HELP)
@click.argument("path", required=False, default=None)
@click.option(
"--provider",
@@ -459,7 +461,16 @@ def init_command(**params: Any) -> None:
structural either way.
Use --mode fast for a quick graph + essential-git index of a very large repo.
"""
- opts = resolve_structural_flags(InitOptions(**params))
+ from repowise.core.cancellation import PipelineCancelled
+
+ try:
+ _run_init(resolve_structural_flags(InitOptions(**params)))
+ except (PipelineCancelled, KeyboardInterrupt):
+ exit_interrupted()
+
+
+def _run_init(opts: InitOptions) -> None:
+ """The whole init, one repo or a workspace; exits 2 when it finishes with gaps."""
start = time.monotonic()
repo_path = resolve_repo_path(opts.path)
@@ -491,8 +502,12 @@ def init_command(**params: Any) -> None:
def _run_single_repo(opts: InitOptions, repo_path: Any, start: float) -> None:
run = _prepare_single_repo(opts, repo_path, start)
- if run is None or not index_repository(run):
+ if run is None:
return
+ index_repository(run)
+ # Each one is an analysis step the pipeline skipped on an error.
+ if run.run_warnings:
+ run.gaps.append(f"{len(run.run_warnings):,} warning(s) while indexing (see above)")
show_analysis_summary(run.result)
if _generate(run):
@@ -506,4 +521,4 @@ def _run_single_repo(opts: InitOptions, repo_path: Any, start: float) -> None:
register_clients(run)
write_run_state(run)
complete_setup(run)
- raise_on_embed_failure(run)
+ exit_with_gaps(run)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index 9799ebc35..cffe30e35 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -68,6 +68,7 @@ from repowise.cli.ui import (
from repowise.core.docs_mode import docs_mode_state_fields
from repowise.core.generation.styles import DEFAULT_STYLE
+from ._exit import COST_UNCONFIRMED_BUILT, exit_on_gaps
from ._ingest import structural_generation_config
from ._interactive import offer_distill_rewrite_hook, offer_hook_install
from .generation import (
@@ -293,6 +294,8 @@ class _WorkspaceCtx:
#: Same reasoning for key persistence: each workspace repo gets its own
#: .repowise/, so each needs its own credential to be MCP-answerable.
save_key: bool = True
+ #: Asked-for work a repo did not get; any entry makes init exit degraded.
+ gaps: list[str] = field(default_factory=list)
@dataclass
@@ -508,6 +511,8 @@ def _generate_repo_with_model(
except CostGateDeclined:
# Declining only meant "not at that price": fall back to the free
# template renderer rather than leave the repo with no wiki.
+ if not sys.stdin.isatty():
+ ctx.gaps.append(f"{repo.alias}: {COST_UNCONFIRMED_BUILT}")
console.print(
" [dim]Building this repo's wiki from structure instead. Run "
"[bold]repowise update --repo "
@@ -517,6 +522,7 @@ def _generate_repo_with_model(
except Exception as gen_exc:
console.print(f" [{ERR}]✗ Generation failed: {gen_exc}[/]\n")
docs.skip_reason = f"generation error: {gen_exc}"
+ ctx.gaps.append(f"{repo.alias}: documentation not written ({gen_exc})")
result.generated_pages = []
@@ -915,7 +921,7 @@ def _workspace_init(
editor_setup=editor_setup,
)
console.print()
- _raise_on_embed_failures(totals.embed_failures)
+ exit_on_gaps(_workspace_gaps(ctx, totals))
def _select_workspace_repos(scan: Any, *, select_all: bool) -> tuple[list[Any], str, Any] | None:
@@ -1163,17 +1169,17 @@ def _offer_workspace_hooks(
)
-def _raise_on_embed_failures(embed_failures: dict[str, int]) -> None:
- """Fail a scripted run whose semantic indexes were not built.
-
- Raised after every repo is persisted, as single-repo init does.
- """
- if embed_failures:
- import click
-
- listed = ", ".join(f"{alias} ({n} page(s))" for alias, n in embed_failures.items())
- raise click.ClickException(
+def _workspace_gaps(ctx: _WorkspaceCtx, totals: _WorkspaceTotals) -> list[str]:
+ """Every repo's gaps, raised after each one is persisted, as single-repo init does."""
+ gaps = list(ctx.gaps)
+ if totals.errors:
+ failed = ", ".join(alias for alias, _ in totals.errors)
+ gaps.append(f"{len(totals.errors):,} repo(s) failed to index ({failed})")
+ if totals.embed_failures:
+ listed = ", ".join(f"{alias} ({n:,} page(s))" for alias, n in totals.embed_failures.items())
+ gaps.append(
f"Embedding failed for {listed}, so semantic search is unavailable there "
"(full-text search still works). Fix the cause in the warnings above, "
- "then run: repowise reindex in each."
+ "then run: repowise reindex in each"
)
+ return gaps
diff --git a/packages/cli/src/repowise/cli/exit_codes.py b/packages/cli/src/repowise/cli/exit_codes.py
new file mode 100644
index 000000000..3454bec89
--- /dev/null
+++ b/packages/cli/src/repowise/cli/exit_codes.py
@@ -0,0 +1,15 @@
+"""Exit codes a script or agent can branch on.
+
+0 is ready. Any code not named here is a failure: nothing usable was produced.
+"""
+
+from __future__ import annotations
+
+#: Finished and usable, but something the run was asked for did not complete.
+EXIT_DEGRADED = 2
+#: Stopped by Ctrl-C; the shell convention for SIGINT (128 + 2).
+EXIT_INTERRUPTED = 130
+
+EXIT_CODES_HELP = (
+ "Exit codes: 0 ready, 2 finished with gaps (named on the last line), 130 interrupted."
+)
diff --git a/tests/unit/cli/test_embed_failure_reporting.py b/tests/unit/cli/test_embed_failure_reporting.py
index 39942468a..be7812cbc 100644
--- a/tests/unit/cli/test_embed_failure_reporting.py
+++ b/tests/unit/cli/test_embed_failure_reporting.py
@@ -217,7 +217,7 @@ def _broken_store(monkeypatch):
monkeypatch.setattr(LanceDBVectorStore, "embed_batch", _boom)
-def test_init_with_a_real_embedder_exits_nonzero_when_embedding_fails(tmp_path, monkeypatch):
+def test_init_with_a_real_embedder_exits_degraded_when_embedding_fails(tmp_path, monkeypatch):
from repowise.cli.main import cli
monkeypatch.setenv("OLLAMA_BASE_URL", "http://127.0.0.1:9")
@@ -230,7 +230,7 @@ def test_init_with_a_real_embedder_exits_nonzero_when_embedding_fails(tmp_path,
cli, ["init", str(tmp_path), "--index-only", "--embedder", "ollama", "--yes"]
)
- assert result.exit_code == 1, result.output
+ assert result.exit_code == 2, result.output
assert "Embedding failed for" in result.output
assert "repowise reindex" in result.output
state = json.loads((tmp_path / ".repowise" / "state.json").read_text(encoding="utf-8"))
@@ -381,7 +381,7 @@ def test_reindex_clears_the_unavailable_stamp(tmp_path, monkeypatch):
assert state["index_scope"]["search"]["next_command"] is None
-def test_workspace_init_persists_every_repo_then_exits_nonzero(tmp_path, monkeypatch):
+def test_workspace_init_persists_every_repo_then_exits_degraded(tmp_path, monkeypatch):
import git as gitpython
from repowise.cli.main import cli
@@ -403,7 +403,7 @@ def test_workspace_init_persists_every_repo_then_exits_nonzero(tmp_path, monkeyp
["init", str(tmp_path), "--index-only", "--embedder", "ollama", "--yes", "--all"],
)
- assert result.exit_code == 1, result.output
+ assert result.exit_code == 2, result.output
assert "Embedding failed for" in " ".join(result.output.split())
for name in ("api", "web"):
state = json.loads((tmp_path / name / ".repowise" / "state.json").read_text("utf-8"))
@@ -414,7 +414,7 @@ def test_workspace_init_persists_every_repo_then_exits_nonzero(tmp_path, monkeyp
def _indexed_repo_with_broken_store(tmp_path, monkeypatch) -> Path:
"""An index-only repo pinned to a real embedder, with a store that fails.
- Init itself exits 1 here (its embed fails too); the stamp is reset to
+ Init itself exits 2 here (its embed fails too); the stamp is reset to
available so the update test proves the update is what marks it.
"""
import subprocess
@@ -441,7 +441,7 @@ def _indexed_repo_with_broken_store(tmp_path, monkeypatch) -> Path:
init = CliRunner().invoke(
cli, ["init", str(repo), "--index-only", "--embedder", "ollama", "--yes", "--no-workspace"]
)
- assert init.exit_code == 1, init.output
+ assert init.exit_code == 2, init.output
state = load_state(repo)
state["index_scope"]["search"]["semantic"] = "available"
save_state(repo, state)
diff --git a/tests/unit/cli/test_init_exit_codes.py b/tests/unit/cli/test_init_exit_codes.py
new file mode 100644
index 000000000..9aa460c10
--- /dev/null
+++ b/tests/unit/cli/test_init_exit_codes.py
@@ -0,0 +1,131 @@
+"""`repowise init` exit codes: 0 ready, 2 finished with gaps, 130 interrupted."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands.init_cmd import _generate, _ingest, command
+from repowise.cli.commands.init_cmd._exit import exit_on_gaps, run_gaps
+from repowise.cli.exit_codes import EXIT_DEGRADED, EXIT_INTERRUPTED
+from repowise.cli.main import cli
+from repowise.core.cancellation import PipelineCancelled
+
+_KEYS = (
+ "ANTHROPIC_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENROUTER_API_KEY",
+ "DEEPSEEK_API_KEY",
+ "KIMI_API_KEY",
+ "GOOGLE_API_KEY",
+ "GEMINI_API_KEY",
+ "OLLAMA_BASE_URL",
+ "LITELLM_API_KEY",
+ "REPOWISE_PROVIDER",
+ "REPOWISE_EMBEDDER",
+)
+
+
+def repo(tmp_path, monkeypatch):
+ for var in _KEYS:
+ monkeypatch.delenv(var, raising=False)
+ (tmp_path / "app.py").write_text("def main():\n return 1\n", encoding="utf-8")
+ return tmp_path
+
+
+def _init(repo, *flags):
+ return CliRunner().invoke(cli, ["init", str(repo), "--no-workspace", *flags])
+
+
[email protected]("signal", [KeyboardInterrupt, PipelineCancelled])
+def test_interrupt_while_indexing_exits_130(repo, monkeypatch, signal):
+ async def _stop(*_a, **_k):
+ raise signal
+
+ monkeypatch.setattr(_ingest, "_index_with_resume", _stop)
+
+ result = _init(repo, "--no-prose", "--yes")
+
+ assert result.exit_code == EXIT_INTERRUPTED, result.output
+ assert "Interrupted." in result.output
+ assert "repowise init --resume" in result.output
+
+
+def test_interrupt_after_indexing_exits_130(repo, monkeypatch):
+ """Ctrl-C outside the pipeline's own handler, e.g. during generation."""
+
+ def _stop(_run):
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(command, "_generate", _stop)
+
+ result = _init(repo, "--no-prose", "--yes")
+
+ assert result.exit_code == EXIT_INTERRUPTED, result.output
+ assert "repowise init --resume" in result.output
+
+
+def test_a_run_with_warnings_exits_degraded(repo, monkeypatch):
+ """A degraded result: the index is saved and the last line says why."""
+ real = _ingest.index_repository
+
+ def _with_warning(run):
+ real(run)
+ run.run_warnings.append("Git history skipped: repository is shallow")
+
+ monkeypatch.setattr(command, "index_repository", _with_warning)
+
+ result = _init(repo, "--no-prose", "--yes")
+
+ assert result.exit_code == EXIT_DEGRADED, result.output
+ assert "Finished with gaps: 1 warning(s) while indexing (see above)." in " ".join(result.output.split())
+ assert (repo / ".repowise" / "state.json").exists()
+
+
+def test_unconfirmed_cost_builds_from_code_and_exits_degraded(repo, monkeypatch):
+ """No terminal and no --yes over the gate: built from code, exit 2, names --yes."""
+ est = SimpleNamespace(estimated_cost_usd=9.0, cost_range=None, is_calibrated=False)
+ monkeypatch.setattr(_generate, "estimate_generation", lambda **_k: ([], est))
+ monkeypatch.setattr(_generate, "_print_generation_plan", lambda *_a, **_k: None)
+
+ result = _init(repo, "--provider", "mock")
+
+ assert result.exit_code == EXIT_DEGRADED, result.output
+ out = " ".join(result.output.split())
+ assert "Finished with gaps: documentation built from code" in out
+ assert "Re-run with --yes to accept the cost" in out
+ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ assert state["docs_mode"] == "deterministic"
+
+
+def test_overwrite_guard_names_no_prose(repo):
+ (repo / ".repowise").mkdir()
+ (repo / ".repowise" / "state.json").write_text(
+ json.dumps({"docs_mode": "llm", "last_sync_commit": "abc"}), encoding="utf-8"
+ )
+
+ result = _init(repo, "--no-prose")
+
+ assert result.exit_code == 1, result.output
+ out = " ".join(result.output.split())
+ assert "drop --no-prose" in out
+ assert "--index-only" not in out
+
+
+def test_help_names_the_exit_codes():
+ result = CliRunner().invoke(cli, ["init", "--help"])
+ assert "Exit codes: 0 ready, 2 finished with gaps" in " ".join(result.output.split())
+
+
+def test_no_gaps_returns_and_any_gap_exits_degraded():
+ assert run_gaps(failed_pages=0, embed_error=None) == []
+ exit_on_gaps([])
+ gaps = run_gaps(failed_pages=3, embed_error="Embedding failed for 1 page(s).")
+ assert gaps == ["3 page(s) failed to generate", "Embedding failed for 1 page(s)"]
+ with pytest.raises(SystemExit) as exc:
+ exit_on_gaps(gaps)
+ assert exc.value.code == EXIT_DEGRADED