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(init): ingest, generation, state and post-run stages of init_command (#4007)

Raghav Chamadiyaa1b45de85e94
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/init_cmd/__init__.py
index c8651135e..09b2ab048 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/__init__.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/__init__.py
@@ -8,6 +8,8 @@ Split out of a single 2k-line module into cohesive parts:
* :mod:`.persistence` — database + state.json + config.yaml writers
* :mod:`.reporting` — analysis + completion console panels
* :mod:`._interactive` — interactive prompts
+* :mod:`._options`, :mod:`._seed`, :mod:`._provider`, :mod:`._ingest`,
+ :mod:`._finish` — the single-repo run's options and stages
This package re-exports the public command plus the leading-underscore names
that sibling commands (``search``/``reindex``) and the test-suite import from
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
new file mode 100644
index 000000000..b495a1f6f
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
@@ -0,0 +1,416 @@
+"""After generation: persistence, config and state, editor setup and the completion panel."""
+
+from __future__ import annotations
+
+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
+from repowise.cli.editor_setup import register_editor_clients, write_editor_project_files
+from repowise.cli.helpers import (
+ config_fingerprint,
+ console,
+ get_head_commit,
+ head_commit_ts,
+ load_state,
+ run_async,
+ save_config_partial,
+ save_state,
+)
+from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
+from repowise.cli.ui import (
+ BRAND_STYLE,
+ OK,
+ OWL_SPINNER,
+ MaybeCountColumn,
+ RichProgressCallback,
+ print_phase_header,
+)
+from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
+from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
+from repowise.core.docs_mode import docs_mode_state_fields
+from repowise.core.generation.styles import DEFAULT_STYLE
+from repowise.core.repo_config import config_dependency_fingerprints
+
+from ._interactive import offer_distill_rewrite_hook, offer_hook_install
+from ._options import InitRun
+from .persistence import (
+ apply_git_history_coverage_state,
+ git_tier_for_run_mode,
+ persist_result,
+ save_full_state_and_config,
+)
+from .reporting import show_completion
+
+
+def persist_index(run: InitRun) -> None:
+ """Save to the database and build the search index."""
+ print_phase_header(
+ console,
+ run.total_phases,
+ run.total_phases,
+ "Persistence",
+ "Saving to database and building search index",
+ )
+
+ # The index run's columns, minus cost.
+ recorder = run.recorder
+ with Progress(
+ SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),
+ TextColumn("[progress.description]{task.description}"),
+ BarColumn(),
+ MaybeCountColumn(),
+ TimeElapsedColumn(),
+ console=console,
+ ) as persist_bar:
+ persist_callback = recorder.rebind(RichProgressCallback(persist_bar, console))
+ # Indeterminate, announced so the stage is never silent.
+ persist_callback.on_phase_start("persist", None)
+ run_async(persist_result(run.result, run.repo_path, persist_callback, recorder.table))
+ persist_callback.on_phase_done("persist")
+ # Persistence has its own callback; fold its warnings into the run record.
+ run.run_warnings.extend(persist_callback.warnings)
+ # Read last: every stage writes into the one table.
+ recorder.table.stop("run")
+ run.phase_timings = recorder.timings
+ console.print(f" [{OK}]✓[/] Database updated")
+
+
+def catch_up_savings(repo_path: Path) -> None:
+ """Bank the token savings agents recorded before the first index. Best-effort.
+
+ Init only: its cost scales with agent history, too much for every update.
+ """
+ try:
+ from repowise.core.savings.transcript import sync_transcript_savings
+
+ outcome = sync_transcript_savings(repo_path)
+ except Exception:
+ return
+ if outcome.recorded:
+ console.print(
+ f" [{OK}]✓[/] Recovered {outcome.saved_input_tokens:,} saved tokens "
+ f"from agent history"
+ )
+
+
+def save_run_config(run: InitRun) -> None:
+ """Record this run's choices in config.yaml so later runs keep them."""
+ opts = run.opts
+ repo_path = run.repo_path
+ # Defaults stay unrecorded; only overrides are written.
+ if not opts.onboarding:
+ save_config_partial(repo_path, enable_onboarding=False)
+
+ # 0 (a refusal) is recorded; only None stays unwritten.
+ if run.max_file_pages is not None and run.max_file_pages != run.config.get("max_file_pages"):
+ save_config_partial(repo_path, max_file_pages=run.max_file_pages)
+
+ # Written before the config fingerprint. A template wiki has no style or
+ # language, and recording one would make `restyle` skip it.
+ if opts.wiki_style != DEFAULT_STYLE and not run.effective_index_only:
+ save_config_partial(repo_path, wiki_style=opts.wiki_style)
+
+ if run.language != run.config.get("language", "en") and not run.effective_index_only:
+ save_config_partial(repo_path, language=run.language)
+
+ if opts.commit_limit is not None:
+ save_config_partial(repo_path, commit_limit=run.resolved_commit_limit)
+
+
+def register_clients(run: InitRun) -> None:
+ """Global client registration, then the workspace's distill verdict."""
+ register_editor_clients(console, run.repo_path, no_editor_setup=not run.opts.editor_setup)
+
+ # Before the config fingerprint: left unwritten, the first update writes it,
+ # sees a fingerprint change and re-scores every file.
+ from repowise.cli.commands.workspace_cmd import inherit_workspace_distill_verdict
+
+ inherit_workspace_distill_verdict(run.repo_path)
+
+
+def _docs_mode(run: InitRun) -> str:
+ """``llm``, ``deterministic`` (templates) or ``none`` (fast mode)."""
+ if run.opts.run_mode == "fast":
+ return "none"
+ if not run.effective_index_only and run.provider is not None:
+ return "llm"
+ return "deterministic"
+
+
+def _stamp_scope(run: InitRun, base_state: dict[str, Any], docs_mode: str) -> None:
+ from repowise.cli.providers import semantic_search_status
+ from repowise.core.generation.selection import count_documentable_files
+ from repowise.core.index_scope import dropped_files_scope, file_page_scope, stamp_index_scope
+
+ result = run.result
+ run_mode = run.opts.run_mode
+ provider = run.provider
+ scope_embedder = run.scope_embedder
+ unavailable = []
+ if getattr(result, "health_report", None) is None:
+ unavailable.append("health")
+ skipped = ["generation"] if run_mode == "fast" else []
+ stamp_index_scope(
+ base_state,
+ {"commit_limit": run.resolved_commit_limit, "max_file_pages": run.max_file_pages},
+ run_mode=run_mode,
+ content_provenance={"none": "none", "deterministic": "template", "llm": "model"}[
+ docs_mode
+ ],
+ git_tier=git_tier_for_run_mode(run_mode),
+ git_commit_cap=run.resolved_commit_limit,
+ dropped_files=dropped_files_scope(getattr(result, "traversal_stats", None)),
+ file_pages={
+ "configured_cap": run.max_file_pages,
+ **(
+ result.generation_scope
+ if getattr(result, "generation_scope", None)
+ else file_page_scope(
+ configured_cap=run.max_file_pages,
+ eligible=count_documentable_files(result.parsed_files),
+ generated_pages=result.generated_pages,
+ )
+ ),
+ },
+ analysis={"unavailable": unavailable, "skipped": skipped},
+ provider={
+ "name": provider.provider_name if provider is not None else None,
+ "model": provider.model_name if provider is not None else None,
+ "embedder": scope_embedder,
+ "reused": False,
+ "model_cost_possible": docs_mode == "llm",
+ },
+ search={
+ "full_text": "available" if result.generated_pages else "unavailable",
+ "semantic": (
+ semantic_search_status(scope_embedder, getattr(result, "embed_failed_pages", 0))
+ if result.generated_pages
+ else "unavailable"
+ ),
+ "next_command": "repowise reindex" if result.generated_pages else None,
+ },
+ upgrade={
+ "status": "pending" if docs_mode != "llm" else "not_applicable",
+ "retryable": docs_mode != "llm",
+ "completed_stages": [],
+ "next_stage": "git_backfill" if run_mode == "fast" else "generation",
+ },
+ )
+
+
+def _base_state(run: InitRun) -> dict[str, Any]:
+ """state.json for this run, before the mode-specific stamps.
+
+ ``last_sync_commit`` is written in every mode so ``repowise update`` has a
+ baseline to diff against.
+ """
+ repo_path = run.repo_path
+ result = run.result
+ run_mode = run.opts.run_mode
+ head = get_head_commit(repo_path)
+ base_state = load_state(repo_path)
+ base_state["last_sync_commit"] = head
+ docs_mode = _docs_mode(run)
+ base_state.update(docs_mode_state_fields(docs_mode))
+ base_state["total_pages"] = len(getattr(result, "generated_pages", None) or [])
+ # So a later --resume keeps this git tier.
+ base_state["run_mode"] = run_mode
+ base_state["git_tier"] = git_tier_for_run_mode(run_mode)
+ apply_git_history_coverage_state(base_state, result)
+ _stamp_scope(run, base_state, docs_mode)
+ base_state["include_submodules"] = run.opts.include_submodules
+ if run.phase_timings:
+ base_state["phase_timings"] = run.phase_timings
+ # Never inherit the previous run's degradation report.
+ base_state.pop("degraded", None)
+ if run.run_warnings:
+ base_state["degraded"] = run.run_warnings
+ kg = getattr(result, "knowledge_graph_result", None)
+ if kg is not None:
+ base_state["knowledge_graph"] = build_kg_state(kg)
+ save_knowledge_graph_json(repo_path, kg)
+ return base_state
+
+
+def _save_index_only_state(run: InitRun, base_state: dict[str, Any]) -> None:
+ """Config and state for a run with no model, which skips save_config()."""
+ from repowise.cli.providers.embedders import resolve_embedding_model
+
+ repo_path = run.repo_path
+ embedder = run.index_only_embedder
+ # Embedder and model as a pair, so update, serve and the store-format check
+ # keep embedding the way this run did.
+ save_config_partial(
+ repo_path,
+ exclude_patterns=run.exclude_patterns if run.exclude_patterns else None,
+ commit_limit=run.resolved_commit_limit if run.opts.commit_limit is not None else None,
+ embedder=embedder,
+ embedding_model=resolve_embedding_model(embedder) if embedder else None,
+ )
+ # Fingerprint after config writes so the first update doesn't false-positive.
+ base_state["config_fingerprint"] = config_fingerprint(repo_path)
+ base_state["config_dependency_fingerprints"] = config_dependency_fingerprints(repo_path)
+ # Without these stamps the version triggers never fire for keyless installs.
+ base_state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION
+ base_state["security_scanner_version"] = SECURITY_SCANNER_VERSION
+ # Unstamped, the first update would re-render the whole wiki.
+ from repowise.cli.commands.update_cmd.command import _current_renderer_fingerprint
+
+ base_state["renderer_fingerprint"] = _current_renderer_fingerprint(repo_path)
+ # Start the re-score cadence only when a health report was persisted;
+ # otherwise the first update's re-score must still run.
+ _head_ts = head_commit_ts(repo_path) if getattr(run.result, "health_report", None) else None
+ if _head_ts is not None:
+ base_state["last_full_rescore_at"] = _head_ts
+ save_state(repo_path, base_state, full_index=True)
+
+
+def write_run_state(run: InitRun) -> None:
+ """state.json always; config.yaml for the mode this run ran in."""
+ run.scope_embedder = (
+ run.embedder_name_resolved if not run.effective_index_only else run.index_only_embedder
+ )
+ base_state = _base_state(run)
+ if run.effective_index_only or run.provider is None:
+ _save_index_only_state(run, base_state)
+
+ if not run.effective_index_only and run.provider:
+ opts = run.opts
+ save_full_state_and_config(
+ repo_path=run.repo_path,
+ result=run.result,
+ provider=run.provider,
+ phase_timings=run.phase_timings,
+ degraded=run.run_warnings,
+ embedder_name_resolved=run.embedder_name_resolved,
+ exclude_patterns=run.exclude_patterns,
+ commit_limit=opts.commit_limit,
+ resolved_commit_limit=run.resolved_commit_limit,
+ resolved_reasoning=run.resolved_reasoning,
+ max_file_pages=run.max_file_pages,
+ include_submodules=opts.include_submodules,
+ save_key=opts.save_key,
+ )
+
+
+def _record_init_outcome(run: InitRun) -> None:
+ """Attach the anonymous index-shape outcome to ``command_run``. Best-effort."""
+ result = run.result
+ try:
+ lang_dist = getattr(
+ getattr(result, "repo_structure", None), "root_language_distribution", None
+ )
+ top_language = None
+ if isinstance(lang_dist, dict) and lang_dist:
+ top_language = max(lang_dist.items(), key=lambda kv: kv[1])[0]
+
+ pages = getattr(result, "generated_pages", None) or []
+ if not run.effective_index_only and run.provider is not None:
+ docs_mode = "llm"
+ else:
+ docs_mode = "deterministic" if pages else "none"
+ buckets = {
+ "file_count": getattr(result, "file_count", 0) or 0,
+ "symbol_count": getattr(result, "symbol_count", 0) or 0,
+ }
+ if pages:
+ buckets["deterministic_pages"] = sum(
+ 1 for p in pages if getattr(p, "provider_name", "") == "template"
+ )
+ except Exception:
+ return
+ record_index_outcome(
+ index_only=run.effective_index_only,
+ provider=run.provider,
+ docs_mode=docs_mode,
+ pages=pages,
+ buckets=buckets,
+ fields={
+ "run_mode": run.opts.run_mode,
+ "top_language": top_language,
+ "embedder": run.embedder_name_resolved or None,
+ },
+ )
+
+
+def _write_editor_files(run: InitRun) -> list[Path]:
+ """Read views, project editor files and the coverage hook; returns the files written.
+
+ Runs after state is saved so the guidance reads the final index_scope.
+ """
+ repo_path = run.repo_path
+ editor_setup = run.opts.editor_setup
+ # Before the editor files, which quote Fix first from these views.
+ refresh_read_snapshots(repo_path)
+ files_written = write_editor_project_files(
+ console,
+ repo_path,
+ options=run.editor_options,
+ no_editor_setup=not editor_setup,
+ )
+ if editor_setup:
+ from repowise.cli.commands.augment_cmd.coverage_reingest import sync_repo_hook
+
+ sync_repo_hook(repo_path, console)
+ return files_written
+
+
+def complete_setup(run: InitRun) -> None:
+ """Editor files, hook offers, then the completion panel."""
+ opts = run.opts
+ repo_path = run.repo_path
+ files_written = _write_editor_files(run)
+ _record_init_outcome(run)
+
+ offer_hook_install(
+ console,
+ [repo_path],
+ flag=opts.hook,
+ yes=opts.yes,
+ no_editor_setup=not opts.editor_setup,
+ )
+
+ offer_distill_rewrite_hook(
+ console,
+ [repo_path],
+ opts.distill_hook,
+ yes=opts.yes,
+ no_editor_setup=not opts.editor_setup,
+ )
+
+ # Last, so the panel reflects what setup did. `interactive` mirrors the
+ # offers' gate: when they were skipped the panel names their hooks.
+ from repowise.cli.editor_setup import detect_editor_setup_outcome
+
+ setup_outcome = detect_editor_setup_outcome(
+ repo_path,
+ interactive=(sys.stdin.isatty() and not opts.yes),
+ first_index=run.first_index,
+ no_editor_setup=not opts.editor_setup,
+ )
+ show_completion(
+ repo_path=repo_path,
+ result=run.result,
+ start=run.start,
+ effective_index_only=run.effective_index_only,
+ run_mode=opts.run_mode,
+ provider=run.provider,
+ setup=setup_outcome,
+ files_written=files_written,
+ )
+
+
+def raise_on_embed_failure(run: InitRun) -> None:
+ """Exit non-zero when embedding failed; raised 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)
+ )
+ if embed_error:
+ raise click.ClickException(embed_error)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py b/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py
new file mode 100644
index 000000000..183a413ef
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py
@@ -0,0 +1,169 @@
+"""Ingestion and analysis stage of ``repowise init`` (phases 1 and 2)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
+
+from repowise.cli.helpers import console, load_state, run_async
+from repowise.cli.ui import (
+ BRAND_STYLE,
+ OK,
+ OWL_SPINNER,
+ WARN,
+ MaybeCountColumn,
+ RichProgressCallback,
+)
+
+from ._options import InitRun
+from .persistence import build_resume_controller
+
+
+def _index_vector_store(run: InitRun) -> Any:
+ """Generation's vector store, built early so analysis can dedup decisions against it.
+
+ None for runs that build no store (a dry run, index-only fast mode) and
+ for a keyless store, which the matcher refuses.
+ """
+ opts = run.opts
+ if opts.dry_run or (opts.index_only and opts.run_mode == "fast"):
+ return None
+ from repowise.cli.providers import build_embedder, build_vector_store, template_run_embedder
+ from repowise.core.providers.embedding import store_has_semantic_vectors
+
+ store_embedder = (
+ template_run_embedder(run.embedder_name_resolved, run.embedder_was_requested)
+ if opts.index_only or run.no_provider
+ else run.embedder_name_resolved
+ )
+ candidate = build_vector_store(run.repo_path, build_embedder(store_embedder, run.repo_path))
+ return candidate if store_has_semantic_vectors(candidate) else None
+
+
+def _index_columns(with_cost: bool) -> list[Any]:
+ columns: list[Any] = [
+ SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),
+ TextColumn("[progress.description]{task.description}"),
+ BarColumn(),
+ MaybeCountColumn(),
+ TimeElapsedColumn(),
+ ]
+ # Cost column only when a model can be called.
+ if with_cost:
+ columns.append(TextColumn("[" + OK + "]${task.fields[cost]:.3f}[/]"))
+ return columns
+
+
+async def _index_with_resume(
+ run: InitRun,
+ *,
+ run_pipeline: Any,
+ llm_client: Any,
+ vector_store: Any,
+ mode: Any,
+ callback: Any,
+ existing_kg_fingerprint: str | None,
+) -> Any:
+ """Run the pipeline with a resume controller.
+
+ The controller's engine and repository row are created first, in this
+ event loop, so an interrupt leaves a resumable index. A dry run touches no
+ database.
+ """
+ opts = run.opts
+ controller = None
+ engine = None
+ if not opts.dry_run:
+ controller, engine = await build_resume_controller(run.repo_path, resume=opts.resume)
+ try:
+ return await run_pipeline(
+ run.repo_path,
+ commit_depth=run.resolved_commit_limit,
+ follow_renames=run.resolved_follow_renames,
+ skip_tests=opts.skip_tests,
+ skip_infra=opts.skip_infra,
+ exclude_patterns=run.exclude_patterns if run.exclude_patterns else None,
+ include_submodules=opts.include_submodules,
+ generate_docs=False,
+ llm_client=llm_client,
+ vector_store=vector_store,
+ concurrency=opts.concurrency,
+ test_run=opts.test_run,
+ mode=mode,
+ progress=callback,
+ existing_kg_fingerprint=existing_kg_fingerprint,
+ resume_controller=controller,
+ coverage_report_paths=(
+ [Path(p) for p in opts.coverage_report] if opts.coverage_report else None
+ ),
+ # Only local init describes the user's own environment.
+ derive_environment_facts=True,
+ )
+ finally:
+ if engine is not None:
+ await engine.dispose()
+
+
+def index_repository(run: InitRun) -> bool:
+ """Phases 1 and 2, without docs (generation follows the cost gate). False 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
+ # None on a dry run: analysis would call it before generation's dry-run exit.
+ llm_client = None
+ if not opts.dry_run:
+ llm_client = run.provider if not opts.index_only else run.decision_provider
+
+ from repowise.core.pipeline import PhaseTimingRecorder, run_pipeline
+ from repowise.core.pipeline.modes import OrchestratorMode
+
+ orchestrator_mode = (
+ OrchestratorMode.FAST if opts.run_mode == "fast" else OrchestratorMode.STANDARD
+ )
+ index_vector_store = _index_vector_store(run)
+
+ with Progress(*_index_columns(llm_client is not None), console=console) as progress_bar:
+ rich_callback = RichProgressCallback(progress_bar, console, total_phases=run.total_phases)
+ callback = PhaseTimingRecorder(rich_callback)
+ # Whole-run total: phases nest and overlap, so their sum can exceed it.
+ callback.table.start("run")
+
+ prev_state = load_state(run.repo_path)
+ prev_kg_fp = (
+ prev_state.get("knowledge_graph", {}).get("fingerprint") if not opts.force else None
+ )
+
+ # First Ctrl-C unwinds cleanly for a later --resume; a second hard-quits.
+ from repowise.core.cancellation import PipelineCancelled, cancellation_scope
+
+ try:
+ with cancellation_scope():
+ result = run_async(
+ _index_with_resume(
+ run,
+ run_pipeline=run_pipeline,
+ llm_client=llm_client,
+ vector_store=index_vector_store,
+ mode=orchestrator_mode,
+ callback=callback,
+ existing_kg_fingerprint=prev_kg_fp,
+ )
+ )
+ except (PipelineCancelled, KeyboardInterrupt):
+ from repowise.cli.ui.mascot import EYES_SLEEPY, mini
+
+ 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
+
+ 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 894900318..8ac650914 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
@@ -95,6 +95,17 @@ class InitRun:
# template renderer. Treated exactly like ``--index-only`` from the
# generation phase onward.
no_provider: bool = False
+ total_phases: int = 4
+ result: Any = None
+ # PhaseTimingRecorder shared by every stage.
+ recorder: Any = None
+ run_warnings: list[str] = field(default_factory=list)
+ # Embedder of the template wiki, None when none was rendered.
+ index_only_embedder: str | None = None
+ cost_declined: bool = False
+ effective_index_only: bool = False
+ phase_timings: dict[str, float] = field(default_factory=dict)
+ scope_embedder: str | None = None
def resolve_structural_flags(opts: InitOptions) -> InitOptions:
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 88f79a017..e6ef64129 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -15,52 +15,37 @@ from pathlib import Path
from typing import Any
import click
-from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
from rich.table import Table
from repowise.cli._setup import configure_cli_logging
-from repowise.cli.commands._index_outcome import record_index_outcome, refresh_read_snapshots
from repowise.cli.editor_integrations.defaults import (
get_default_disabled_project_files,
get_default_integration_overrides,
get_default_project_file_overrides,
)
from repowise.cli.editor_setup import (
- register_editor_clients,
resolve_editor_setup_options,
select_agents_interactively,
- write_editor_project_files,
)
from repowise.cli.errors import reasoned_error
from repowise.cli.helpers import (
- config_fingerprint,
console,
ensure_repowise_dir,
- get_head_commit,
- head_commit_ts,
load_config,
load_state,
resolve_max_file_pages,
resolve_provider,
resolve_reasoning,
resolve_repo_path,
- run_async,
- save_config_partial,
- save_state,
warn,
)
from repowise.cli.providers import resolve_embedder
from repowise.cli.providers.embedders import embedder_was_requested as _embedder_was_requested
-from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
from repowise.cli.ui import (
BRAND,
- BRAND_STYLE,
- OK,
OWL_SPINNER,
VALUE,
WARN,
- MaybeCountColumn,
- RichProgressCallback,
agent_providers_set_up,
interactive_advanced_config,
interactive_customize_offer,
@@ -76,16 +61,22 @@ from repowise.cli.ui import (
quick_repo_scan,
should_offer_fast_mode,
)
-from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
from repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS
-from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
-from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
+from repowise.core.docs_mode import resolve_docs_mode
from repowise.core.generation.languages import SUPPORTED_LANGUAGES
from repowise.core.generation.styles import DEFAULT_STYLE, list_styles, resolve_style
from repowise.core.reasoning import REASONING_MODES
-from repowise.core.repo_config import config_dependency_fingerprints
-from ._interactive import offer_distill_rewrite_hook, offer_hook_install
+from ._finish import (
+ catch_up_savings,
+ complete_setup,
+ persist_index,
+ raise_on_embed_failure,
+ register_clients,
+ save_run_config,
+ write_run_state,
+)
+from ._ingest import index_repository
from ._options import InitOptions, InitRun, resolve_structural_flags
from ._provider import announce_index_only, decision_key_in_env, resolve_docs_provider
from ._seed import delegate_to_seeded_update
@@ -99,94 +90,12 @@ from .generation import (
structural_page_summary,
)
from .persistence import (
- apply_git_history_coverage_state,
- build_resume_controller,
effective_run_mode_for_resume,
- git_tier_for_run_mode,
- persist_result,
- save_full_state_and_config,
)
-from .reporting import show_analysis_summary, show_completion
+from .reporting import show_analysis_summary
from .workspace import _workspace_init
-def _catch_up_savings(repo_path: Path) -> None:
- """Bank the savings this repository's agents were shown before indexing.
-
- Keyless, time-budgeted and best-effort, following the session-decision
- stage that runs here for the same reason: the history is already on disk,
- and a first index that ignores it shows an empty savings page for a
- repository that has been saving tokens for months.
-
- Not in ``repowise update``: update runs on every commit, and this reads a
- corpus bounded by how much the user has worked rather than by the repo.
- """
- try:
- from repowise.core.savings.transcript import sync_transcript_savings
-
- outcome = sync_transcript_savings(repo_path)
- except Exception:
- return
- if outcome.recorded:
- console.print(
- f" [{OK}]✓[/] Recovered {outcome.saved_input_tokens:,} saved tokens "
- f"from agent history"
- )
-
-
-def _record_init_outcome(
- *,
- result: Any,
- effective_index_only: bool,
- run_mode: str,
- provider: Any,
- embedder_name_resolved: str,
-) -> None:
- """Attach an anonymous shape-of-the-index outcome to the ``command_run`` event.
-
- File and symbol buckets, run mode, top language and embedder on top of the
- shared index shape. Best-effort: never let telemetry break the command.
- """
- try:
- lang_dist = getattr(
- getattr(result, "repo_structure", None), "root_language_distribution", None
- )
- top_language = None
- if isinstance(lang_dist, dict) and lang_dist:
- top_language = max(lang_dist.items(), key=lambda kv: kv[1])[0]
-
- # docs_mode carries the same three values as the state field of that
- # name. It used to be a bool, which collapsed "template wiki" and "no
- # wiki" into one number, and template runs are the ones worth counting.
- pages = getattr(result, "generated_pages", None) or []
- if not effective_index_only and provider is not None:
- docs_mode = "llm"
- else:
- docs_mode = "deterministic" if pages else "none"
- buckets = {
- "file_count": getattr(result, "file_count", 0) or 0,
- "symbol_count": getattr(result, "symbol_count", 0) or 0,
- }
- if pages:
- buckets["deterministic_pages"] = sum(
- 1 for p in pages if getattr(p, "provider_name", "") == "template"
- )
- except Exception:
- return
- record_index_outcome(
- index_only=effective_index_only,
- provider=provider,
- docs_mode=docs_mode,
- pages=pages,
- buckets=buckets,
- fields={
- "run_mode": run_mode,
- "top_language": top_language,
- "embedder": embedder_name_resolved or None,
- },
- )
-
-
def _print_structural_plan(
*,
result: Any,
@@ -867,6 +776,107 @@ def _prepare_single_repo(opts: InitOptions, repo_path: Path, start: float) -> In
return run
+def _render_template_wiki(run: InitRun, *, embedder_was_requested: bool) -> None:
+ """Render the whole wiki from structure and remember the embedder it used."""
+ opts = run.opts
+ run.index_only_embedder = _run_deterministic_generation_phase(
+ repo_path=run.repo_path,
+ result=run.result,
+ total_phases=run.total_phases,
+ concurrency=opts.concurrency,
+ language=run.language,
+ onboarding=opts.onboarding,
+ wiki_style=opts.wiki_style,
+ max_file_pages=run.max_file_pages,
+ embedder_name_resolved=run.embedder_name_resolved,
+ embedder_was_requested=embedder_was_requested,
+ resume=opts.resume,
+ timings=run.recorder.table,
+ warnings=run.run_warnings,
+ )
+
+
+def _generate_with_model(run: InitRun) -> bool:
+ """The priced branch. True when it was a dry run and init should stop."""
+ opts = run.opts
+ gen_stop, cost_declined = _run_generation_phase(
+ repo_path=run.repo_path,
+ result=run.result,
+ provider=run.provider,
+ total_phases=run.total_phases,
+ concurrency=opts.concurrency,
+ language=run.language,
+ resolved_reasoning=run.resolved_reasoning,
+ onboarding=opts.onboarding,
+ wiki_style=opts.wiki_style,
+ max_file_pages=run.max_file_pages,
+ yes=opts.yes,
+ dry_run=opts.dry_run,
+ skip_tests=opts.skip_tests,
+ skip_infra=opts.skip_infra,
+ embedder_name_resolved=run.embedder_name_resolved,
+ # A template wiki fills the store resume reads, so never resume over it.
+ resume=opts.resume and run.prior_docs_mode != "deterministic",
+ warnings=run.run_warnings,
+ test_run=opts.test_run,
+ timings=run.recorder.table,
+ )
+ if gen_stop:
+ return True
+ if cost_declined and run.prior_docs_mode == "llm":
+ # 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
+
+
+def _generate(run: InitRun) -> bool:
+ """Phase 3. True when init should stop here (a dry run)."""
+ opts = run.opts
+ # The priced branch has its own dry-run exit.
+ if opts.dry_run and (opts.index_only or run.no_provider):
+ if opts.run_mode == "fast":
+ console.print("\n Dry run: fast mode indexes graph and git only. No wiki written.")
+ else:
+ _print_structural_plan(
+ result=run.result,
+ repo_path=run.repo_path,
+ concurrency=opts.concurrency,
+ language=run.language,
+ onboarding=opts.onboarding,
+ wiki_style=opts.wiki_style,
+ max_file_pages=run.max_file_pages,
+ skip_tests=opts.skip_tests,
+ skip_infra=opts.skip_infra,
+ )
+ return True
+
+ # Fast mode is a graph-and-git index only.
+ if opts.index_only and opts.run_mode == "fast":
+ console.print(
+ " [dim]Skipping wiki generation in fast mode. Run "
+ "[bold]repowise init[/bold] without [bold]--mode fast[/bold] to "
+ "render it from structure, or [bold]repowise update --full[/bold] "
+ "to write it with a model.[/dim]"
+ )
+ return False
+ if opts.index_only or run.no_provider:
+ _render_template_wiki(run, embedder_was_requested=run.embedder_was_requested)
+ return False
+ return _generate_with_model(run)
+
+
@click.command("init")
@click.argument("path", required=False, default=None)
@click.option(
@@ -1224,653 +1234,19 @@ def init_command(**params: Any) -> None:
repo_path = scan.repos[0].path
run = _prepare_single_repo(opts, repo_path, start)
- if run is None:
+ if run is None or not index_repository(run):
return
- opts = run.opts
- index_only = opts.index_only
- run_mode = opts.run_mode
- dry_run = opts.dry_run
- force = opts.force
- yes = opts.yes
- resume = opts.resume
- skip_tests = opts.skip_tests
- skip_infra = opts.skip_infra
- include_submodules = opts.include_submodules
- concurrency = opts.concurrency
- test_run = opts.test_run
- coverage_report = opts.coverage_report
- onboarding = opts.onboarding
- wiki_style = opts.wiki_style
- commit_limit = opts.commit_limit
- editor_setup = opts.editor_setup
- save_key = opts.save_key
- hook = opts.hook
- distill_hook = opts.distill_hook
- editor_options = run.editor_options
- config = run.config
- language = run.language
- max_file_pages = run.max_file_pages
- resolved_reasoning = run.resolved_reasoning
- exclude_patterns = run.exclude_patterns
- resolved_commit_limit = run.resolved_commit_limit
- resolved_follow_renames = run.resolved_follow_renames
- embedder_name_resolved = run.embedder_name_resolved
- embedder_was_requested = run.embedder_was_requested
- _first_index = run.first_index
- _prior_docs_mode = run.prior_docs_mode
- provider = run.provider
- decision_provider = run.decision_provider
- no_provider = run.no_provider
-
- # ---- Phase 1 & 2: Ingestion + Analysis (always) ----
- # Index-only generates too, it just renders templates instead of prompting
- # a model, so it is four phases like a full run. Fast mode is the one that
- # still stops at three: see the generation phase below for why.
- total_phases = 3 if run_mode == "fast" 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 the persisted docs
- # mode so subsequent updates default to index-only.
- cost_declined = False
- # None on a dry run: decision extraction and KG enrichment both call this
- # client before the generation phase's dry-run return is reached.
- llm_client = None if dry_run else (provider if not index_only else decision_provider)
-
- from repowise.core.pipeline import PhaseTimingRecorder, run_pipeline
- from repowise.core.pipeline.modes import OrchestratorMode
-
- orchestrator_mode = OrchestratorMode.FAST if run_mode == "fast" else OrchestratorMode.STANDARD
-
- # The store generation would build anyway, hoisted so the analysis
- # checkpoint inside the pipeline can dedup decisions against it;
- # ``run_repo_generation`` reuses this object. Never more than that store,
- # so the exclusions are the runs that build none: a dry run, and index-only
- # fast mode, which also pins no embedder for a table to be read back with.
- # Keyless is dropped rather than handed to a matcher that refuses it.
- index_vector_store = None
- if not dry_run and not (index_only and run_mode == "fast"):
- from repowise.cli.providers import build_embedder, build_vector_store, template_run_embedder
- from repowise.core.providers.embedding import store_has_semantic_vectors
-
- _store_embedder = (
- template_run_embedder(embedder_name_resolved, embedder_was_requested)
- if index_only or no_provider
- else embedder_name_resolved
- )
- _candidate = build_vector_store(repo_path, build_embedder(_store_embedder, repo_path))
- index_vector_store = _candidate if store_has_semantic_vectors(_candidate) else None
-
- index_columns: list[Any] = [
- SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),
- TextColumn("[progress.description]{task.description}"),
- BarColumn(),
- MaybeCountColumn(),
- TimeElapsedColumn(),
- ]
- # Only when a model can actually be called. On a --no-prose run the column
- # would sit at $0.000 for the whole multi-minute index, which reads as an
- # unanswered question rather than an answer (same call generation.py makes
- # for the generation bar).
- if llm_client is not None:
- index_columns.append(TextColumn("[" + OK + "]${task.fields[cost]:.3f}[/]"))
-
- with Progress(*index_columns, console=console) as progress_bar:
- rich_callback = RichProgressCallback(progress_bar, console, total_phases=total_phases)
- # Wrap the Rich callback so we can record per-phase wall-clock
- # durations without changing the pipeline API. Timings get
- # persisted to state.json below.
- callback = PhaseTimingRecorder(rich_callback)
- # The denominator. Phases nest (``persist.fts`` inside ``persist``)
- # and some overlap, so the totals can exceed it - without it there is
- # no way to tell an unrecorded stage from an overlapping one.
- callback.table.start("run")
-
- # Always run ingestion + analysis first (generate_docs=False).
- # Generation happens separately after cost confirmation.
- _prev_state = load_state(repo_path)
- _prev_kg_fp = (
- _prev_state.get("knowledge_graph", {}).get("fingerprint") if not force else None
- )
- async def _index_with_resume() -> Any:
- # Create the engine, session factory, and repository row *before*
- # the pipeline (all in this one event loop) so the resume
- # controller has a stable Repository.id to checkpoint against —
- # fixing the old str(repo_path) FK wiring — and so an interrupt
- # mid-run leaves a resumable, persisted index behind. Skipped on a
- # dry run, which must not touch the database at all.
- controller = None
- engine = None
- if not dry_run:
- controller, engine = await build_resume_controller(repo_path, resume=resume)
- try:
- return await run_pipeline(
- repo_path,
- commit_depth=resolved_commit_limit,
- follow_renames=resolved_follow_renames,
- skip_tests=skip_tests,
- skip_infra=skip_infra,
- exclude_patterns=exclude_patterns if exclude_patterns else None,
- include_submodules=include_submodules,
- generate_docs=False,
- llm_client=llm_client,
- vector_store=index_vector_store,
- concurrency=concurrency,
- test_run=test_run,
- mode=orchestrator_mode,
- progress=callback,
- existing_kg_fingerprint=_prev_kg_fp,
- resume_controller=controller,
- coverage_report_paths=(
- [Path(p) for p in coverage_report] if coverage_report else None
- ),
- # Local `init` is the one place a fact about this machine's
- # environment is a fact about the user's environment.
- derive_environment_facts=True,
- )
- finally:
- if engine is not None:
- await engine.dispose()
-
- # Make the long synchronous index/analysis phases interruptible: the
- # first Ctrl-C unwinds them cleanly (the INDEX checkpoint already on
- # disk is reused on the next --resume), a second forces a hard quit.
- from repowise.core.cancellation import PipelineCancelled, cancellation_scope
-
- try:
- with cancellation_scope():
- result = run_async(_index_with_resume())
- except (PipelineCancelled, KeyboardInterrupt):
- from repowise.cli.ui.mascot import EYES_SLEEPY, mini
-
- 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
-
- # What the run degraded on, in a place an agent can read after the
- # terminal is gone. Timings are read after persistence instead, so
- # generation and the persist tail are in the table too.
- run_warnings: list[str] = list(rich_callback.warnings)
-
- # ---- Analysis summary (shown between analysis and generation) ----
- show_analysis_summary(result)
-
- # ---- Phase 3: Generation ----
- # The priced branch below has its own dry-run return; these two rendered
- # the template wiki and fell through to persistence, overwriting a
- # model-written one. Same shape as #2005 (update) and #1526 (workspace).
- if dry_run and (index_only or no_provider):
- if run_mode == "fast":
- # Fast skips generation outright, so promising a wiki here would
- # preview the opposite of what the real run does.
- console.print("\n Dry run: fast mode indexes graph and git only. No wiki written.")
- else:
- _print_structural_plan(
- result=result,
- repo_path=repo_path,
- concurrency=concurrency,
- language=language,
- onboarding=onboarding,
- wiki_style=wiki_style,
- max_file_pages=max_file_pages,
- skip_tests=skip_tests,
- skip_infra=skip_infra,
- )
+ show_analysis_summary(run.result)
+ if _generate(run):
return
- # The embedder the template wiki was actually built with, persisted below
- # so `repowise update` reuses it. None means no template wiki was rendered.
- _index_only_embedder: str | None = None
-
- # Both modes generate. Index-only renders from templates; full mode picks
- # a coverage level, estimates the spend and prompts a model.
- #
- # Fast mode is the exception. It exists to get a very large repo indexed
- # quickly, and it is offered precisely because the repo is large, so
- # rendering and embedding a page per file is the cost it was chosen to
- # avoid. It also runs ESSENTIAL git, which would leave the git-derived
- # sections of those pages thinner than the pages claim. Fast stays a
- # graph-and-git index; `repowise update --full` is the way out of it.
- if index_only and run_mode == "fast":
- console.print(
- " [dim]Skipping wiki generation in fast mode. Run "
- "[bold]repowise init[/bold] without [bold]--mode fast[/bold] to "
- "render it from structure, or [bold]repowise update --full[/bold] "
- "to write it with a model.[/dim]"
- )
- elif index_only or no_provider:
- # ``no_provider`` reaches here the same way ``--index-only`` does: a
- # full run that found no key still gets the whole template wiki.
- _index_only_embedder = _run_deterministic_generation_phase(
- repo_path=repo_path,
- result=result,
- total_phases=total_phases,
- concurrency=concurrency,
- language=language,
- onboarding=onboarding,
- wiki_style=wiki_style,
- max_file_pages=max_file_pages,
- embedder_name_resolved=embedder_name_resolved,
- embedder_was_requested=embedder_was_requested,
- resume=resume,
- timings=callback.table,
- warnings=run_warnings,
- )
- else:
- gen_stop, cost_declined = _run_generation_phase(
- repo_path=repo_path,
- result=result,
- provider=provider,
- total_phases=total_phases,
- concurrency=concurrency,
- language=language,
- resolved_reasoning=resolved_reasoning,
- onboarding=onboarding,
- wiki_style=wiki_style,
- max_file_pages=max_file_pages,
- yes=yes,
- dry_run=dry_run,
- skip_tests=skip_tests,
- skip_infra=skip_infra,
- embedder_name_resolved=embedder_name_resolved,
- # Resume seeds "already done" from the page ids in the vector
- # store, and a completed template wiki put one there for every
- # file. Resuming against it would skip the entire model run and
- # say nothing, so a template wiki is never a run to continue.
- resume=resume and _prior_docs_mode != "deterministic",
- warnings=run_warnings,
- test_run=test_run,
- timings=callback.table,
- )
- if gen_stop:
- return
- if cost_declined and _prior_docs_mode == "llm":
- # The repo already has written pages. Declining the price of new
- # ones is not a request to replace the old ones with templates,
- # which is what the fallback below would do.
- cost_declined = False
- console.print(
- " [dim]Keeping the wiki this repo already has. Nothing was "
- "generated and nothing was replaced.[/dim]"
- )
- elif cost_declined:
- # Declining the gate used to mean leaving with no wiki at all.
- # It only ever meant "not at that price", so fall back to the
- # free renderer rather than to nothing.
- console.print(
- " [dim]Building the wiki from structure instead. Run "
- "[bold]repowise update --full[/bold] to write it with a "
- "model later.[/dim]"
- )
- _index_only_embedder = _run_deterministic_generation_phase(
- repo_path=repo_path,
- result=result,
- total_phases=total_phases,
- concurrency=concurrency,
- language=language,
- onboarding=onboarding,
- wiki_style=wiki_style,
- max_file_pages=max_file_pages,
- # The user has a provider and just declined a bill, not the
- # embedder they configured, so honour it either way.
- embedder_was_requested=True,
- embedder_name_resolved=embedder_name_resolved,
- resume=resume,
- timings=callback.table,
- warnings=run_warnings,
- )
-
- # ---- Persistence ----
- # `cost_declined` short-circuits any further LLM work for the rest of
- # this run, so persistence/state below treat it as index-only. So does
- # `no_provider`: there is no model to do the work either way.
- effective_index_only = index_only or cost_declined or no_provider
- print_phase_header(
- console,
- total_phases,
- total_phases,
- "Persistence",
- "Saving to database and building search index",
- )
-
- # A bar rather than the old indeterminate spinner: full-text indexing walks
- # every generated page one await at a time, so on a few thousand pages this
- # stage ran for minutes with nothing on screen but a spinner, immediately
- # after a generation bar that had just claimed to be finished. The columns
- # are the index run's, minus the cost one — nothing here spends tokens.
- with Progress(
- SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),
- TextColumn("[progress.description]{task.description}"),
- BarColumn(),
- MaybeCountColumn(),
- TimeElapsedColumn(),
- console=console,
- ) as persist_bar:
- persist_callback = callback.rebind(RichProgressCallback(persist_bar, console))
- # Indeterminate: persistence has no page-proportional loop to count
- # since the full-text index became a single statement. Announced here
- # so the stage is never silent.
- persist_callback.on_phase_start("persist", None)
- run_async(persist_result(result, repo_path, persist_callback, callback.table))
- persist_callback.on_phase_done("persist")
- # Persistence has its own callback, so its warnings need folding into the
- # run record explicitly — the state write below is the last chance.
- run_warnings.extend(persist_callback.warnings)
- # Read now, not before generation: ingestion, analysis, generation and
- # persistence all write into the one table.
- callback.table.stop("run")
- phase_timings: dict[str, float] = callback.timings
- console.print(f" [{OK}]✓[/] Database updated")
-
- _catch_up_savings(repo_path)
-
- # Persist the onboarding choice so subsequent `repowise update` runs
- # honor it without re-passing the flag. Default True is omitted to keep
- # config files tidy — only the override is recorded.
- if not onboarding:
- save_config_partial(repo_path, enable_onboarding=False)
-
- # Persist the file-page decision so `repowise update --full` and `repowise
- # generate` keep the wiki the size that was asked for instead of re-deciding.
- # Recorded whether or not a model wrote the pages, since the cap applies to the
- # template wiki just the same. A refusal (0) is recorded like any other answer:
- # leaving it unrecorded would hand the next run back to the size policy the
- # user just declined. Only an unset value stays unwritten.
- if max_file_pages is not None and max_file_pages != config.get("max_file_pages"):
- # save_config_partial drops None values, and 0 is not None, so an explicit
- # refusal reaches the file.
- save_config_partial(repo_path, max_file_pages=max_file_pages)
-
- # Persist the wiki style so `repowise update` / `restyle` honor it without
- # re-passing the flag. Written before any config_fingerprint is computed
- # below so the first update doesn't false-positive on a config change. The
- # default is omitted to keep config files tidy — only an override is recorded.
- #
- # A template wiki records neither style nor language: it has neither, and
- # recording them would make `restyle` believe the pages are already in that
- # style and refuse the very run that would put them there.
- if wiki_style != DEFAULT_STYLE and not effective_index_only:
- save_config_partial(repo_path, wiki_style=wiki_style)
-
- # Persist the output language so `repowise update` regenerates changed
- # pages in the same language. Written only when the run's language differs
- # from what config.yaml already holds; the default stays unrecorded.
- if language != config.get("language", "en") and not effective_index_only:
- save_config_partial(repo_path, language=language)
-
- # ---- Post-run: config, state, MCP, editor project files ----
- if commit_limit is not None:
- save_config_partial(repo_path, commit_limit=resolved_commit_limit)
- # One flag, one meaning: --no-editor-setup now suppresses the project-local
- # writes as well as the global registration. The paths come back so the
- # completion panel can name what landed in the working tree.
- # Render after state persistence below so generated guidance reads the same
- # canonical index_scope that status/API/MCP expose.
- files_written: list[Path] = []
- register_editor_clients(console, repo_path, no_editor_setup=not editor_setup)
-
- # Inherit the workspace's distill rewrite-hook verdict NOW, before the
- # config fingerprint below is computed. `repowise update` runs the same
- # backfill at its start; if init leaves the verdict unwritten, the first
- # update writes it, sees a fingerprint mismatch, and silently replaces
- # the incremental path with a full health re-score of every file.
- from repowise.cli.commands.workspace_cmd import inherit_workspace_distill_verdict
-
- inherit_workspace_distill_verdict(repo_path)
-
- # ---- State (always) ----
- # Even in index-only mode we persist `last_sync_commit` so that a
- # subsequent `repowise update` (e.g. fired by the post-commit hook) has
- # a baseline to diff against. Without this, index-only users hit
- # "No previous sync found" on every update.
- head = get_head_commit(repo_path)
- base_state = load_state(repo_path)
- base_state["last_sync_commit"] = head
- # A full run wrote its pages with a model. An index-only run (or one where
- # the cost gate was declined) fell back to the template renderer. Fast mode
- # is the one path that reaches here with no pages at all.
- if run_mode == "fast":
- _docs_mode = "none"
- elif not effective_index_only and provider is not None:
- _docs_mode = "llm"
- else:
- _docs_mode = "deterministic"
- base_state.update(docs_mode_state_fields(_docs_mode))
- # Only the full-mode path went through save_full_state_and_config, which
- # counts the pages in the database. An index-only run now produces pages
- # too, so it has to record its own count or `status` reports a wiki of
- # zero pages next to a docs mode that says there is one.
- base_state["total_pages"] = len(getattr(result, "generated_pages", None) or [])
- # Record the git tier this run indexed so a later --resume continues the
- # same tier instead of silently upgrading ESSENTIAL → FULL (issue #341).
- base_state["run_mode"] = run_mode
- base_state["git_tier"] = git_tier_for_run_mode(run_mode)
- apply_git_history_coverage_state(base_state, result)
- from repowise.cli.providers import semantic_search_status
- from repowise.core.generation.selection import count_documentable_files
- from repowise.core.index_scope import dropped_files_scope, file_page_scope, stamp_index_scope
-
- _scope_embedder = embedder_name_resolved if not effective_index_only else _index_only_embedder
- _unavailable = []
- if getattr(result, "health_report", None) is None:
- _unavailable.append("health")
- _skipped = ["generation"] if run_mode == "fast" else []
- stamp_index_scope(
- base_state,
- {"commit_limit": resolved_commit_limit, "max_file_pages": max_file_pages},
- run_mode=run_mode,
- content_provenance={"none": "none", "deterministic": "template", "llm": "model"}[
- _docs_mode
- ],
- git_tier=git_tier_for_run_mode(run_mode),
- git_commit_cap=resolved_commit_limit,
- dropped_files=dropped_files_scope(getattr(result, "traversal_stats", None)),
- file_pages={
- "configured_cap": max_file_pages,
- **(
- result.generation_scope
- if getattr(result, "generation_scope", None)
- else file_page_scope(
- configured_cap=max_file_pages,
- eligible=count_documentable_files(result.parsed_files),
- generated_pages=result.generated_pages,
- )
- ),
- },
- analysis={"unavailable": _unavailable, "skipped": _skipped},
- provider={
- "name": provider.provider_name if provider is not None else None,
- "model": provider.model_name if provider is not None else None,
- "embedder": _scope_embedder,
- "reused": False,
- "model_cost_possible": _docs_mode == "llm",
- },
- search={
- "full_text": "available" if result.generated_pages else "unavailable",
- "semantic": (
- semantic_search_status(
- _scope_embedder, getattr(result, "embed_failed_pages", 0)
- )
- if result.generated_pages
- else "unavailable"
- ),
- "next_command": "repowise reindex" if result.generated_pages else None,
- },
- upgrade={
- "status": "pending" if _docs_mode != "llm" else "not_applicable",
- "retryable": _docs_mode != "llm",
- "completed_stages": [],
- "next_stage": "git_backfill" if run_mode == "fast" else "generation",
- },
- )
- # Record whether submodules were indexed so `repowise update` rebuilds
- # the graph with the same boundary semantics (same pattern as git_tier:
- # missing → False keeps legacy behavior for old state files).
- base_state["include_submodules"] = include_submodules
- if phase_timings:
- base_state["phase_timings"] = phase_timings
- # Cleared before it is set: ``base_state`` came from the previous run's
- # state.json, and a fixed re-run must not inherit its predecessor's
- # degradation report (see save_full_state_and_config for the same rule).
- base_state.pop("degraded", None)
- if run_warnings:
- base_state["degraded"] = run_warnings
- kg = getattr(result, "knowledge_graph_result", None)
- if kg is not None:
- base_state["knowledge_graph"] = build_kg_state(kg)
- save_knowledge_graph_json(repo_path, kg)
- if effective_index_only or provider is None:
- # Index-only mode skips save_config(); persist exclude_patterns/commit_limit here.
- # The embedder rides along now that this mode produces pages: without
- # it `repowise update` would re-resolve from the environment and could
- # start embedding, at a different width, a store this run deliberately
- # built with the mock.
- # ``embedding_model`` rides with it, the way save_config() writes the
- # pair: `serve` pins the model from it, and the store-format upgrade
- # check reads it to notice an embedder change. Half the pair is not
- # enough for either.
- from repowise.cli.providers.embedders import resolve_embedding_model
-
- save_config_partial(
- repo_path,
- exclude_patterns=exclude_patterns if exclude_patterns else None,
- commit_limit=resolved_commit_limit if commit_limit is not None else None,
- embedder=_index_only_embedder,
- embedding_model=(
- resolve_embedding_model(_index_only_embedder) if _index_only_embedder else None
- ),
- )
- # Fingerprint after config writes so the first update doesn't false-positive.
- base_state["config_fingerprint"] = config_fingerprint(repo_path)
- base_state["config_dependency_fingerprints"] = config_dependency_fingerprints(repo_path)
- # Index-only is the keyless default, so this is where most installs get
- # their stamp. Without it `health_analyzer_changed` reads absent-as-
- # unchanged and the version trigger never fires for them.
- base_state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION
- # Same reasoning for the security scanner (#3072): this run just
- # scanned every file, so start tracking its version here too.
- base_state["security_scanner_version"] = SECURITY_SCANNER_VERSION
- # The pages were just rendered by this release's structural renderer.
- # Unstamped, the first update would read the index as pre-stamp and
- # re-render the whole wiki it had only just written.
- from repowise.cli.commands.update_cmd.command import _current_renderer_fingerprint
-
- base_state["renderer_fingerprint"] = _current_renderer_fingerprint(repo_path)
- # This run just scored every file, so the periodic re-score cadence
- # starts now. Without the stamp the gate reads "never re-scored" and the
- # very next update re-scores the whole repo init had only just scored.
- #
- # Only when there really is a report. The health phase swallows its own
- # failures and returns None, and nothing is persisted for a None report,
- # so stamping there would suppress the first update's re-score - the
- # only thing that would have repopulated the missing rows. Same rule the
- # two update-side writers follow: they stamp only on a re-score that
- # returned True. None (no git) is left unstamped too: the gate cannot
- # fire without a head_ts either, so there is nothing to suppress.
- _head_ts = head_commit_ts(repo_path) if getattr(result, "health_report", None) else None
- if _head_ts is not None:
- base_state["last_full_rescore_at"] = _head_ts
- # Index-only still renders the full concept tree (deterministically, from
- # templates), so the store has the current capability — stamp the terminal
- # version rather than clamping it below the reindex gate and falsely
- # recommending a re-index of a store this run just built.
- save_state(repo_path, base_state, full_index=True)
-
- # ---- State + config (full mode only) ----
- if not effective_index_only and provider:
- save_full_state_and_config(
- repo_path=repo_path,
- result=result,
- provider=provider,
- phase_timings=phase_timings,
- degraded=run_warnings,
- embedder_name_resolved=embedder_name_resolved,
- exclude_patterns=exclude_patterns,
- commit_limit=commit_limit,
- resolved_commit_limit=resolved_commit_limit,
- resolved_reasoning=resolved_reasoning,
- max_file_pages=max_file_pages,
- include_submodules=include_submodules,
- save_key=save_key,
- )
-
- # Every store is final: store the views ``repowise next`` and the
- # dashboard read, before the editor files quote Fix first from them.
- refresh_read_snapshots(repo_path)
- files_written = write_editor_project_files(
- console,
- repo_path,
- options=editor_options,
- no_editor_setup=not editor_setup,
- )
- if editor_setup:
- # The index may carry a coverage ingest now; see ``sync_repo_hook``.
- from repowise.cli.commands.augment_cmd.coverage_reingest import sync_repo_hook
-
- sync_repo_hook(repo_path, console)
-
- _record_init_outcome(
- result=result,
- effective_index_only=effective_index_only,
- run_mode=run_mode,
- provider=provider,
- embedder_name_resolved=embedder_name_resolved,
- )
-
- # Post-commit auto-sync hook (both index-only and full modes)
- offer_hook_install(
- console,
- [repo_path],
- flag=hook,
- yes=yes,
- no_editor_setup=not editor_setup,
- )
-
- # Opt-in distill command-rewrite hook for Claude Code. The workspace flow
- # runs its own offer across all selected repos inside _workspace_init.
- offer_distill_rewrite_hook(
- console,
- [repo_path],
- distill_hook,
- yes=yes,
- no_editor_setup=not editor_setup,
- )
-
- # ---- Completion panel (last, so it reflects what setup actually did) ----
- # Snapshot the editor-setup state now that client registration and the two
- # hook offers above have run, so the "what's next" panel and MCP note react
- # to reality. `interactive` mirrors the offers' own gate: when False they
- # were skipped, so the panel is the only place their hooks surface.
- from repowise.cli.editor_setup import detect_editor_setup_outcome
-
- _setup_outcome = detect_editor_setup_outcome(
- repo_path,
- interactive=(sys.stdin.isatty() and not yes),
- first_index=_first_index,
- no_editor_setup=not editor_setup,
- )
- show_completion(
- repo_path=repo_path,
- result=result,
- start=start,
- effective_index_only=effective_index_only,
- run_mode=run_mode,
- provider=provider,
- setup=_setup_outcome,
- files_written=files_written,
- )
- # Raised last, so everything above is kept: pages, state and full-text
- # search are fine. Exiting 0 here is what let a scripted run record a
- # healthy semantic index that held no vectors.
- from repowise.cli.providers import embed_failure_message
-
- _embed_error = embed_failure_message(
- _scope_embedder, getattr(result, "embed_failed_pages", 0)
- )
- if _embed_error:
- raise click.ClickException(_embed_error)
+ # A declined cost gate or a missing provider persists like index-only.
+ run.effective_index_only = run.opts.index_only or run.cost_declined or run.no_provider
+ persist_index(run)
+ catch_up_savings(run.repo_path)
+ save_run_config(run)
+ register_clients(run)
+ write_run_state(run)
+ complete_setup(run)
+ raise_on_embed_failure(run)
diff --git a/tests/unit/cli/test_coverage_cmd.py b/tests/unit/cli/test_coverage_cmd.py
index c140e3b35..4a29a6c21 100644
--- a/tests/unit/cli/test_coverage_cmd.py
+++ b/tests/unit/cli/test_coverage_cmd.py
@@ -340,7 +340,7 @@ def test_init_and_update_keep_the_repo_hook_in_step(
import inspect
from repowise.cli.commands.augment_cmd import coverage_reingest
- from repowise.cli.commands.init_cmd import command as init_command
+ from repowise.cli.commands.init_cmd import _finish as init_finish
from repowise.cli.commands.update_cmd import command as update_command
calls: list = []
@@ -350,4 +350,4 @@ def test_init_and_update_keep_the_repo_hook_in_step(
)
update_command._refresh_editor_stamp(tmp_path, None)
assert calls == [tmp_path]
- assert "sync_repo_hook(repo_path, console)" in inspect.getsource(getattr(init_command.init_command, "callback", init_command.init_command))
+ assert "sync_repo_hook(repo_path, console)" in inspect.getsource(init_finish._write_editor_files)
diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.py
index b0ea1ec85..0546ca65a 100644
--- a/tests/unit/cli/test_editor_setup.py
+++ b/tests/unit/cli/test_editor_setup.py
@@ -1327,8 +1327,10 @@ def test_workspace_generation_rebinds_opencode_provider_to_repo(
def test_init_command_uses_editor_option_abstraction() -> None:
- source = inspect.getsource(init_cmd.init_command.callback) + inspect.getsource(
- init_cmd._workspace_init
+ source = (
+ inspect.getsource(init_cmd.command._editor_options)
+ + inspect.getsource(init_cmd._finish._write_editor_files)
+ + inspect.getsource(init_cmd._workspace_init)
)
assert "resolve_editor_setup_options" in source
diff --git a/tests/unit/cli/test_health_rescore_gate.py b/tests/unit/cli/test_health_rescore_gate.py
index 537adaa96..7f77ea9bb 100644
--- a/tests/unit/cli/test_health_rescore_gate.py
+++ b/tests/unit/cli/test_health_rescore_gate.py
@@ -149,7 +149,7 @@ class TestInitStampsTheCadence:
@pytest.mark.parametrize(
"module_name",
[
- "repowise.cli.commands.init_cmd.command",
+ "repowise.cli.commands.init_cmd._finish",
"repowise.cli.commands.init_cmd.persistence",
],
)
diff --git a/tests/unit/precedent/test_environment_fact_gate.py b/tests/unit/precedent/test_environment_fact_gate.py
index f5e5ab972..d5b1eab79 100644
--- a/tests/unit/precedent/test_environment_fact_gate.py
+++ b/tests/unit/precedent/test_environment_fact_gate.py
@@ -36,6 +36,6 @@ def test_only_the_local_init_command_opts_in() -> None:
if "derive_environment_facts=True" in py.read_text(encoding="utf-8", errors="ignore")
}
assert opted_in == {
- "repowise/cli/commands/init_cmd/command.py",
+ "repowise/cli/commands/init_cmd/_ingest.py",
"repowise/cli/commands/init_cmd/workspace.py",
}, opted_in