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(status): status and state.json describe the index the last command left (#4241)

Raghav Chamadiyaffe2252e203e
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 52011afc2..45f385961 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -189,7 +189,7 @@ All three reach the indexing knobs; the LLM-only knobs appear only when model-wr
| `--no-seed` | Disable worktree auto-seeding and run a full init even inside a linked worktree. |
| `--yes` / `-y` | Skip confirmation prompts |
| `--dry-run` | Show the generation plan and cost estimate. Writes no wiki |
-| `--test-run` | Generate docs for only the top 10 files (by PageRank) |
+| `--test-run` | Write docs with the model for only the top 10 files (by PageRank). Not with `--no-prose` or `--mode fast` |
| `--all` | In multi-repo mode, index every detected repo without prompting |
| `--no-workspace` | Force single-repo mode even when invoked from a workspace root (indexes only the target PATH instead of fanning out across workspace repos) |
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
index 07a94a656..b76252317 100644
--- a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
@@ -37,7 +37,7 @@ from repowise.core.cost_estimator import STRUCTURAL_PAGE_TYPES
from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
from repowise.core.generation.page_selection import PageSelectionIntent
-from .engine import run_scoped_generation
+from .engine import NO_DOCUMENTATION_MESSAGE, has_documentation, run_scoped_generation
def _build_intent(
@@ -83,6 +83,25 @@ def _reject_structural_page_ids(page_ids: tuple[str, ...]) -> None:
)
+def _dry_run_provider(
+ provider_name: str | None, model: str | None, repo_path: Path, reasoning: str | None
+) -> Any | None:
+ """The configured provider for a ``--dry-run``, or ``None`` when there is none.
+
+ A dry run never prompts and never needs a key; without a provider it prints
+ the plan without a price.
+ """
+ try:
+ return resolve_provider_or_prompt(
+ provider_name, model, repo_path, reasoning=reasoning, interactive=False
+ )
+ except click.ClickException as exc:
+ # Only "nothing configured" is keyless; a broken provider is a real error.
+ if getattr(exc, "reason", None) != "no_provider_configured":
+ raise
+ return None
+
+
def _make_gate(dry_run: bool):
"""Return the ``gate_cost`` callback the engine invokes before generating.
@@ -96,6 +115,17 @@ def _make_gate(dry_run: bool):
from repowise.cli.commands.init_cmd.generation import cost_gate_blocks, format_cost
from repowise.core.cost_estimator import estimate_cost
+ if provider is None:
+ est = estimate_cost(cost_plans, "none", "", repo_path=repo_path)
+ tokens = est.estimated_input_tokens + est.estimated_output_tokens
+ console.print(
+ f"Writing [bold]{est.total_pages}[/bold] pages, about [bold]{tokens:,}[/bold] "
+ "tokens. No model is configured, so there is no price; pass "
+ "[cyan]--provider[/cyan] to price it."
+ )
+ console.print("[dim]Dry run, nothing generated.[/dim]")
+ return False
+
est = None
try:
est = estimate_cost(
@@ -112,7 +142,7 @@ def _make_gate(dry_run: bool):
)
if dry_run:
- console.print("[dim]Dry run — nothing generated.[/dim]")
+ console.print("[dim]Dry run, nothing generated.[/dim]")
return False
if est is not None and cost_gate_blocks(est, yes=yes, message=" Generate at this cost?"):
@@ -227,25 +257,34 @@ def generate_command(
page_ids=page_ids,
)
- # Provider is required since a model writes these pages. On a real terminal, a
- # missing one drops into init's provider + key prompt and persists the choice,
- # so a first `generate` onboards the same way init does instead of dying.
- # Onboarding needs a terminal on both ends: a terminal stdout (so the provider
- # table renders) and a tty stdin (so the answer can be read). The stdin check
- # keeps a background hook / CI / agent run from hanging even when it inherits a
- # FORCE_COLOR that makes console.is_terminal report True; those keep the clean
- # "No provider configured" error. Unlike the bare-run default above, this fires
- # even with explicit page flags, so a keyless `generate --all` still onboards,
- # not just a bare `generate`.
- can_prompt_provider = console.is_terminal and sys.stdin.isatty() and not yes
- provider = resolve_provider_or_prompt(
- provider_name, model, repo_path, reasoning=reasoning, interactive=can_prompt_provider
- )
+ # Checked first: with nothing to write, a missing key is not the reason.
+ if not run_async(has_documentation(repo_path)):
+ console.print(NO_DOCUMENTATION_MESSAGE)
+ return
- console.print(
- f"[bold]repowise generate[/bold] — {repo_path}\n"
- f"Provider: [cyan]{provider.provider_name}[/cyan] / [cyan]{provider.model_name}[/cyan]"
- )
+ if dry_run:
+ provider = _dry_run_provider(provider_name, model, repo_path, reasoning)
+ else:
+ # Provider is required since a model writes these pages. On a real terminal, a
+ # missing one drops into init's provider + key prompt and persists the choice,
+ # so a first `generate` onboards the same way init does instead of dying.
+ # Onboarding needs a terminal on both ends: a terminal stdout (so the provider
+ # table renders) and a tty stdin (so the answer can be read). The stdin check
+ # keeps a background hook / CI / agent run from hanging even when it inherits a
+ # FORCE_COLOR that makes console.is_terminal report True; those keep the clean
+ # "No provider configured" error. Unlike the bare-run default, this fires
+ # even with explicit page flags, so a keyless `generate --all` still onboards,
+ # not just a bare `generate`.
+ can_prompt_provider = console.is_terminal and sys.stdin.isatty() and not yes
+ provider = resolve_provider_or_prompt(
+ provider_name, model, repo_path, reasoning=reasoning, interactive=can_prompt_provider
+ )
+
+ console.print(f"[bold]repowise generate[/bold] {repo_path}")
+ if provider is not None:
+ console.print(
+ f"Provider: [cyan]{provider.provider_name}[/cyan] / [cyan]{provider.model_name}[/cyan]"
+ )
from repowise.core.generation import GenerationConfig
@@ -299,7 +338,7 @@ def generate_command(
if outcome is None:
return # nothing generated, dry run, or declined — messaging already printed
- _write_state(repo_path, state, provider, outcome)
+ _write_state(repo_path, state, provider, outcome, embedder=embedder_name)
_report_outcome(outcome, time.monotonic() - start)
if embedder_upgraded:
@@ -409,19 +448,45 @@ def _reembed_after_upgrade(repo_path: Path, embedder_name: str) -> None:
console.print(f"[yellow]Re-embedding failed:[/yellow] {exc}\n{tail}")
-def _write_state(repo_path: Path, state: dict, provider: Any, outcome: Any) -> None:
- """Persist the post-run state: page count, provider, and docs mode.
+def _write_state(
+ repo_path: Path,
+ state: dict,
+ provider: Any,
+ outcome: Any,
+ *,
+ embedder: str | None = None,
+) -> None:
+ """Persist the post-run state: page count, provider, docs mode and scope.
docs_mode flips to ``llm`` only once no template page remains — a partial
upgrade leaves a mixed wiki, so it keeps its current mode rather than
over-claiming that everything is written.
"""
+ from repowise.core.index_scope import stamp_index_scope
+
head = get_head_commit(repo_path)
if head is not None:
state["last_sync_commit"] = head
state["total_pages"] = outcome.total_pages
state["provider"] = provider.provider_name
state["model"] = provider.model_name
- if outcome.remaining_template_pages == 0 and resolve_docs_mode(state) != "llm":
+ all_written = outcome.remaining_template_pages == 0
+ if all_written and resolve_docs_mode(state) != "llm":
state.update(docs_mode_state_fields("llm"))
+ provider_block = {
+ "name": provider.provider_name,
+ "model": provider.model_name,
+ "model_cost_possible": True,
+ }
+ if embedder is not None:
+ provider_block["embedder"] = embedder
+ # The model upgrade this index was waiting on is what this run did; the
+ # pages still unwritten are named by the report, not by a pending upgrade.
+ stamp_index_scope(
+ state,
+ load_config(repo_path),
+ content_provenance="model" if all_written else "mixed",
+ provider=provider_block,
+ upgrade={"status": "not_applicable", "retryable": False, "next_stage": None},
+ )
save_state(repo_path, state)
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py b/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py
index 3b3379802..08b9eeb28 100644
--- a/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py
@@ -45,6 +45,44 @@ def _narrow_to_model_written(plan: ScopePlan) -> ScopePlan:
return replace(plan, generate_ids=gen, stale_ids=stale, cost_plans=build_cost_plans(gen))
+NO_DOCUMENTATION_MESSAGE = (
+ "[yellow]This repo has no documentation yet.[/yellow] "
+ "Run `repowise init --no-prose` or `repowise update --full` first."
+)
+
+
+async def has_documentation(repo_path: Path) -> bool:
+ """Whether the index holds any page, checked before a provider is resolved.
+
+ A repo with nothing to write against should hear that, not a missing-key
+ error. Unreadable stores answer True so the full run reports the real error.
+ """
+ from sqlalchemy import func, select
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.cli.helpers import db_configured, get_db_url_for_repo
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.crud import get_repository_by_path
+ from repowise.core.persistence.models import Page
+
+ if not (repo_path / ".repowise" / "wiki.db").exists() and not db_configured():
+ return False
+ engine = create_engine(get_db_url_for_repo(repo_path))
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ return False
+ count = await session.execute(
+ select(func.count()).select_from(Page).where(Page.repository_id == repo.id)
+ )
+ return bool(count.scalar_one())
+ except (OSError, SQLAlchemyError):
+ return True
+ finally:
+ await engine.dispose()
+
+
@dataclass
class GenerateOutcome:
"""What a generate run produced, for the command's state write + report."""
@@ -133,10 +171,7 @@ async def run_scoped_generation(
include_nested_repos=bool(state.get("include_nested_repos", False)),
)
if rehydrated is None:
- console.print(
- "[yellow]This repo has no wiki pages yet.[/yellow] "
- "Run `repowise init --no-prose` or `repowise update --full` first."
- )
+ console.print(NO_DOCUMENTATION_MESSAGE)
return None
console.print(
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 3a925682a..f09a6441f 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
@@ -16,6 +16,7 @@ from repowise.cli.helpers import (
console,
get_head_commit,
head_commit_ts,
+ load_config,
load_state,
run_async,
save_config_partial,
@@ -166,6 +167,7 @@ def _stamp_scope(run: InitRun, base_state: dict[str, Any], docs_mode: str) -> No
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)),
+ test_run=run.opts.test_run and docs_mode == "llm",
file_pages={
"configured_cap": run.max_file_pages,
**(
@@ -299,6 +301,19 @@ def write_run_state(run: InitRun) -> None:
include_submodules=opts.include_submodules,
save_key=opts.save_key,
)
+ _stamp_test_run(run)
+
+
+def _stamp_test_run(run: InitRun) -> None:
+ """Record ``--test-run`` on the model path, which re-reads state from disk.
+
+ Stamped every run, so a whole-repo init clears an earlier sample's mark.
+ """
+ from repowise.core.index_scope import stamp_index_scope
+
+ state = load_state(run.repo_path)
+ stamp_index_scope(state, load_config(run.repo_path), test_run=run.opts.test_run)
+ save_state(run.repo_path, state, full_index=True)
def _record_init_outcome(run: InitRun) -> None:
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 1b8c48ab3..c7b686d0e 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
@@ -144,4 +144,10 @@ def resolve_structural_flags(opts: InitOptions) -> InitOptions:
# git tier to ESSENTIAL.
if opts.run_mode == "fast":
index_only = True
+ # --test-run caps what a model writes; a run with no model has nothing to cap.
+ if opts.test_run and index_only:
+ raise click.UsageError(
+ "--test-run limits the model run to the top 10 files, and --no-prose "
+ "or --mode fast runs no model. Drop --test-run, or use --prose."
+ )
return replace(opts, index_only=index_only)
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 7ce234916..ee2ad669a 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -22,6 +22,7 @@ from repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS
from repowise.core.generation.languages import SUPPORTED_LANGUAGES
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 ._finish import (
catch_up_savings,
@@ -186,7 +187,10 @@ def _run_workspace_init(opts: InitOptions, scan: Any) -> None:
"--test-run",
is_flag=True,
default=False,
- help="Limit generation to top 10 files by PageRank for quick validation.",
+ help=(
+ "Limit the model run to the top 10 files by PageRank for quick validation. "
+ "Needs a model, so not with --no-prose or --mode fast."
+ ),
)
@click.option(
"--prose/--no-prose",
@@ -481,6 +485,11 @@ def init_command(**params: Any) -> None:
if len(scan.repos) == 1 and scan.repos[0].path != repo_path:
repo_path = scan.repos[0].path
+ with init_in_progress(repo_path):
+ _run_single_repo(opts, repo_path, start)
+
+
+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):
return
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 e6676818e..4eef06a03 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -632,6 +632,7 @@ def _stamp_repo_scope(
git_tier=state["git_tier"],
git_commit_cap=ctx.resolved_commit_limit,
dropped_files=dropped_files_scope(getattr(result, "traversal_stats", None)),
+ test_run=ctx.test_run and docs_mode == "llm",
file_pages={"configured_cap": configured_cap, **_file_page_fields(result, configured_cap)},
analysis={
"unavailable": unavailable,
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index e4ca70ba0..5c388b356 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -326,6 +326,57 @@ def _query_health_line(repo_path: Path) -> str | None:
)
+#: The resume command an interrupted ``init`` leaves for the user.
+_RESUME_COMMAND = "repowise init --resume"
+
+
+def _incomplete_index(repo_path: Path, state: dict) -> dict | None:
+ """Why the index is unfinished, or ``None``.
+
+ A live ``init`` holds its lock for the whole run. Without one, ``init``
+ writes state.json last, with ``index_scope`` (and ``last_sync_commit`` in a
+ git repo), so persisted graph rows without either are a run that stopped
+ before it finished.
+ """
+ from datetime import datetime
+
+ from repowise.core.update_lock import read_init_lock
+
+ lock = read_init_lock(repo_path)
+ if lock is not None:
+ started = datetime.fromtimestamp(lock["started_at"], UTC).isoformat()
+ return {"reason": "running", "started_at": started, "next_command": "repowise status"}
+ finished = state.get("last_sync_commit") or "index_scope" in state
+ if finished or not _query_repo_counts(repo_path)[0]:
+ return None
+ return {"reason": "interrupted", "next_command": _RESUME_COMMAND}
+
+
+def _incomplete_line(incomplete: dict) -> str:
+ """The "Next" line for an index that is still running or was interrupted."""
+ command = f"[bold]{incomplete['next_command']}[/bold]"
+ if incomplete["reason"] == "running":
+ started = _format_relative_time(incomplete["started_at"])
+ return (
+ f"[bold]Next:[/bold] Index in progress (started {started}). "
+ f"Wait for it to finish, then run {command}."
+ )
+ return f"[bold]Next:[/bold] Index incomplete (interrupted). Run {command}."
+
+
+def _shows_upgrade_row(scope: dict) -> bool:
+ """Whether the "Full upgrade" row says something the rest of status does not.
+
+ A finished index built from code stores ``pending`` for the optional model
+ run; the keyless note under the table already names that command, and a
+ bare "pending" reads as unfinished work.
+ """
+ status = scope["upgrade"]["status"]
+ if status in ("unknown", "not_applicable", "complete"):
+ return False
+ return not (status == "pending" and scope["content_provenance"] == "template")
+
+
def _load_actions(repo_path: Path) -> dict | None:
"""The stored next-actions view, or ``None``; never raises (see ``next_cmd``)."""
try:
@@ -632,6 +683,7 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
storage_bytes = _index_storage_bytes(repowise_dir)
db_path = repowise_dir / "wiki.db"
has_db = db_path.exists() or db_configured()
+ incomplete = _incomplete_index(repo_path, state)
if fmt == "json":
counts, total_db_tokens = (
@@ -641,12 +693,14 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
{
"repo": str(repo_path),
"indexed": True,
+ "incomplete": incomplete,
"state": {
"last_sync_commit": state.get("last_sync_commit"),
"total_pages": state.get("total_pages", 0),
"provider": state.get("provider"),
"model": state.get("model"),
- "total_tokens": state.get("total_tokens", 0),
+ # The live rows, as the table shows: only init stamps state's.
+ "total_tokens": total_db_tokens if counts else state.get("total_tokens", 0),
"storage_bytes": storage_bytes,
},
"database_found": has_db,
@@ -718,7 +772,9 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
)
if scope["analysis"]["skipped"]:
state_table.add_row("Intentionally skipped", ", ".join(scope["analysis"]["skipped"]))
- if scope["upgrade"]["status"] not in ("unknown", "not_applicable", "complete"):
+ if scope["test_run"]:
+ state_table.add_row("Test run", "documentation covers the top 10 files only")
+ if _shows_upgrade_row(scope):
state_table.add_row("Full upgrade", scope["upgrade"]["status"])
console.print(state_table)
@@ -753,7 +809,10 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
console.print()
console.print(health_line)
- next_lines = _next_actions_lines(_load_actions(repo_path))
+ if incomplete is not None:
+ next_lines = [_incomplete_line(incomplete)]
+ else:
+ next_lines = _next_actions_lines(_load_actions(repo_path))
if next_lines:
console.print()
for line in next_lines:
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index 25339290c..3b7d8813d 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -987,6 +987,7 @@ def _finish_upgrade_state(
git_commit_cap=(commit_limit if isinstance(commit_limit, int) else _DEFAULT_COMMIT_LIMIT),
git_history_coverage=outcome["git_history_coverage"],
file_pages=outcome["file_pages"],
+ test_run=False,
analysis={"unavailable": [], "skipped": []},
upgrade=state["full_upgrade"],
provider=dict(provider_block),
diff --git a/packages/core/src/repowise/core/index_scope.py b/packages/core/src/repowise/core/index_scope.py
index 4310df701..9f160966f 100644
--- a/packages/core/src/repowise/core/index_scope.py
+++ b/packages/core/src/repowise/core/index_scope.py
@@ -176,6 +176,8 @@ def resolve_index_scope(
else None
),
"dropped_files": _dropped_files(scope.get("dropped_files")),
+ # ``init --test-run``: the model wrote documentation for a sample of files.
+ "test_run": scope.get("test_run") if isinstance(scope.get("test_run"), bool) else None,
"file_pages": {
"configured_cap": configured_cap,
"effective_cap": _number(pages.get("effective_cap")),
diff --git a/packages/core/src/repowise/core/pipeline/_run/analysis.py b/packages/core/src/repowise/core/pipeline/_run/analysis.py
index 0f7de0b0f..ce5a67b0c 100644
--- a/packages/core/src/repowise/core/pipeline/_run/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/_run/analysis.py
@@ -45,7 +45,7 @@ def _limit_test_run(run: PipelineRun) -> None:
run.parsed_files, run.graph_builder, n=TEST_RUN_FILE_LIMIT
)
if run.progress:
- run.progress.on_message("warning", f"Test run: limiting to {len(run.parsed_files)} files")
+ run.progress.on_message("notice", f"Test run: limiting to {len(run.parsed_files)} files")
async def _rehydrate_analysis(run: PipelineRun) -> bool:
diff --git a/packages/core/src/repowise/core/pipeline/phases/generation.py b/packages/core/src/repowise/core/pipeline/phases/generation.py
index eaa7c1426..f611a5d57 100644
--- a/packages/core/src/repowise/core/pipeline/phases/generation.py
+++ b/packages/core/src/repowise/core/pipeline/phases/generation.py
@@ -113,7 +113,7 @@ async def run_generation(
if test_run:
parsed_files = limit_to_top_pagerank(parsed_files, graph_builder, n=TEST_RUN_FILE_LIMIT)
if progress:
- progress.on_message("warning", f"Test run: limiting to {len(parsed_files)} files")
+ progress.on_message("notice", f"Test run: limiting to {len(parsed_files)} files")
# Resolve embedder and vector store
embedder_impl = embedder if embedder is not None else KeylessEmbedder()
diff --git a/packages/core/src/repowise/core/update_lock.py b/packages/core/src/repowise/core/update_lock.py
index b71eb00ab..918589e9a 100644
--- a/packages/core/src/repowise/core/update_lock.py
+++ b/packages/core/src/repowise/core/update_lock.py
@@ -14,11 +14,16 @@ import json
import os
import threading
import time
+from collections.abc import Iterator
from pathlib import Path
from typing import Any
UPDATE_LOCK_FILENAME = ".update.lock"
+#: Held for the length of an ``init``, so ``status`` can tell a run still
+#: going from one that was killed. Advisory: it never blocks anything.
+INIT_LOCK_FILENAME = ".init.lock"
+
# Wall-clock ceiling, applied only when the owner's liveness cannot be
# established: no PID in the payload (legacy writer) or a probe that could not
# decide. A lock this old whose owner we cannot find is treated as abandoned.
@@ -266,3 +271,27 @@ def format_lock_age(age: float | None) -> str:
return f"for {int(age / 60)}m"
return f"for {age / 3600:.1f}h"
+
+def _init_lock_path(repo_path: Path) -> Path:
+ return Path(repo_path) / ".repowise" / INIT_LOCK_FILENAME
+
+
+def init_in_progress(repo_path: Path) -> Iterator[None]:
+ """Mark an ``init`` as running for its duration; released on any exit.
+
+ A killed process leaves the file behind, and :func:`read_init_lock` reads
+ a dead or recycled owner as absent, so a stale mark means "interrupted".
+ """
+ path = _init_lock_path(repo_path)
+ held = _try_acquire_lock_at(path, None) is None
+ try:
+ yield
+ finally:
+ if held:
+ _release_lock_at(path)
+
+
+def read_init_lock(repo_path: Path) -> dict[str, Any] | None:
+ """The running ``init``'s lock payload, or ``None`` when no live one holds it."""
+ return _read_lock_at(_init_lock_path(repo_path))
diff --git a/tests/unit/cli/test_status_state_truth.py b/tests/unit/cli/test_status_state_truth.py
new file mode 100644
index 000000000..0f286ee1e
--- /dev/null
+++ b/tests/unit/cli/test_status_state_truth.py
@@ -0,0 +1,234 @@
+"""``status`` and state.json describe the index the last command left behind."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import click
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands import status_cmd
+from repowise.cli.commands.generate_cmd import command as generate_cmd
+from repowise.cli.main import cli
+from repowise.core.index_scope import resolve_index_scope
+
+
+def _status(tmp_path: Path, monkeypatch, state: dict, *, files: int = 0, fmt: str = "table"):
+ repowise_dir = tmp_path / ".repowise"
+ repowise_dir.mkdir()
+ (repowise_dir / "wiki.db").write_bytes(b"")
+ if state:
+ (repowise_dir / "state.json").write_text(json.dumps(state))
+
+ async def _pages(_path):
+ return {"module_page": 2}, 1125
+
+ monkeypatch.setattr(status_cmd, "_query_pages", _pages)
+ monkeypatch.setattr(status_cmd, "_query_repo_counts", lambda _path: (files, 0))
+ monkeypatch.setattr(status_cmd, "_query_health", lambda _path: None)
+ monkeypatch.setattr(status_cmd, "_query_health_line", lambda _path: None)
+ monkeypatch.setattr(status_cmd, "_load_actions", lambda _path: None)
+ args = [str(tmp_path), "--no-workspace", "--format", fmt]
+ result = CliRunner().invoke(status_cmd.status_command, args, terminal_width=200)
+ assert result.exit_code == 0, result.output
+ return result.output
+
+
+class TestInterruptedInit:
+ def test_rows_without_a_finished_state_say_resume(self, tmp_path, monkeypatch) -> None:
+ out = _status(tmp_path, monkeypatch, {}, files=40)
+ assert "Next: Index incomplete (interrupted). Run repowise init --resume." in out
+
+ def test_json_names_the_reason_and_the_command(self, tmp_path, monkeypatch) -> None:
+ data = json.loads(_status(tmp_path, monkeypatch, {}, files=40, fmt="json"))
+ assert data["incomplete"] == {
+ "reason": "interrupted",
+ "next_command": "repowise init --resume",
+ }
+
+ def test_a_finished_index_is_not_incomplete(self, tmp_path, monkeypatch) -> None:
+ state = {"last_sync_commit": "abc", "docs_mode": "llm"}
+ data = json.loads(_status(tmp_path, monkeypatch, state, files=40, fmt="json"))
+ assert data["incomplete"] is None
+
+ def test_a_finished_index_outside_git_is_not_incomplete(self, tmp_path, monkeypatch) -> None:
+ state = {"last_sync_commit": None, "index_scope": {"run_mode": "standard"}}
+ assert "interrupted" not in _status(tmp_path, monkeypatch, state, files=40)
+
+ def test_a_live_init_reads_as_running_not_interrupted(self, tmp_path, monkeypatch) -> None:
+ from repowise.core.update_lock import init_in_progress
+
+ (tmp_path / ".repowise").mkdir()
+ with init_in_progress(tmp_path):
+ monkeypatch.setattr(status_cmd, "_query_repo_counts", lambda _p: (40, 0))
+ incomplete = status_cmd._incomplete_index(tmp_path, {})
+ line = status_cmd._incomplete_line(incomplete)
+ assert incomplete["reason"] == "running"
+ assert "Index in progress (started " in line
+ assert "Wait for it to finish, then run [bold]repowise status[/bold]." in line
+ assert not (tmp_path / ".repowise" / ".init.lock").exists()
+
+ def test_a_dead_inits_lock_reads_as_interrupted(self, tmp_path, monkeypatch) -> None:
+ import time
+
+ from repowise.core import procutils
+
+ lock = tmp_path / ".repowise" / ".init.lock"
+ lock.parent.mkdir()
+ lock.write_text(json.dumps({"pid": 999_999, "started_at": time.time()}))
+ monkeypatch.setattr(procutils, "pid_alive", lambda _pid: False)
+ monkeypatch.setattr(status_cmd, "_query_repo_counts", lambda _p: (40, 0))
+ assert status_cmd._incomplete_index(tmp_path, {})["reason"] == "interrupted"
+
+ def test_an_empty_store_is_not_an_interrupted_run(self, tmp_path, monkeypatch) -> None:
+ assert "interrupted" not in _status(tmp_path, monkeypatch, {}, files=0)
+
+
+def _scope_state(provenance: str, upgrade: dict, **extra) -> dict:
+ return {
+ "last_sync_commit": "abc",
+ "index_scope": {"content_provenance": provenance, "upgrade": upgrade, **extra},
+ }
+
+
+class TestUpgradeRow:
+ def test_a_finished_index_built_from_code_has_no_pending_upgrade(
+ self, tmp_path, monkeypatch
+ ) -> None:
+ state = _scope_state("template", {"status": "pending", "next_stage": "generation"})
+ assert "Full upgrade" not in _status(tmp_path, monkeypatch, state)
+
+ def test_an_index_only_run_still_shows_its_pending_upgrade(
+ self, tmp_path, monkeypatch
+ ) -> None:
+ state = _scope_state("none", {"status": "pending", "next_stage": "git_backfill"})
+ assert "Full upgrade" in _status(tmp_path, monkeypatch, state)
+
+ def test_a_failed_upgrade_is_always_shown(self, tmp_path, monkeypatch) -> None:
+ state = _scope_state("template", {"status": "failed"})
+ assert "Full upgrade" in _status(tmp_path, monkeypatch, state)
+
+
+def test_json_total_tokens_match_the_page_rows(tmp_path, monkeypatch) -> None:
+ data = json.loads(_status(tmp_path, monkeypatch, {"last_sync_commit": "abc"}, fmt="json"))
+ assert data["state"]["total_tokens"] == data["page_tokens"] == 1125
+
+
+def test_a_test_run_is_named_in_status(tmp_path, monkeypatch) -> None:
+ state = _scope_state("model", {"status": "not_applicable"}, test_run=True)
+ assert "documentation covers the top 10 files only" in _status(tmp_path, monkeypatch, state)
+
+
+def test_test_run_survives_resolve_and_junk_reads_as_unknown() -> None:
+ assert resolve_index_scope({"index_scope": {"test_run": True}})["test_run"] is True
+ assert resolve_index_scope({"index_scope": {"test_run": "yes"}})["test_run"] is None
+ assert resolve_index_scope({})["test_run"] is None
+
+
+class TestGenerateRestampsScope:
+ def _write(self, monkeypatch, state: dict, remaining: int) -> dict:
+ monkeypatch.setattr(generate_cmd, "get_head_commit", lambda _p: "head")
+ monkeypatch.setattr(generate_cmd, "save_state", lambda _p, _s: None)
+ monkeypatch.setattr(generate_cmd, "load_config", lambda _p: {})
+ outcome = SimpleNamespace(total_pages=28, remaining_template_pages=remaining)
+ provider = SimpleNamespace(provider_name="mock", model_name="mock-1")
+ generate_cmd._write_state(Path("."), state, provider, outcome, embedder="mock")
+ return resolve_index_scope(state)
+
+ def _template_state(self) -> dict:
+ return {
+ "docs_mode": "deterministic",
+ "index_scope": {
+ "content_provenance": "template",
+ "provider": {"name": None, "embedder": "mock"},
+ "upgrade": {"status": "pending", "retryable": True, "next_stage": "generation"},
+ },
+ }
+
+ def test_every_page_written_reads_as_written_by_the_model(self, monkeypatch) -> None:
+ scope = self._write(monkeypatch, self._template_state(), remaining=0)
+ assert scope["content_provenance"] == "model"
+ assert scope["provider"]["name"] == "mock"
+ assert scope["provider"]["model"] == "mock-1"
+ assert scope["upgrade"]["status"] == "not_applicable"
+
+ def test_pages_left_unwritten_read_as_mixed(self, monkeypatch) -> None:
+ scope = self._write(monkeypatch, self._template_state(), remaining=2)
+ assert scope["content_provenance"] == "mixed"
+ assert scope["upgrade"]["status"] == "not_applicable"
+
+
+class TestGenerateChecksOrder:
+ def test_no_documentation_is_reported_before_a_missing_key(
+ self, tmp_path, monkeypatch
+ ) -> None:
+ async def _none(_path):
+ return False
+
+ def _no_provider(*_a, **_k):
+ raise click.ClickException("No provider configured.")
+
+ monkeypatch.setattr(generate_cmd, "load_state", lambda _p: {"run_mode": "fast"})
+ monkeypatch.setattr(generate_cmd, "has_documentation", _none)
+ monkeypatch.setattr(generate_cmd, "resolve_provider_or_prompt", _no_provider)
+ result = CliRunner().invoke(cli, ["generate", str(tmp_path), "--dry-run"])
+ assert result.exit_code == 0, result.output
+ assert "no documentation yet" in result.output
+ assert "No provider configured" not in result.output
+
+ def test_a_keyless_dry_run_needs_no_provider(self, monkeypatch) -> None:
+ from repowise.cli.errors import reasoned_error
+
+ def _no_provider(*_a, **_k):
+ raise reasoned_error("No provider configured.", reason="no_provider_configured")
+
+ monkeypatch.setattr(generate_cmd, "resolve_provider_or_prompt", _no_provider)
+ resolved = generate_cmd._dry_run_provider(None, None, Path("."), None)
+ assert resolved is None
+
+ def test_a_broken_provider_still_errors(self, monkeypatch) -> None:
+ def _bad(*_a, **_k):
+ raise click.ClickException("Could not set up the provider.")
+
+ monkeypatch.setattr(generate_cmd, "resolve_provider_or_prompt", _bad)
+ with pytest.raises(click.ClickException):
+ generate_cmd._dry_run_provider(None, None, Path("."), None)
+
+ def test_the_unpriced_plan_states_pages_and_tokens(self, monkeypatch, tmp_path) -> None:
+ import io
+
+ from rich.console import Console
+
+ from repowise.core.cost_estimator import PageTypePlan
+
+ buf = io.StringIO()
+ monkeypatch.setattr(generate_cmd, "console", Console(file=buf, width=200))
+ plans = [PageTypePlan(page_type="module_page", count=3, level=0)]
+ proceed = generate_cmd._make_gate(True)(plans, None, tmp_path, yes=False, dry_run=True)
+ assert proceed is False
+ out = buf.getvalue()
+ assert "Writing 3 pages, about" in out and "tokens" in out
+ assert "no price" in out
+
+
+class TestInitTestRun:
+ @pytest.mark.parametrize("flags", [["--no-prose"], ["--mode", "fast"]])
+ def test_a_run_with_no_model_rejects_test_run(self, tmp_path, flags) -> None:
+ result = CliRunner().invoke(
+ cli, ["init", str(tmp_path), "--test-run", "--no-editor-setup", *flags]
+ )
+ assert result.exit_code == 2
+ assert "--test-run limits the model run" in result.output
+
+ @pytest.mark.parametrize("test_run", [True, False])
+ def test_a_model_init_stamps_the_test_run(self, tmp_path, test_run) -> None:
+ from repowise.cli.commands.init_cmd import _finish
+ from repowise.cli.helpers import load_state, save_state
+
+ save_state(tmp_path, {"index_scope": {"test_run": not test_run}})
+ run = SimpleNamespace(repo_path=tmp_path, opts=SimpleNamespace(test_run=test_run))
+ _finish._stamp_test_run(run)
+ assert resolve_index_scope(load_state(tmp_path))["test_run"] is test_run