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.

feat(cli): make init --index-only produce a complete wiki, no key, no spend (#975)

Raghav Chamadiyab0df7eb72976
diff --git a/README.md b/README.md
index 471e4a381..b1cce3420 100644
--- a/README.md
+++ b/README.md
@@ -110,10 +110,10 @@ queryable from the CLI, the MCP tools, and the local dashboard.
| **◈ Decisions** | Architectural decisions mined from eight sources, evidence-backed, linked to the graph nodes they govern, connected by supersedes / refines / conflicts_with, tracked for staleness | **★ Captured nowhere else** |
| **★ Code health** | **25 deterministic markers**, 1 to 10 per file · three signals: defect risk · maintainability · performance · coverage ingestion · concrete refactoring plans (Extract Class / Helper, Move Method, Break Cycle, Split File) · **zero LLM, under 30s** | **★ Defect-validated, with the fix attached** |
-Only the Docs layer needs an LLM. `repowise init --index-only` builds the graph,
-git, decision, and health layers with no API key and no spend (seven of the eight
-decision sources are deterministic; only the one harvested during doc generation
-needs a provider).
+Only model-written prose needs an LLM. `repowise init --index-only` builds the
+graph, git, decision, and health layers with no API key and no spend, and renders
+the whole wiki from the code's structure (seven of the eight decision sources are
+deterministic; only the one harvested during doc generation needs a provider).
Full detail on every layer: **[docs/layers/INTELLIGENCE_LAYERS.md →](docs/layers/INTELLIGENCE_LAYERS.md)**
@@ -341,8 +341,17 @@ repowise init --index-only -y
```
That builds the dependency graph, git history, code-health scores and dead-code
-findings in seconds. Want the generated wiki and semantic search too? Use `repowise
-init --provider gemini|anthropic|openai` with the matching key.
+findings in seconds, and renders a complete wiki from the code's structure: file,
+module, layer and cycle pages, the architecture diagram, the repo overview, API
+and infra pages, and the onboarding collection. Every page carries a footer saying
+it was derived from structure, and the repo overview describes composition, entry
+points, clusters and dependencies rather than what the project does end to end,
+because no template can derive that. Full-text search works on this index;
+semantic search needs an embedder configured (Ollama is the keyless option).
+
+Want the wiki written by a model instead? Use `repowise init --provider
+gemini|anthropic|openai` with the matching key, or upgrade an existing index later
+with `repowise update --full`.
**3. Connect your agent.** The MCP server is `repowise mcp`, served from the repo directory.
@@ -378,8 +387,10 @@ repo"*, or *"`get_context` for `src/auth.py`"*. You get graph-grounded architect
per-file triage instead of a flurry of greps.
> `get_overview` and `get_context` work in index-only mode with no key, synthesized
-> from the graph, git and health layers. `search_codebase`, `get_answer` and `get_why`
-> need full mode (the generated wiki).
+> from the graph, git and health layers. `search_codebase` and `get_answer` read the
+> wiki, which index-only mode does build, but they answer from pages rendered from
+> structure rather than model-written prose, and `search_codebase` is full-text only
+> until you configure an embedder.
Full walkthrough: **[docs/start/QUICKSTART.md →](docs/start/QUICKSTART.md)**
@@ -496,7 +507,7 @@ Doing a security review? **[docs/business/SECURITY_COMPLIANCE.md →](docs/busin
## CLI
```bash
-repowise init [PATH] # index a codebase (one-time; --index-only skips the LLM)
+repowise init [PATH] # index a codebase (one-time; --index-only needs no LLM)
repowise serve [PATH] # MCP server + local dashboard
repowise update [PATH] # incremental update (seconds; --workspace for every repo)
repowise watch # auto-sync daemon, re-index on file change
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 4faf3b73e..f219a6997 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -45,18 +45,18 @@ repowise init .
1. **Ingestion**, walks every file, parses AST with tree-sitter, builds a two-tier dependency graph (file + symbol nodes), indexes git history (churn, hotspots, ownership, bus factor)
2. **Analysis**, detects dead code, extracts architectural decisions from inline markers, READMEs, and git history. Runs Leiden community detection and execution flow tracing.
-3. **Generation**, sends structured prompts to the LLM, generates file-level, module-level, and repo-level wiki pages
+3. **Generation**, generates file-level, module-level, and repo-level wiki pages, either by prompting the LLM or, with `--index-only`, by rendering them from the parsed structure
4. **Persistence**, stores everything in `.repowise/wiki.db`, builds search indexes, generates editor instruction files, registers MCP server and hooks
In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (co-changes, contracts, package deps), workspace CLAUDE.md generation.
**Interactive modes.** Running a bare `repowise init` on a TTY (no `--provider`, `--index-only`, or `--yes`) opens a menu:
-1. **Everything**, index + AI docs. After picking a provider you can answer **"Customize?"** to tune any setting before the run.
-2. **Index only**, graph, git, code health, dead code; no LLM, no cost. Answer **"Customize indexing?"** to set exclude patterns, commit limit, skip-tests/infra, submodules, and fast mode.
-3. **Advanced**, full control. First choose **"Generate AI docs?"**; the prompts then split into an **Indexing** section (always) and a **Generation** section (provider, concurrency, embedder, wiki style, onboarding, decision harvesting, tiering, only when docs are on).
+1. **Everything**, index + model-written docs. After picking a provider you can answer **"Customize?"** to tune any setting before the run.
+2. **Index only**, the same layers plus a wiki rendered from structure; no LLM, no key, no cost. Answer **"Customize indexing?"** to set exclude patterns, commit limit, skip-tests/infra, submodules, and fast mode.
+3. **Advanced**, full control. First choose **"Generate model-written wiki docs?"**; the prompts then split into an **Indexing** section (always) and a **Generation** section (provider, concurrency, embedder, wiki style, onboarding, decision harvesting, tiering, only when model-written docs are on).
-All three reach the indexing knobs; the LLM-only knobs appear only when docs are enabled. Passing any of the flags below (or `--yes`) skips the menu and runs non-interactively.
+All three reach the indexing knobs; the LLM-only knobs appear only when model-written docs are enabled. Passing any of the flags below (or `--yes`) skips the menu and runs non-interactively.
**Options:**
@@ -65,8 +65,8 @@ All three reach the indexing knobs; the LLM-only knobs appear only when docs are
| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `kimi`, `ollama`, `litellm`, `codex_cli`, `opencode`, `mock` |
| `--model` | Model name override (e.g., `claude-sonnet-4-6`) |
| `--embedder` | Embedder for semantic search: `gemini`, `openai`, `openrouter`, `ollama`, `mock` (default: auto-detect) |
-| `--index-only` | Skip LLM generation. Only parse, build graph, and index git. Free. |
-| `--mode` | Pipeline depth: `standard` (default) or `fast` (graph + essential-git only, no per-file blame/co-change, no LLM, for very large repos; upgrade later with `update --full`) |
+| `--index-only` | No LLM calls, no API key, no spend. Parses, builds the graph, indexes git, and renders the whole wiki from that structure: file, module, layer and cycle (SCC) pages, the architecture diagram, the repo overview, API and infra pages, and the onboarding collection. Symbol spotlight pages are skipped, since the file pages already carry that content. Every page footer says it was derived from structure, and the repo overview covers composition, entry points, clusters and dependencies rather than what the project does end to end. Full-text search works; semantic search needs an embedder. Upgrade to model-written prose later with `update --full`, or restyle with `restyle`. |
+| `--mode` | Pipeline depth: `standard` (default) or `fast` (graph + essential-git only, no per-file blame/co-change, no LLM docs, for very large repos; upgrade later with `update --full`) |
| `--skip-tests` | Exclude test files from doc generation |
| `--skip-infra` | Exclude infrastructure files (Dockerfiles, Makefiles, Terraform) |
| `--exclude` / `-x` | Gitignore-style exclusion pattern. Repeatable. |
@@ -102,7 +102,7 @@ repowise init # interactive
repowise init --provider anthropic --yes # automated
repowise init --provider codex_cli --codex --yes # use authenticated Codex CLI
repowise init --provider opencode --yes # use local OpenCode CLI
-repowise init --index-only # free, no LLM
+repowise init --index-only # free, wiki rendered from structure
repowise init --dry-run # preview cost
repowise init --test-run # quick test (10 files)
repowise init --provider openai --model qwen3 --reasoning off
@@ -170,7 +170,7 @@ See [WORKTREES.md](../scale/WORKTREES.md).
**First-time indexing:** `update --workspace` runs full first-time indexing for workspace entries that have no `.repowise/` dir yet (previously skipped with `"not_indexed"`). The pipeline runs index-only, no LLM cost, and writes a state.json marker. Doc generation then follows on the next update once the repo has an index: pass `--docs` (or set its `docs_enabled`) and it regenerates pages like any other member.
-**Upgrading a fast index to full (`--full`):** a repo first indexed with `repowise init --mode fast` has the full dependency graph + metrics persisted, but only the *essential* git tier (last commits, no per-file blame or co-change) and no LLM docs. `repowise update --full` upgrades it **incrementally**: it backfills the git tier to FULL (per-file blame + repo-wide co-change) using a resumable, checkpointed worker, then generates the docs that fast mode skipped. Crucially, it **reuses the persisted graph**, the dependency graph is rehydrated from SQL rather than re-parsed and re-resolved, so the expensive import/call/heritage resolution and centrality computation the fast index already did are not repeated. This is measurably cheaper than re-running a full `init`. The backfill is resumable: if it is interrupted, re-running `repowise update --full` picks it up. A provider is required (the fast index made no LLM calls), so pass `--provider`/`--model` or have one configured. Single-repo only; it errors if run in workspace mode.
+**Upgrading a fast index to full (`--full`):** a repo first indexed with `repowise init --mode fast` has the full dependency graph + metrics persisted, but only the *essential* git tier (last commits, no per-file blame or co-change) and no LLM docs. `repowise update --full` upgrades it **incrementally**: it backfills the git tier to FULL (per-file blame + repo-wide co-change) using a resumable, checkpointed worker, then generates the docs that fast mode skipped. Crucially, it **reuses the persisted graph**, the dependency graph is rehydrated from SQL rather than re-parsed and re-resolved, so the expensive import/call/heritage resolution and centrality computation the fast index already did are not repeated. This is measurably cheaper than re-running a full `init`. The backfill is resumable: if it is interrupted, re-running `repowise update --full` picks it up. A provider is required (the fast index made no LLM calls), so pass `--provider`/`--model` or have one configured. It does not build the vector store, so run `repowise reindex` afterwards if you want semantic search. Single-repo only; it errors if run in workspace mode.
**Examples:**
diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index 451e488a5..23321c945 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -38,7 +38,14 @@ repowise init --index-only -y
This is the step worth doing first, because it costs nothing and answers the
question "is this useful on my codebase". It parses every file to an AST, builds
the dependency graph, reads your git history, scores every file for code health,
-and finds dead code. No LLM calls, no key, no network.
+and finds dead code. It also renders a complete wiki from that structure: file,
+module, layer and cycle pages, the architecture diagram, the repo overview, API
+and infra pages, and the onboarding collection. No LLM calls, no key, no network.
+
+Those pages are honest about where they came from. Each one ends with a footer
+saying it was derived from structure, and the repo overview covers composition,
+entry points, clusters and dependencies rather than what the project does end to
+end, because no template can derive that.
When it finishes you have a working index. Try it:
@@ -128,14 +135,16 @@ file reads. That is the whole point.
> **What works without a key:** `get_overview`, `get_context`, `get_symbol`,
> `get_risk`, `get_change_risk`, `get_dead_code` and `get_health` all synthesize
-> from the graph, git and health layers. `search_codebase`, `get_answer` and
-> `get_why` need the generated wiki, which is step 4.
+> from the graph, git and health layers. `search_codebase` and `get_answer` read
+> the wiki, which step 2 already built, so they answer from pages rendered from
+> structure. `search_codebase` is full-text only until you configure an embedder.
-## 4. Optional: add a provider for the wiki and semantic search
+## 4. Optional: add a provider for model-written prose
-Everything so far was deterministic. A provider adds the generated wiki (a
-documentation page per module and file), semantic search, architectural decision
-mining, and codebase chat.
+Everything so far was deterministic. A provider rewrites the wiki pages as prose
+and unlocks architectural decision mining and codebase chat. Semantic search is a
+separate step: configure an embedder and run `repowise reindex` to build the
+vector store.
```bash
export ANTHROPIC_API_KEY="sk-ant-..." # or OPENAI_API_KEY / GEMINI_API_KEY
@@ -156,7 +165,9 @@ Three ways to avoid paying a provider at all:
- **Fully local:** point it at Ollama with a local embedding model for zero
external calls. See [Config](../reference/CONFIG.md).
- **Stay in index-only mode.** The graph, git, health, risk and dead-code layers
- never needed a provider.
+ never needed a provider, and the wiki you already have was rendered without
+ one. Full-text search works on it; semantic search is the part that needs an
+ embedder, and Ollama is the keyless one.
## 5. Keep it in sync
diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.md
index 3297263e2..b6d138824 100644
--- a/docs/start/USER_GUIDE.md
+++ b/docs/start/USER_GUIDE.md
@@ -83,9 +83,12 @@ worse than no answer. Every MCP response carries the indexed commit and warns wh
it has diverged from your live `HEAD`, but the real fix is step 3.
**Two modes.** `--index-only` gives you the graph, git intelligence, code health,
-change risk and dead code, with no LLM, no key and no network. Adding a provider
-gives you the generated wiki, semantic search, decision mining and chat on top.
-You can start index-only and upgrade later without re-doing the parse.
+change risk and dead code, plus a complete wiki rendered from the code's
+structure, with no LLM, no key and no network. Adding a provider rewrites those
+pages as model-written prose and unlocks decision mining and chat. You can start
+index-only and upgrade later with `repowise update --full`, which reuses the
+persisted graph instead of re-parsing it. Semantic search is separate: it needs
+an embedder, and `repowise reindex` is what builds the vector store.
---
@@ -119,7 +122,7 @@ Grouped by what you are trying to do. Every flag for every command lives in the
| Command | What it is for |
|---|---|
-| `repowise init` | First index. Interactive: asks for a provider, shows a cost estimate, waits for confirmation. `--index-only` skips the LLM entirely. |
+| `repowise init` | First index. Interactive: asks for a provider, shows a cost estimate, waits for confirmation. `--index-only` builds the same wiki from structure, with no LLM. |
| `repowise update` | Incremental catch-up after pulling or committing. Seconds, not minutes. |
| `repowise watch` | File watcher that updates continuously while you work. |
| `repowise hook install` | Post-commit hook so syncing happens without you. |
@@ -273,10 +276,10 @@ the [Docker image](../../docker/README.md) if you would rather not install Node.
`Ctrl+K` / `Cmd+K` opens a command palette from any page, which is the fastest way
to move between views and repos.
-Views that need the generated wiki (Docs, Chat, parts of Overview) show thin
-content on an index-only repo. Everything else, including Architecture, Code
-Health, Files, Commits and Contributors, works off the parsed graph and git
-history alone.
+An index-only repo has a full Docs section, rendered from structure rather than
+written by a model, so the pages read as structural summaries. Chat still needs a
+provider. Everything else, including Architecture, Code Health, Files, Commits and
+Contributors, works off the parsed graph and git history alone.
Every view and what it answers: **[Dashboard](DASHBOARD.md)**.
@@ -293,7 +296,7 @@ repowise init --index-only -y # free, no key, seconds
repowise hook install # keep it current from here on
```
-Add the wiki and semantic search when you want them:
+Rewrite the wiki with a model and add semantic search when you want them:
```bash
export ANTHROPIC_API_KEY="sk-ant-..."
@@ -425,8 +428,8 @@ validate on 10 files, and `--skip-tests --skip-infra` to cut scope. Lower
`repowise reindex` rebuilds it from the existing wiki pages, with no LLM calls.
**Doctor reports 0 pages**
-Either init failed, or it ran with `--index-only`. Run `repowise init` with a
-provider to generate pages.
+init failed or was interrupted. Even `--index-only` writes pages, so an empty
+wiki means the run did not finish. Try `repowise init --resume`.
**Dashboard shows an empty repo list**
The backend and frontend have to point at the same database. Check `REPOWISE_DB_URL`
diff --git a/packages/api-client/src/types/repository.ts b/packages/api-client/src/types/repository.ts
index bd47231af..d7452cf7a 100644
--- a/packages/api-client/src/types/repository.ts
+++ b/packages/api-client/src/types/repository.ts
@@ -41,8 +41,14 @@ export interface RepoResponse {
workspace_alias?: string | null;
workspace_status?: "indexed" | "needs_index" | "missing_dir" | null;
is_primary?: boolean | null;
+ /** Whether any pages exist. `docs_mode` says who wrote them: "deterministic"
+ * pages are rendered from templates and can be upgraded to model-written
+ * ones. */
docs_enabled?: boolean | null;
+ docs_mode?: "none" | "deterministic" | "llm" | null;
docs_skip_reason?: string | null;
+ run_mode?: string | null;
+ git_tier?: string | null;
/** Set on POST /api/repos responses when the create enqueued the first
* index; attach to /api/jobs/{id}/stream with it. */
initial_job_id?: string | null;
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py b/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py
index 868312475..b4716d27f 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py
@@ -6,6 +6,8 @@ import contextlib
import json
from pathlib import Path
+from repowise.core.docs_mode import resolve_docs_mode
+
from ._shared import _find_repo_root
_GIT_COMMIT_PATTERNS = (
@@ -107,8 +109,7 @@ def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str |
return None
_record_warning(repo_path, head)
- docs_enabled = state.get("docs_enabled", True)
- artifact = "Wiki" if docs_enabled else "Index"
+ artifact = "Index" if resolve_docs_mode(state) == "none" else "Wiki"
return (
f"[repowise] {artifact} is stale — last indexed at commit "
f"{last_sync[:8]}, HEAD is now {head[:8]}. "
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 4a6ffb3e5..df735ecae 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -66,6 +66,7 @@ from repowise.cli.ui import (
quick_repo_scan,
should_offer_fast_mode,
)
+from repowise.core.docs_mode import docs_mode_state_fields
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
@@ -133,6 +134,76 @@ def _record_init_outcome(
return
+def _run_deterministic_generation_phase(
+ *,
+ repo_path: Path,
+ result: Any,
+ total_phases: int,
+ concurrency: int,
+ language: str,
+ onboarding: bool,
+ wiki_style: str,
+ embedder_name_resolved: str,
+ embedder_was_requested: bool,
+ resume: bool,
+) -> None:
+ """Render the whole wiki from templates, for ``init --index-only``.
+
+ Every page type has a deterministic renderer, so an index-only run is no
+ longer a wiki-less index: it is a complete wiki whose pages are derived
+ from structure rather than written by a model. There is nothing to
+ estimate and nothing to gate, since no provider is involved and the run
+ costs nothing, so this skips the coverage chooser the LLM phase runs.
+ """
+ from repowise.core.generation import GenerationConfig
+ from repowise.core.providers.llm.template import TemplateProvider
+
+ # This mode is sold as "no key, no spend", and embedding 2000+ pages
+ # through a hosted embedder is a real bill. ``resolve_embedder`` infers one
+ # from any LLM key it finds in the environment, which is the right default
+ # for a run that is already paying a model and the wrong one here: nobody
+ # who typed --index-only asked to be charged. So a hosted embedder is used
+ # only when the user named it, through --embedder or REPOWISE_EMBEDDER.
+ # Anything else falls back to the mock, which keeps full-text search
+ # working and leaves semantic search to be built later with
+ # ``repowise reindex``.
+ hosted = embedder_name_resolved not in ("mock", "ollama")
+ embedder = "mock" if hosted and not embedder_was_requested else embedder_name_resolved
+
+ print_phase_header(
+ console,
+ 3,
+ total_phases,
+ "Generation",
+ "Building wiki pages from the code's structure (no model, no cost)",
+ )
+ if embedder != embedder_name_resolved:
+ console.print(
+ f" [dim]Not embedding with [bold]{embedder_name_resolved}[/bold]: it was "
+ "inferred from a key in your environment, and this run is meant to cost "
+ "nothing. Pass [bold]--embedder "
+ f"{embedder_name_resolved}[/bold] if you want it.[/dim]"
+ )
+
+ gen_config = GenerationConfig(
+ deterministic=True,
+ max_concurrency=concurrency,
+ language=language,
+ enable_onboarding=onboarding,
+ wiki_style=wiki_style,
+ )
+ run_repo_generation(
+ repo_path=repo_path,
+ result=result,
+ provider=TemplateProvider(),
+ gen_config=gen_config,
+ concurrency=concurrency,
+ embedder_name_resolved=embedder_name_resolved,
+ resume=resume,
+ verbose=True,
+ )
+
+
def _run_generation_phase(
*,
repo_path: Path,
@@ -850,6 +921,14 @@ def init_command(
config["follow_renames"] = True
embedder_name_resolved = resolve_embedder(embedder_name)
+ # Whether the user actually asked for this embedder, as opposed to
+ # resolve_embedder inferring one from an LLM key it found lying around.
+ # The deterministic generation phase needs the distinction: it advertises
+ # itself as costing nothing, so it will not put a hosted embedder on the
+ # user's bill unless they named it.
+ embedder_was_requested = bool(embedder_name) or bool(
+ os.environ.get("REPOWISE_EMBEDDER", "").strip()
+ )
# ---- Resolve provider ----
provider = None
@@ -928,11 +1007,14 @@ def init_command(
console.print(" [green]✓[/green] Provider connection verified")
# ---- Phase 1 & 2: Ingestion + Analysis (always) ----
- total_phases = 3 if index_only else 4
+ # 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 state.docs_enabled
- # so subsequent updates default to index-only.
+ # the run isn't wasted, and propagate the choice to the persisted docs
+ # mode so subsequent updates default to index-only.
cost_declined = False
llm_client = provider if not index_only else decision_provider
@@ -1024,8 +1106,37 @@ def init_command(
# ---- Analysis summary (shown between analysis and generation) ----
show_analysis_summary(result)
- # ---- Phase 3: Generation (full mode only) ----
- if not index_only:
+ # ---- Phase 3: Generation ----
+ # 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:
+ _run_deterministic_generation_phase(
+ repo_path=repo_path,
+ result=result,
+ total_phases=total_phases,
+ concurrency=concurrency,
+ language=language,
+ onboarding=onboarding,
+ wiki_style=wiki_style,
+ embedder_name_resolved=embedder_name_resolved,
+ embedder_was_requested=embedder_was_requested,
+ resume=resume,
+ )
+ else:
gen_stop, cost_declined = _run_generation_phase(
repo_path=repo_path,
result=result,
@@ -1049,17 +1160,41 @@ def init_command(
)
if gen_stop:
return
+ if 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]"
+ )
+ _run_deterministic_generation_phase(
+ repo_path=repo_path,
+ result=result,
+ total_phases=total_phases,
+ concurrency=concurrency,
+ language=language,
+ onboarding=onboarding,
+ wiki_style=wiki_style,
+ # 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,
+ )
# ---- Persistence ----
# `cost_declined` short-circuits any further LLM work for the rest of
# this run, so persistence/state below treat it as index-only.
effective_index_only = index_only or cost_declined
- if effective_index_only:
- print_phase_header(console, 3, total_phases, "Persistence", "Saving to database")
- else:
- print_phase_header(
- console, 4, total_phases, "Persistence", "Saving to database and building search index"
- )
+ print_phase_header(
+ console,
+ total_phases,
+ total_phases,
+ "Persistence",
+ "Saving to database and building search index",
+ )
with console.status(" Persisting to database…", spinner=OWL_SPINNER):
run_async(persist_result(result, repo_path))
@@ -1112,7 +1247,21 @@ def init_command(
head = get_head_commit(repo_path)
base_state = load_state(repo_path)
base_state["last_sync_commit"] = head
- base_state["docs_enabled"] = not effective_index_only and provider is not None
+ # 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
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
index 06cc28809..998693e66 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
@@ -246,27 +246,34 @@ def run_repo_generation(
vector_store: Any = build_vector_store(repo_path, embedder_impl)
result.vector_store = vector_store
+ deterministic = bool(getattr(gen_config, "deterministic", False))
+
# Cost tracker backed by the real DB so every LLM call is persisted to the
# llm_costs table. Attached to the provider unconditionally (all providers
- # accept ``_cost_tracker`` as an attribute).
- cost_tracker = build_cost_tracker(repo_path, result.repo_name)
+ # accept ``_cost_tracker`` as an attribute). A deterministic run makes no
+ # calls, so it gets none: an empty ledger, not a ledger of zeroes.
+ cost_tracker = None if deterministic else build_cost_tracker(repo_path, result.repo_name)
provider._cost_tracker = cost_tracker
- if verbose:
+ if verbose and not deterministic:
console.print(
" [dim](each generated page is saved as it completes — safe to Ctrl-C, "
"then run 'repowise init --resume' to pick up where it stopped)[/dim]"
)
- with Progress(
+ # No cost column on a deterministic run: it would sit at $0.000 for the
+ # whole run, which reads as an unanswered question rather than an answer.
+ columns: list[Any] = [
SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
MaybeCountColumn(),
TimeElapsedColumn(),
- TextColumn("[green]${task.fields[cost]:.3f}[/green]"),
- console=console,
- ) as gen_progress:
+ ]
+ if not deterministic:
+ columns.append(TextColumn("[green]${task.fields[cost]:.3f}[/green]"))
+
+ with Progress(*columns, console=console) as gen_progress:
gen_callback = RichProgressCallback(gen_progress, console)
generated_pages = run_async(
run_generation_with_persistence(
@@ -308,13 +315,16 @@ def run_repo_generation(
if verbose:
console.print(f" [green]✓[/green] Generated [bold]{len(generated_pages)}[/bold] pages")
- _enrich_knowledge_graph(
- result=result,
- provider=provider,
- gen_config=gen_config,
- generated_pages=generated_pages,
- verbose=verbose,
- )
-
- flush_cost_tracker(cost_tracker)
+ # KG enrichment is layer naming and the guided tour, both pure prompting.
+ # A deterministic run has no model to ask, and the skeleton's structural
+ # layers stand on their own.
+ if not deterministic:
+ _enrich_knowledge_graph(
+ result=result,
+ provider=provider,
+ gen_config=gen_config,
+ generated_pages=generated_pages,
+ verbose=verbose,
+ )
+ flush_cost_tracker(cost_tracker)
return generated_pages
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
index fab4e0e13..7563d017f 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
@@ -21,6 +21,7 @@ from repowise.cli.helpers import (
save_state,
)
from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
+from repowise.core.docs_mode import docs_mode_state_fields
async def build_resume_controller(repo_path: Path, *, resume: bool) -> tuple[Any, Any]:
@@ -246,7 +247,7 @@ def save_full_state_and_config(
state["total_pages"] = run_async(_count_db_pages())
state["provider"] = provider.provider_name
state["model"] = provider.model_name
- state["docs_enabled"] = True
+ state.update(docs_mode_state_fields("llm"))
# Full-mode docs runs always index the FULL git tier.
state["run_mode"] = "standard"
state["git_tier"] = "full"
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
index ec9c9c543..06eb18ad0 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
@@ -163,10 +163,12 @@ def show_completion(
_lang_summary_final = str(len(result.languages))
if effective_index_only:
+ _template_pages = len(result.generated_pages or [])
metrics: list[tuple[str, str]] = [
("Files indexed", str(result.file_count)),
("Symbols", f"{result.symbol_count:,}"),
("Languages", _lang_summary_final),
+ ("Wiki pages", f"{_template_pages} rendered from structure"),
("Elapsed", format_elapsed(elapsed)),
("", ""),
(
@@ -198,17 +200,32 @@ def show_completion(
build_completion_panel("repowise index complete", metrics, next_steps=next_steps)
)
console.print()
+ # Fast mode reaches this branch too, and it generates nothing, so the
+ # note has to check rather than assume.
+ if result.generated_pages:
+ console.print(
+ " [dim]Every page is derived from structure and says so in its footer. "
+ "Full-text\n search works now; semantic search needs an embedder "
+ "(Ollama is the keyless one).[/dim]"
+ )
+ else:
+ console.print(
+ " [dim]No wiki pages: fast mode indexes the graph and git history only.\n"
+ " Re-run without [bold]--mode fast[/bold] to render the wiki from "
+ "structure.[/dim]"
+ )
+ console.print()
_render_defect_accuracy(result)
else:
_pages = result.generated_pages or []
total_tokens = sum(p.total_tokens for p in _pages)
- # Split AI-written from the zero-LLM deterministic coverage tail so broad
- # coverage reads as thoroughness, not padding.
+ # Split model-written from the zero-LLM deterministic coverage tail so
+ # broad coverage reads as thoroughness, not padding.
_det = sum(1 for p in _pages if getattr(p, "provider_name", "") == "template")
_ai = len(_pages) - _det
_pages_label = str(len(_pages))
if _det:
- _pages_label = f"{len(_pages)} ({_ai} AI-written · {_det} deterministic)"
+ _pages_label = f"{len(_pages)} ({_ai} model-written · {_det} from structure)"
metrics = [
("Pages generated", _pages_label),
("Total tokens", f"{total_tokens:,}"),
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 2c00b281f..3492f5b87 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -58,6 +58,7 @@ from repowise.cli.ui import (
load_dotenv,
print_banner,
)
+from repowise.core.docs_mode import docs_mode_state_fields
from repowise.core.generation.styles import DEFAULT_STYLE
from ._interactive import offer_distill_rewrite_hook, offer_hook_install
@@ -133,9 +134,9 @@ def _run_workspace_generation(
"[dim]Index will be saved without docs; "
"future `repowise update` runs default to index-only.[/dim]"
)
- # Sentinel — caller treats this exactly like an index-only run so
- # state.docs_enabled lands as False and the post-commit hook
- # doesn't surprise the user with LLM regen later.
+ # Sentinel: caller treats this exactly like an index-only run so the
+ # persisted docs mode is not "llm" and the post-commit hook doesn't
+ # surprise the user with LLM regen later.
raise CostGateDeclined()
return run_repo_generation(
@@ -264,7 +265,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt
index_only = ctx.index_only
# Generation phase (per-repo, only when not index-only).
- # Track per-repo whether the user declined cost so state.docs_enabled
+ # Track per-repo whether the user declined cost so the persisted docs mode
# reflects the actual choice instead of the original init mode.
repo_docs_enabled = not index_only and provider is not None
skip_reason: str | None = None
@@ -329,7 +330,9 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt
state: dict[str, Any] = {
"last_sync_commit": head,
"total_pages": pages_count,
- "docs_enabled": repo_docs_enabled,
+ # Workspace init has no template fallback yet, so a repo that skipped
+ # generation really does end up with no pages at all.
+ **docs_mode_state_fields("llm" if repo_docs_enabled else "none"),
}
if repo_docs_enabled and provider is not None:
state["provider"] = provider.provider_name
diff --git a/packages/cli/src/repowise/cli/commands/restyle_cmd.py b/packages/cli/src/repowise/cli/commands/restyle_cmd.py
index 200abbde6..46ce876f9 100644
--- a/packages/cli/src/repowise/cli/commands/restyle_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/restyle_cmd.py
@@ -33,6 +33,7 @@ from repowise.cli.helpers import (
save_state,
)
from repowise.cli.ui import load_dotenv
+from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
from repowise.core.generation.styles import (
DEFAULT_STYLE,
is_known_style,
@@ -195,14 +196,22 @@ def restyle_command(
# classifier) records as a usage_error rather than an error.
raise click.BadArgumentUsage(f"Unknown style '{style}'. Choose one of: {valid}.")
- # Restyle only makes sense for a full index (one that has generated docs).
+ # Restyle only makes sense once there are pages to restyle.
if not state:
raise click.ClickException(f"No index found at {repo_path}. Run `repowise init` first.")
- if not state.get("docs_enabled", False):
+ docs_mode = resolve_docs_mode(state)
+ if docs_mode == "none":
raise click.ClickException(
- "This repo is index-only (no wiki pages to restyle). "
+ "This repo has no wiki pages to restyle. "
"Run `repowise update --full` to generate docs first."
)
+ if docs_mode == "deterministic":
+ # A template wiki is a legitimate starting point, not a dead end:
+ # restyling it is how a user upgrades to model-written pages.
+ console.print(
+ "[yellow]This repo's wiki was rendered from templates.[/yellow] "
+ "Restyling rewrites every page with a model, which costs money."
+ )
if style == current:
console.print(f"[yellow]Already using the '{style}' style.[/yellow]")
@@ -254,6 +263,9 @@ def restyle_command(
head = get_head_commit(repo_path)
state["last_sync_commit"] = head
+ # A restyle rewrites every page with a model, so a template wiki stops
+ # being one here. Without this, `update` keeps defaulting to index-only.
+ state.update(docs_mode_state_fields("llm"))
state["total_pages"] = len(generated_pages)
state["config_fingerprint"] = config_fingerprint(repo_path)
save_state(repo_path, state)
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 79d9e247f..8f5af8ebc 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -19,6 +19,7 @@ from repowise.cli.helpers import (
run_async,
)
from repowise.cli.ui.brand import format_bytes
+from repowise.core.docs_mode import resolve_docs_mode
# ---------------------------------------------------------------------------
# Workspace status
@@ -293,15 +294,18 @@ def _workspace_status(target: CommandTarget) -> None:
indexed_ago = _format_relative_time(entry.indexed_at)
page_count = _query_page_count(abs_path)
storage_cell = format_bytes(_index_storage_bytes(repowise_dir))
- docs_state = load_state(abs_path)
- docs_enabled = docs_state.get("docs_enabled")
+ docs_mode = resolve_docs_mode(load_state(abs_path))
- # Render the Docs column in plain English so the user instantly
- # knows whether the LLM-generated wiki exists for this repo.
+ # Render the Docs column in plain English so the user instantly knows
+ # both whether a wiki exists and whether a model wrote it. A template
+ # wiki is complete but thinner, and `restyle` upgrades it.
if page_count > 0:
- docs_cell = f"[green]{page_count}[/green]"
- elif docs_enabled is False:
- docs_cell = "[yellow]skipped[/yellow]"
+ if docs_mode == "deterministic":
+ docs_cell = f"[cyan]{page_count} Template[/cyan]"
+ else:
+ docs_cell = f"[green]{page_count} LLM[/green]"
+ elif docs_mode == "none":
+ docs_cell = "[yellow]None[/yellow]"
no_docs.append(entry.alias)
else:
docs_cell = "[yellow]0[/yellow]"
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/update_cmd/__init__.py
index fc322f5d0..9034d8dec 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/__init__.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/__init__.py
@@ -16,7 +16,7 @@ from .incremental import (
_rebuild_graph_and_git,
_run_partial_analysis,
)
-from .mode import _infer_legacy_docs_enabled, _resolve_index_only_mode
+from .mode import _resolve_index_only_mode
from .persistence import (
_git_metadata_to_dict,
_persist_incremental_commits,
@@ -32,7 +32,6 @@ __all__ = [
"_build_repo_graph",
"_build_update_vector_store",
"_git_metadata_to_dict",
- "_infer_legacy_docs_enabled",
"_persist_incremental_commits",
"_persist_index_only_update",
"_persist_partial_health",
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index ac561d291..45f250f97 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -38,6 +38,7 @@ from repowise.cli.helpers import (
try_acquire_update_lock,
write_update_pending,
)
+from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
from repowise.core.reasoning import REASONING_MODES
from .incremental import (
@@ -46,7 +47,7 @@ from .incremental import (
_refresh_knowledge_graph,
_run_partial_analysis,
)
-from .mode import _infer_legacy_docs_enabled, _resolve_index_only_mode
+from .mode import _resolve_index_only_mode
from .persistence import (
_persist_index_only_update,
_run_full_health_rescore,
@@ -222,7 +223,7 @@ def _surface_release_news(*, written_by: str | None) -> None:
"Override the persisted init mode for this run. --no-docs is "
"equivalent to --index-only; --docs forces LLM page regeneration "
"even when the repo was indexed without docs. Without either flag, "
- "the value of `docs_enabled` from .repowise/state.json is used "
+ "the value of `docs_mode` from .repowise/state.json is used "
"(set during `repowise init`)."
),
)
@@ -232,10 +233,11 @@ def _surface_release_news(*, written_by: str | None) -> None:
is_flag=True,
default=False,
help=(
- "Upgrade a fast (`--mode fast`) index to a full one: backfill the git "
- "tier ESSENTIAL -> FULL and generate the LLM docs that fast mode "
- "skipped. Incremental — reuses the persisted graph instead of "
- "re-parsing and re-resolving it. Single-repo only."
+ "Upgrade an index with a model: backfill the git tier ESSENTIAL -> "
+ "FULL if it was built with `--mode fast`, and write the pages with a "
+ "provider, replacing a template wiki from `--index-only`. Incremental: "
+ "reuses the persisted graph instead of re-parsing and re-resolving it. "
+ "Single-repo only."
),
)
@click.option(
@@ -597,11 +599,11 @@ def run_update(
atexit.register(release_update_lock, repo_path)
atexit.register(clear_update_queued, repo_path)
- # Backfill docs_enabled on legacy state files using the same
- # shape-based inference the resolver uses, so the post-commit hook
- # and future runs stop relying on the inference. Done before mode
- # resolution and only when no explicit override was passed, so a
- # one-off `--docs` / `--no-docs` doesn't lock anything in.
+ # Backfill the docs mode on legacy state files using the same inference
+ # the resolver uses, so the post-commit hook and future runs stop relying
+ # on the inference. Done before mode resolution and only when no explicit
+ # override was passed, so a one-off `--docs` / `--no-docs` doesn't lock
+ # anything in.
explicit_override = (
# The CLI default of index_only is False; treat it like an
# override only when the user actually passed the flag, which we
@@ -609,8 +611,8 @@ def run_update(
# index_only=True is always treated as an override.
index_only or docs_flag is not None
)
- if "docs_enabled" not in state and not explicit_override:
- state["docs_enabled"] = _infer_legacy_docs_enabled(state)
+ if "docs_mode" not in state and not explicit_override:
+ state.update(docs_mode_state_fields(resolve_docs_mode(state)))
save_state(repo_path, state)
# --- Resolve effective mode (index-only vs full LLM regen) ---
@@ -851,8 +853,8 @@ def run_update(
)
# Resolve the generation provider. If the repo wants docs but was never
- # given a provider/key (e.g. it started --index-only and later flipped
- # docs_enabled on, or `repowise update --docs`), onboard the same way init
+ # given a provider/key (e.g. it started --index-only and later asked for
+ # LLM docs, or `repowise update --docs`), onboard the same way init
# does: prompt for provider + key and persist, but only in an interactive
# terminal. Hooks / CI / --progress json keep the clean non-blocking error.
# In the workspace docs flow each member reaches this per-repo run; the
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/mode.py b/packages/cli/src/repowise/cli/commands/update_cmd/mode.py
index 4a0e6fa31..58a98b6f5 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/mode.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/mode.py
@@ -2,21 +2,7 @@
from __future__ import annotations
-
-def _infer_legacy_docs_enabled(state: dict) -> bool:
- """Infer ``docs_enabled`` for state files written before the field existed.
-
- Pre-migration ``init`` only wrote ``provider`` / ``model`` to state when
- docs were generated; index-only init wrote nothing past ``last_sync_commit``.
- So absence of both fields is a reliable signal that the original run was
- index-only and we should default new updates to index-only too — this
- avoids surprising those users with a full LLM regen on first upgrade.
- Full-init users keep the old default (full mode) because their state
- has ``provider`` and ``model`` populated.
- """
- if state.get("provider") or state.get("model"):
- return True
- return False
+from repowise.core.docs_mode import resolve_docs_mode
def _resolve_index_only_mode(
@@ -27,10 +13,13 @@ def _resolve_index_only_mode(
) -> bool:
"""Decide whether this update should skip LLM regeneration.
- Priority: explicit ``--index-only`` flag > ``--docs/--no-docs`` >
- ``state.docs_enabled`` > inferred default from legacy state shape.
- Encapsulated as a pure function so the post-commit hook does the right
- thing without needing any extra knobs at install time.
+ Priority: explicit ``--index-only`` flag > ``--docs/--no-docs`` > the
+ persisted docs mode. Encapsulated as a pure function so the post-commit
+ hook does the right thing without needing any extra knobs at install time.
+
+ Only an ``llm`` repo defaults to a full update. A ``deterministic`` one has
+ no provider configured, so defaulting it to full would either fail or bill
+ a user who never asked for a model.
"""
if index_only:
return True
@@ -38,8 +27,4 @@ def _resolve_index_only_mode(
return True
if docs_flag is True:
return False
- # No explicit override — read state, falling back to a shape-based
- # inference for state files predating the docs_enabled field.
- if "docs_enabled" in state:
- return state["docs_enabled"] is False
- return _infer_legacy_docs_enabled(state) is False
+ return resolve_docs_mode(state) != "llm"
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
index d1a1840d8..78cfa2d83 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
@@ -34,7 +34,7 @@ def _workspace_update(
over how the workspace was located (auto-detected vs explicit flag).
Each stale repo resolves its own docs-vs-index-only mode the same way a
- single-repo update does, from its persisted ``docs_enabled`` plus any
+ single-repo update does, from its persisted docs mode plus any
``--docs`` / ``--no-docs`` / ``--index-only`` override passed here. Repos
that want docs are updated through the full single-repo docs path (so
their wiki pages, diagrams, and decisions stay as current as they would
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index cbb4701c5..2f7cf651e 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -41,6 +41,7 @@ from repowise.cli.helpers import (
run_async,
save_state,
)
+from repowise.core.docs_mode import docs_mode_state_fields
def _reparse(repo_path: Path, exclude_patterns: list[str]) -> tuple[list[Any], dict[str, bytes], Any]:
@@ -372,9 +373,9 @@ def upgrade_to_full(
)
# Flip persisted state to full so subsequent `repowise update` runs the
- # normal incremental LLM path (docs_enabled) rather than offering upgrade.
+ # normal incremental LLM path rather than offering upgrade.
state["last_sync_commit"] = head
- state["docs_enabled"] = True
+ state.update(docs_mode_state_fields("llm"))
state["git_tier"] = "full"
state["total_pages"] = len(generated_pages)
save_state(repo_path, state)
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index ff387d571..00b843677 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -17,6 +17,7 @@ from repowise.cli.helpers import (
resolve_repo_path,
run_async,
)
+from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
if TYPE_CHECKING:
from repowise.core.workspace.config import WorkspaceConfig
@@ -573,7 +574,9 @@ def _run_index_for_repo(
state: dict = {
"last_sync_commit": head,
"total_pages": generated_pages,
- "docs_enabled": bool(generate_docs and provider is not None),
+ # No template fallback on this path: without a provider the added repo
+ # is indexed with no pages at all.
+ **docs_mode_state_fields("llm" if generate_docs and provider is not None else "none"),
}
if generate_docs and provider is not None:
state["provider"] = provider.provider_name
@@ -608,7 +611,7 @@ def _run_index_for_repo(
# Honest completion notice — exact remediation command for the
# docs-skipped case.
- if not state["docs_enabled"]:
+ if resolve_docs_mode(state) == "none":
reason = docs_skip_reason or "docs disabled"
console.print(f"\n[yellow]Note:[/yellow] '{alias}' indexed without docs ({reason}).")
console.print(
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index d898579bd..bb2424f24 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -736,7 +736,7 @@ def resolve_provider_or_prompt(
provider/key is configured and ``interactive`` is set (an interactive
terminal, not a hook / CI / ``--progress json`` run), reuse init's exact
provider + API-key prompt, persist the choice, and retry — so a docs run
- that only just gained ``docs_enabled`` onboards the same way ``init`` does
+ that only just asked for LLM pages onboards the same way ``init`` does
instead of dying with "No provider configured".
When ``interactive`` is False the original error propagates unchanged, so
diff --git a/packages/cli/src/repowise/cli/ui/mode_selection.py b/packages/cli/src/repowise/cli/ui/mode_selection.py
index 50ee4b269..ea1ae677d 100644
--- a/packages/cli/src/repowise/cli/ui/mode_selection.py
+++ b/packages/cli/src/repowise/cli/ui/mode_selection.py
@@ -79,9 +79,10 @@ def interactive_mode_select(console: Console) -> str:
body.append(" [2]", style=BRAND_STYLE)
body.append(" Index only ", style="bold")
- body.append("(no LLM, no cost)\n", style="dim")
- body.append(" Same minus the AI docs: graph, git history, code health,\n")
- body.append(" dead code. Great for MCP agents; add docs anytime later.\n\n")
+ body.append("(no key, no spend)\n", style="dim")
+ body.append(" Same layers, and a complete wiki rendered from the code's\n")
+ body.append(" structure instead of written by a model. Upgrade it to\n")
+ body.append(" model-written prose later with update --full.\n\n")
body.append(" [3]", style=BRAND_STYLE)
body.append(" Advanced\n", style="bold")
@@ -115,10 +116,10 @@ def interactive_generate_docs_toggle(console: Console) -> bool:
"""
console.print()
console.print(
- " [dim]AI docs call the LLM (has a cost). Indexing — dependency graph, "
- "git history,\n code health, dead code — is always free.[/dim]"
+ " [dim]Model-written docs call the LLM (has a cost). Say no and you still "
+ "get a wiki,\n rendered from the code's structure, for free.[/dim]"
)
- return click.confirm(" Generate AI wiki docs?", default=True)
+ return click.confirm(" Generate model-written wiki docs?", default=True)
def interactive_customize_offer(console: Console, *, generate_docs: bool) -> bool:
@@ -570,6 +571,9 @@ def print_index_only_intro(console: Console, has_provider: bool = False) -> None
" [green]✓[/] Index git history (hotspots, ownership, co-changes)",
" [green]✓[/] Detect dead code",
" [green]✓[/] Extract architectural decisions",
+ " [green]✓[/] Render the wiki from structure: file, module, layer and",
+ " cycle pages, the architecture diagram, the repo overview, API and",
+ " infra pages, and the onboarding collection",
" [green]✓[/] Set up MCP server for AI assistants",
]
if has_provider:
@@ -577,7 +581,12 @@ def print_index_only_intro(console: Console, has_provider: bool = False) -> None
" [green]✓[/] [dim]Decision extraction enhanced (provider key detected)[/dim]"
)
lines.append("")
- lines.append(" [dim]No LLM calls. No cost.[/dim]")
+ lines.append(" [dim]No LLM calls. No API key. No cost.[/dim]")
+ lines.append(
+ " [dim]Every page says it was derived from structure. Run "
+ "[bold]repowise update --full[/bold][/dim]"
+ )
+ lines.append(" [dim]later to rewrite the wiki with a model.[/dim]")
console.print(
Panel(
diff --git a/packages/cli/src/repowise/cli/ui/result_panels.py b/packages/cli/src/repowise/cli/ui/result_panels.py
index 31ddff667..39f03df48 100644
--- a/packages/cli/src/repowise/cli/ui/result_panels.py
+++ b/packages/cli/src/repowise/cli/ui/result_panels.py
@@ -138,7 +138,7 @@ def build_contextual_next_steps(
# graph, hotspots, dead code, and decisions are easier to browse than
# via the CLI.
steps.append(("repowise serve", "launch the dashboard at http://localhost:3000"))
- steps.append(("repowise init --provider gemini", "generate full documentation"))
+ steps.append(("repowise update --full", "rewrite the wiki with a model (needs a key)"))
else:
steps.append(("repowise mcp .", "start MCP server for AI assistants"))
steps.append(("repowise search <query>", "search the generated wiki"))
diff --git a/packages/core/src/repowise/core/docs_mode.py b/packages/core/src/repowise/core/docs_mode.py
new file mode 100644
index 000000000..233eff534
--- /dev/null
+++ b/packages/core/src/repowise/core/docs_mode.py
@@ -0,0 +1,71 @@
+"""How a repo's wiki was produced: not at all, from templates, or by a model.
+
+``.repowise/state.json`` used to answer that with ``docs_enabled: bool``, which
+was enough while there were only two outcomes. Since ``init --index-only``
+started rendering a full wiki from templates there are three, and a boolean
+collapses two of them: an index-only repo has docs, they just are not written.
+
+The field is ``docs_mode``. ``docs_enabled`` is still written alongside it as a
+derived legacy value for one release, so an older CLI or server reading a newer
+state file keeps working. Read through :func:`resolve_docs_mode`, which
+understands every state shape that has existed.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal, Mapping
+
+__all__ = ["DOCS_MODES", "DocsMode", "docs_mode_state_fields", "resolve_docs_mode"]
+
+DocsMode = Literal["none", "deterministic", "llm"]
+
+DOCS_MODES: tuple[DocsMode, ...] = ("none", "deterministic", "llm")
+
+
+def resolve_docs_mode(state: Mapping[str, Any] | None) -> DocsMode:
+ """Return the docs mode recorded in *state*, across all state generations.
+
+ Three shapes exist in the wild:
+
+ - ``docs_mode`` present: use it.
+ - ``docs_enabled`` present but no ``docs_mode``: written between the two
+ migrations. True meant a model wrote the pages, because templates were
+ not an option yet.
+ - Neither present: predates both. Index-only runs wrote nothing past
+ ``last_sync_commit``, so a populated ``provider`` / ``model`` is the
+ signal that generation actually happened.
+
+ A repo indexed before this change reports ``none`` rather than
+ ``deterministic``, which is correct: it has no pages. Re-running ``init``
+ or ``update`` gives it the deterministic wiki.
+ """
+ if not state:
+ return "none"
+
+ mode = state.get("docs_mode")
+ if mode in DOCS_MODES:
+ return mode # type: ignore[return-value]
+
+ enabled = state.get("docs_enabled")
+ if enabled is None:
+ enabled = bool(state.get("provider") or state.get("model"))
+ return "llm" if enabled else "none"
+
+
+def docs_mode_state_fields(mode: DocsMode) -> dict[str, Any]:
+ """Return the state.json fields recording *mode*.
+
+ Both are written. ``docs_enabled`` is False for ``deterministic``, even
+ though such a repo does have pages, because of what the older reader does
+ with the answer rather than what the field's name suggests. The consumer
+ that matters is the pre-migration ``repowise update``, which read
+ ``docs_enabled is False`` as "do not regenerate with a model". A
+ deterministic repo has no provider configured, so an older CLI or an
+ already-installed post-commit hook seeing True would launch a full LLM
+ regeneration and die on a missing provider, which is the exact failure the
+ field was introduced to prevent. False keeps that reader doing the safe
+ thing; new readers ask ``resolve_docs_mode`` and get the whole truth.
+ """
+ if mode not in DOCS_MODES:
+ raise ValueError(f"unknown docs mode: {mode!r}")
+ return {"docs_mode": mode, "docs_enabled": mode == "llm"}
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 51a7e4cd4..953bc219b 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -420,6 +420,7 @@ class ContextAssembler:
sccs: list[Any], # list[frozenset[str]]
community: dict[str, int],
graph_builder: Any | None = None,
+ repo_name: str | None = None,
external_systems: list[dict] | None = None,
decision_records: list[dict] | None = None,
) -> RepoOverviewContext:
@@ -474,7 +475,9 @@ class ContextAssembler:
pass
return RepoOverviewContext(
- repo_name=getattr(repo_structure, "name", "repo"),
+ # RepoStructure carries no name, so the old getattr fallback made
+ # every overview call the project "repo". The caller knows it.
+ repo_name=repo_name or getattr(repo_structure, "name", None) or "this repository",
is_monorepo=repo_structure.is_monorepo,
packages=repo_structure.packages,
language_distribution=repo_structure.root_language_distribution,
diff --git a/packages/core/src/repowise/core/generation/page_generator/pertype.py b/packages/core/src/repowise/core/generation/page_generator/pertype.py
index 5a19172d5..82d3f0765 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -198,6 +198,7 @@ class PerTypeGenerationMixin:
sccs,
community,
graph_builder=graph_builder,
+ repo_name=repo_name,
external_systems=external_systems,
decision_records=decision_records,
)
diff --git a/packages/core/src/repowise/core/generation/templates/deterministic/onboarding/codebase_map.j2 b/packages/core/src/repowise/core/generation/templates/deterministic/onboarding/codebase_map.j2
index c183ea5f0..e2479dbd0 100644
--- a/packages/core/src/repowise/core/generation/templates/deterministic/onboarding/codebase_map.j2
+++ b/packages/core/src/repowise/core/generation/templates/deterministic/onboarding/codebase_map.j2
@@ -16,9 +16,14 @@ Top to bottom, the order work flows through.
{% if ctx.entry_points %}
## Entry points
-{% for ep in ctx.entry_points %}
+{#- Capped: a monorepo where every UI folder carries an index.ts produces
+ dozens, and the point of this section is to name a place to start. -#}
+{% for ep in ctx.entry_points[:15] %}
- `{{ ep }}`
{% endfor %}
+{%- if ctx.entry_points | length > 15 %}
+- ...and {{ ctx.entry_points | length - 15 }} more.
+{% endif %}
{% endif %}
## Directories
diff --git a/packages/core/src/repowise/core/generation/templates/deterministic/repo_overview.j2 b/packages/core/src/repowise/core/generation/templates/deterministic/repo_overview.j2
index f8eb9f2c0..2505c6420 100644
--- a/packages/core/src/repowise/core/generation/templates/deterministic/repo_overview.j2
+++ b/packages/core/src/repowise/core/generation/templates/deterministic/repo_overview.j2
@@ -13,7 +13,10 @@
## Project Summary
-{% set _langs = ctx.language_distribution.items() | list -%}
+{# Sort by share, do not take the first key: language_distribution is an
+ unordered dict, and taking item 0 called a 59%-Python repo a "dockerfile
+ codebase" because that is what happened to hash first. #}
+{% set _langs = ctx.language_distribution.items() | sort(attribute='1', reverse=true) | list -%}
`{{ ctx.repo_name }}` is a {% if ctx.is_monorepo %}multi-package {% endif %}
{%- if _langs %}{{ _langs[0][0] }} {% endif %}codebase of {{ ctx.total_files }} files
{%- if ctx.is_monorepo %}, split across {{ ctx.packages | length }} packages{% endif %}.
@@ -31,9 +34,14 @@
{% if ctx.entry_points %}
## Entry Points
Start here when reading the codebase.
-{% for ep in ctx.entry_points %}
+{# Capped: a monorepo where every UI folder has an index.ts produces 75 of
+ these, and a 75-item wall is not a place to start reading. #}
+{% for ep in ctx.entry_points[:15] %}
- `{{ ep }}`
{% endfor %}
+{%- if ctx.entry_points | length > 15 %}
+- ...and {{ ctx.entry_points | length - 15 }} more.
+{% endif %}
{% endif %}
{% if ctx.execution_flows %}
@@ -60,10 +68,15 @@ Ranked by PageRank over the import graph: the files most of the codebase ultimat
{% endif %}
{% if ctx.language_distribution %}
+{# Same ordering and cap as the summary sentence above, or the two disagree. #}
+{% set langs = ctx.language_distribution.items() | sort(attribute='1', reverse=true) %}
## Languages
-{% for lang, pct in ctx.language_distribution.items() %}
+{% for lang, pct in langs[:8] %}
- {{ lang }}: {{ "%.1f"|format(pct * 100) }}%
{% endfor %}
+{%- if langs | length > 8 %}
+- ...and {{ langs | length - 8 }} more.
+{% endif %}
{% endif %}
{% if ctx.external_systems %}
diff --git a/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2 b/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2
index 4e1288232..51c25d138 100644
--- a/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2
@@ -10,15 +10,25 @@
{{ ctx.files | length }} files import each other in a loop, directly or transitively. Nothing in this group can be loaded, tested or extracted without the rest of it.
## Files in the cycle
-{% for f in ctx.files %}
+{# Capped, here and in the two listings below: a test-suite cycle routed
+ through a shared conftest can run to 80+ files and 200+ edges, and a page
+ that dumps all of them is 50KB of noise. The decouple ranking is the part
+ worth acting on. #}
+{% for f in ctx.files[:30] %}
- `{{ f }}`
{% endfor %}
+{%- if ctx.files | length > 30 %}
+- ...and {{ ctx.files | length - 30 }} more.
+{% endif %}
{% if ctx.cross_imports %}
## The loop
-{% for edge in ctx.cross_imports %}
+{% for edge in ctx.cross_imports[:40] %}
- `{{ edge.from }}` → `{{ edge.to }}`
{% endfor %}
+{%- if ctx.cross_imports | length > 40 %}
+- ...and {{ ctx.cross_imports | length - 40 }} more edges.
+{% endif %}
{% endif %}
{% if decouple_ranking %}
@@ -35,12 +45,15 @@ Ranked by how many of the cycle's edges each file carries. The file at the top i
{% if ctx.member_symbols %}
## Symbols defined in the cycle
-{% for m in ctx.member_symbols %}
+{% for m in ctx.member_symbols[:20] %}
### `{{ m.file_path }}`
{% for s in m.symbols[:15] %}
- `{{ s.name }}`{% if s.signature %}: `{{ s.signature | oneline(120) }}`{% endif %}
{% endfor %}
{% endfor %}
+{% if ctx.member_symbols | length > 20 %}
+*Symbols for the remaining {{ ctx.member_symbols | length - 20 }} files are on their own file pages.*
+{% endif %}
{% endif %}
**Total symbols in cycle:** {{ ctx.total_symbols }}
diff --git a/packages/core/src/repowise/core/pipeline/modes.py b/packages/core/src/repowise/core/pipeline/modes.py
index 7b55fd8f5..8914ec286 100644
--- a/packages/core/src/repowise/core/pipeline/modes.py
+++ b/packages/core/src/repowise/core/pipeline/modes.py
@@ -9,6 +9,11 @@ modes share one code path and differ only in the knobs they flip.
- ``FAST``: graph + ESSENTIAL git only, no LLM doc generation. Intended for a
quick first index of a very large repo; the deferred git signals can be
backfilled later (see ``git_indexer.backfill``).
+- ``DETERMINISTIC``: everything ``STANDARD`` does, except pages render from
+ templates instead of a model. No provider, no key, no spend. This is what
+ ``repowise init --index-only`` produces, for callers that want the pipeline
+ to generate for them (the CLI runs its own generation phase after the
+ pipeline instead, so it does not use this mode).
"""
from __future__ import annotations
@@ -25,6 +30,7 @@ class OrchestratorMode(enum.StrEnum):
STANDARD = "standard"
FAST = "fast"
+ DETERMINISTIC = "deterministic"
@property
def git_tier(self) -> GitIndexTier:
@@ -35,13 +41,22 @@ class OrchestratorMode(enum.StrEnum):
@property
def allows_doc_generation(self) -> bool:
- """Whether LLM doc generation may run in this mode.
+ """Whether the generation phase may run in this mode.
FAST never generates docs (and never makes LLM calls), regardless of
the ``generate_docs`` flag passed to the pipeline.
"""
return self is not OrchestratorMode.FAST
+ @property
+ def deterministic_docs(self) -> bool:
+ """Whether the generation phase renders templates instead of prompting.
+
+ When True the pipeline supplies its own null provider, so a caller can
+ ask for a full wiki without holding an API key.
+ """
+ return self is OrchestratorMode.DETERMINISTIC
+
@property
def sql_backed_metrics(self) -> bool:
"""Whether file-level metrics should be served from SQL post-build.
@@ -51,8 +66,8 @@ class OrchestratorMode(enum.StrEnum):
``GraphBuilder.release_graph``), serving subsequent metric reads from
the loaded snapshot — the large-repo scaling path.
- Default off in ``STANDARD`` (doc generation traverses the live graph)
- and on in ``FAST`` (which generates no docs, so nothing needs the
- structural graph after build + persistence).
+ Default off in ``STANDARD`` and ``DETERMINISTIC`` (doc generation
+ traverses the live graph) and on in ``FAST`` (which generates no docs,
+ so nothing needs the structural graph after build + persistence).
"""
return self is OrchestratorMode.FAST
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index 212cb9f14..3424b8c18 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -230,9 +230,11 @@ async def run_pipeline(
commit_depth = max(1, min(commit_depth, 10000))
# Mode policy: FAST forces ESSENTIAL git indexing and disables doc
- # generation (and therefore all LLM calls). STANDARD preserves the
- # caller's flags exactly. This is the single switch point — the rest of
- # the pipeline reads ``generate_docs`` / the git tier, not ``mode``.
+ # generation (and therefore all LLM calls). DETERMINISTIC generates every
+ # page from a template and supplies its own null provider, so a caller
+ # with no API key still gets a wiki. STANDARD preserves the caller's flags
+ # exactly. This is the single switch point: the rest of the pipeline
+ # reads ``generate_docs`` / the git tier, not ``mode``.
git_tier = mode.git_tier
generate_docs = generate_docs and mode.allows_doc_generation
@@ -602,7 +604,19 @@ async def run_pipeline(
# PipelineResult.authoritative_page_types). Stays empty unless curated
# generation engaged below.
authoritative_page_types: set[str] = set()
- if generate_docs and llm_client is not None:
+ # DETERMINISTIC supplies its own null provider so a caller with no key can
+ # still get a wiki. Scoped to this phase rather than assigned over
+ # ``llm_client``: the analysis phase above shares that client, and its
+ # decision extractor branches on truthiness, so a non-None provider that
+ # raises on every call would cost it the heuristic fallbacks it would
+ # otherwise have taken with no provider at all.
+ generation_client = llm_client
+ if generate_docs and mode.deterministic_docs and generation_client is None:
+ from repowise.core.providers.llm.template import TemplateProvider
+
+ generation_client = TemplateProvider()
+
+ if generate_docs and generation_client is not None:
if progress:
progress.on_message("info", "Phase 3: Generation")
@@ -623,6 +637,15 @@ async def run_pipeline(
language=_cfg.get("language", "en"),
)
+ # The mode decides how pages are rendered, not the caller's config.
+ # A DETERMINISTIC run with an LLM-shaped config would still prompt.
+ if mode.deterministic_docs and not resolved_generation_config.deterministic:
+ from dataclasses import replace as _dc_replace
+
+ resolved_generation_config = _dc_replace(
+ resolved_generation_config, deterministic=True
+ )
+
# Phase 2 enrichment: flag framework-defined HTTP surfaces (FastAPI,
# ASP.NET controllers, …) as api_contract so they route through the
# api_contract template instead of generic file_page. Lives in the
@@ -648,7 +671,10 @@ async def run_pipeline(
# snapshot generation is already holding. The page-dependent finalize
# (summary backfill) runs after both complete.
kg_structural_task = None
- if knowledge_graph_result is not None:
+ # Skipped in DETERMINISTIC mode: layer naming and the tour are pure
+ # prompting, and the null provider raises rather than stubbing. The
+ # skeleton's structural layers stand on their own.
+ if knowledge_graph_result is not None and not mode.deterministic_docs:
from repowise.core.generation.knowledge_graph import (
enrich_knowledge_graph_structural,
)
@@ -682,7 +708,7 @@ async def run_pipeline(
graph_builder=graph_builder,
repo_structure=repo_structure,
git_meta_map=git_meta_map,
- llm_client=llm_client,
+ llm_client=generation_client,
embedder=embedder,
vector_store=vector_store,
concurrency=concurrency,
@@ -734,6 +760,14 @@ async def run_pipeline(
authoritative_page_types.add("module_page")
if kg_layers_present:
authoritative_page_types.add("layer_page")
+ # A deterministic run takes every candidate rather than a budgeted
+ # slice, so an SCC page missing from its output means the cycle is
+ # gone, not that it lost a budget fight. That makes the run
+ # authoritative for the type and lets the sweep clear cycle pages for
+ # cycles that no longer exist. A budgeted run cannot claim the same:
+ # zero SCC pages there may just mean the allocation was zero.
+ if getattr(resolved_generation_config, "deterministic", False):
+ authoritative_page_types.add("scc_page")
# ---- Knowledge Graph enrichment: join + finalize ----------------------
# The structural half (layer naming + tour) ran concurrently with
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 6de6afe77..72d9a0a14 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -31,6 +31,7 @@ from repowise.core.update_lock import (
try_acquire_update_lock as _try_acquire_lock,
)
+from ..docs_mode import docs_mode_state_fields
from .config import WorkspaceConfig
_log = logging.getLogger("repowise.workspace.update")
@@ -704,8 +705,10 @@ async def update_workspace(
# Mark first-time so downstream tooling (status, doctor) can
# distinguish a never-indexed repo from one that's been
# updated at least once.
- if first_time and "docs_enabled" not in state:
- state["docs_enabled"] = False
+ if first_time and "docs_mode" not in state and "docs_enabled" not in state:
+ # This path indexes only; nothing renders pages here, not
+ # even from templates.
+ state.update(docs_mode_state_fields("none"))
state["docs_skip_reason"] = (
"first-time index via update; run "
"`repowise update --repo " + alias + " --docs` to generate docs"
diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.py
index 29371e80e..3d2f60718 100644
--- a/packages/server/src/repowise/server/job_executor.py
+++ b/packages/server/src/repowise/server/job_executor.py
@@ -22,6 +22,7 @@ from repowise.core.cancellation import (
get_active_token,
set_active_token,
)
+from repowise.core.docs_mode import DocsMode, docs_mode_state_fields
from repowise.core.persistence.crud import (
get_generation_job,
get_repository,
@@ -501,7 +502,9 @@ async def execute_job(
_persist_initial_index_state(
Path(repo_path),
llm_client=llm_client,
- docs_enabled=generate_docs,
+ # The API index path has no template fallback: without a
+ # provider it produces an index and no pages.
+ docs_mode="llm" if generate_docs else "none",
docs_skip_reason=docs_skip_reason,
total_pages=len(all_pages),
wiki_style=wiki_style,
@@ -648,7 +651,7 @@ def _persist_initial_index_state(
repo_path: Path,
*,
llm_client: Any,
- docs_enabled: bool,
+ docs_mode: DocsMode,
docs_skip_reason: str | None,
total_pages: int,
wiki_style: str,
@@ -688,8 +691,8 @@ def _persist_initial_index_state(
head = _read_head_sha(repo_path)
if head:
state["last_sync_commit"] = head
- state["docs_enabled"] = docs_enabled
- if docs_skip_reason and not docs_enabled:
+ state.update(docs_mode_state_fields(docs_mode))
+ if docs_skip_reason and docs_mode == "none":
state["docs_skip_reason"] = docs_skip_reason
state["run_mode"] = "standard"
state["git_tier"] = "full"
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 225ca675e..225f9db93 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -13,6 +13,7 @@ from fastapi.responses import PlainTextResponse, StreamingResponse
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.docs_mode import resolve_docs_mode
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
@@ -230,14 +231,26 @@ async def list_repos(
resp.workspace_status = "indexed"
indexed_aliases.add(entry.alias)
- # docs_enabled is recorded per-repo in state.json. Read it once
- # per response — cheap, and never failing.
+ # The docs mode and index tier are recorded per-repo in state.json.
+ # Read it once per response: cheap, and never failing.
state_path = _P(resp.local_path) / ".repowise" / "state.json"
if state_path.is_file():
try:
state = _json.loads(state_path.read_text(encoding="utf-8"))
- resp.docs_enabled = bool(state.get("docs_enabled", True))
+ resp.docs_mode = resolve_docs_mode(state)
+ # A state file predating every docs field used to report
+ # docs_enabled=True by default. Deriving the flag from the
+ # resolved mode alone would flip those old indexes to False,
+ # so keep the legacy default when nothing at all is recorded.
+ if not any(
+ k in state for k in ("docs_mode", "docs_enabled", "provider", "model")
+ ):
+ resp.docs_enabled = True
+ else:
+ resp.docs_enabled = resp.docs_mode != "none"
resp.docs_skip_reason = state.get("docs_skip_reason")
+ resp.run_mode = state.get("run_mode")
+ resp.git_tier = state.get("git_tier")
except Exception:
pass
@@ -272,6 +285,7 @@ async def list_repos(
workspace_status=status,
is_primary=bool(entry.is_primary),
docs_enabled=False,
+ docs_mode="none",
docs_skip_reason="not indexed yet",
)
)
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 8259b7e72..c1df3e32f 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -13,6 +13,7 @@ from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query, Request
+from repowise.core.docs_mode import resolve_docs_mode
from repowise.server.deps import (
get_cross_repo_enricher,
get_workspace_config,
@@ -125,7 +126,7 @@ def _query_repo_stats(db_path: Path) -> dict:
state_path = db_path.parent / "state.json"
if state_path.is_file():
state = _json.loads(state_path.read_text(encoding="utf-8"))
- result["docs_enabled"] = bool(state.get("docs_enabled", False))
+ result["docs_enabled"] = resolve_docs_mode(state) != "none"
result["docs_skip_reason"] = state.get("docs_skip_reason")
except Exception:
pass
diff --git a/packages/server/src/repowise/server/schemas/repository.py b/packages/server/src/repowise/server/schemas/repository.py
index a5807e882..a9f79d445 100644
--- a/packages/server/src/repowise/server/schemas/repository.py
+++ b/packages/server/src/repowise/server/schemas/repository.py
@@ -8,6 +8,8 @@ from pathlib import Path
from pydantic import BaseModel, field_validator
+from repowise.core.docs_mode import DocsMode
+
class RepoCreate(BaseModel):
name: str
@@ -58,8 +60,16 @@ class RepoResponse(BaseModel):
workspace_alias: str | None = None
workspace_status: str | None = None
is_primary: bool | None = None
+ # ``docs_enabled`` only says whether pages exist; ``docs_mode`` says who
+ # wrote them, which is what a client needs to offer the "upgrade to
+ # model-written pages" path.
docs_enabled: bool | None = None
+ docs_mode: DocsMode | None = None
docs_skip_reason: str | None = None
+ # Mirrors of the same state.json read: which index tier this repo was
+ # built at.
+ run_mode: str | None = None
+ git_tier: str | None = None
# Set on POST /api/repos responses when registration auto-enqueued the
# first index; clients attach to /api/jobs/{id}/stream with it.
initial_job_id: str | None = None
diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py
index f256026b4..310cb4f34 100644
--- a/tests/integration/test_cli.py
+++ b/tests/integration/test_cli.py
@@ -170,23 +170,29 @@ class TestInitFullMock:
class TestInitIndexOnly:
- def test_index_only_creates_db_and_state_no_pages(self, runner, work_repo):
+ def test_index_only_creates_db_and_template_pages(self, runner, work_repo):
result = runner.invoke(
cli,
["init", str(work_repo), "--index-only"],
catch_exceptions=False,
)
assert result.exit_code == 0, result.output
- assert (work_repo / ".repowise" / "wiki.db").exists()
+ db_path = work_repo / ".repowise" / "wiki.db"
+ assert db_path.exists()
assert (work_repo / ".repowise" / "state.json").exists()
assert "index complete" in result.output
import json
state = json.loads((work_repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ assert state.get("docs_mode") == "deterministic"
+ # Still False on purpose: an older reader treats it as "do not
+ # LLM-regenerate", which is right for a repo with no provider.
assert state.get("docs_enabled") is False
- # No pages generated in index-only mode.
- assert state.get("total_pages", 0) == 0
+
+ assert _db_scalar(db_path, "SELECT COUNT(*) FROM wiki_pages") > 0
+ providers = set(_db_column(db_path, "SELECT DISTINCT provider_name FROM wiki_pages"))
+ assert providers == {"template"}
def test_index_only_persists_clamped_commit_limit_and_excludes(self, runner, work_repo):
from repowise.cli.helpers import load_config
diff --git a/tests/unit/cli/test_augment_cmd.py b/tests/unit/cli/test_augment_cmd.py
index b62967fab..8118f3308 100644
--- a/tests/unit/cli/test_augment_cmd.py
+++ b/tests/unit/cli/test_augment_cmd.py
@@ -33,7 +33,12 @@ def _init_repowise_repo(path: Path) -> None:
repowise_dir = path / ".repowise"
repowise_dir.mkdir()
(repowise_dir / "state.json").write_text(
- json.dumps({"last_sync_commit": "1111111111111111111111111111111111111111"}),
+ json.dumps(
+ {
+ "last_sync_commit": "1111111111111111111111111111111111111111",
+ "docs_mode": "llm",
+ }
+ ),
encoding="utf-8",
)
diff --git a/tests/unit/cli/test_augment_staleness.py b/tests/unit/cli/test_augment_staleness.py
index 4998100e6..925cc1839 100644
--- a/tests/unit/cli/test_augment_staleness.py
+++ b/tests/unit/cli/test_augment_staleness.py
@@ -340,12 +340,21 @@ class TestDocsEnabledWording:
msg = _post(repo_path)
assert "Wiki is stale" in msg
- def test_defaults_to_wiki_when_field_missing(self, repo):
- # Backward compat: pre-existing state.json files without
- # docs_enabled should keep the old wording.
+ def test_says_index_when_no_docs_fields_and_no_provider(self, repo):
+ # A state file with neither docs field and no provider was written by
+ # a pre-migration index-only run, which really did leave no pages.
repo_path, head = repo
_state(repo_path, last_sync_commit=head)
_commit(repo_path)
+ msg = _post(repo_path)
+ assert "Index is stale" in msg
+
+ def test_says_wiki_when_no_docs_fields_but_provider_recorded(self, repo):
+ # Pre-migration full inits recorded provider/model and nothing else.
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, provider="openai")
+ _commit(repo_path)
+
msg = _post(repo_path)
assert "Wiki is stale" in msg
diff --git a/tests/unit/cli/test_docs_mode_back_compat.py b/tests/unit/cli/test_docs_mode_back_compat.py
new file mode 100644
index 000000000..18e5c2c4b
--- /dev/null
+++ b/tests/unit/cli/test_docs_mode_back_compat.py
@@ -0,0 +1,84 @@
+"""Back-compat for the docs_enabled to docs_mode migration.
+
+Every state.json shape that has ever shipped must keep resolving to the same
+behaviour it had before the field was split, so upgrading repowise never
+silently changes what `repowise update` does to an already-indexed repo.
+"""
+
+from __future__ import annotations
+
+from repowise.cli.commands.update_cmd import _resolve_index_only_mode as _resolve_mode
+from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
+
+
+class TestResolveDocsMode:
+ def test_docs_mode_field_wins(self):
+ assert resolve_docs_mode({"docs_mode": "deterministic"}) == "deterministic"
+ assert resolve_docs_mode({"docs_mode": "llm"}) == "llm"
+ assert resolve_docs_mode({"docs_mode": "none"}) == "none"
+
+ def test_unrecognised_docs_mode_falls_through(self):
+ # A newer CLI could write a mode this build has never heard of; the
+ # legacy field is still there to answer from.
+ assert resolve_docs_mode({"docs_mode": "wat", "docs_enabled": True}) == "llm"
+
+ def test_legacy_docs_enabled_true_reads_as_llm(self):
+ # Templates did not exist when this field was written, so True could
+ # only ever have meant a model wrote the pages.
+ assert resolve_docs_mode({"docs_enabled": True}) == "llm"
+
+ def test_legacy_docs_enabled_false_reads_as_none(self):
+ assert resolve_docs_mode({"docs_enabled": False}) == "none"
+
+ def test_neither_field_with_provider_reads_as_llm(self):
+ assert resolve_docs_mode({"provider": "openai", "model": "gpt-5.4-mini"}) == "llm"
+
+ def test_neither_field_with_model_only_reads_as_llm(self):
+ assert resolve_docs_mode({"model": "gpt-5.4-mini"}) == "llm"
+
+ def test_neither_field_without_provider_reads_as_none(self):
+ assert resolve_docs_mode({"last_sync_commit": "abc"}) == "none"
+
+ def test_empty_and_missing_state_read_as_none(self):
+ assert resolve_docs_mode({}) == "none"
+ assert resolve_docs_mode(None) == "none"
+
+
+class TestDocsModeStateFields:
+ def test_writes_both_fields(self):
+ assert docs_mode_state_fields("llm") == {"docs_mode": "llm", "docs_enabled": True}
+ # False on purpose for deterministic: an older reader takes it as
+ # "do not regenerate with a model", which is right for a repo that
+ # has pages but no provider.
+ assert docs_mode_state_fields("deterministic") == {
+ "docs_mode": "deterministic",
+ "docs_enabled": False,
+ }
+ assert docs_mode_state_fields("none") == {"docs_mode": "none", "docs_enabled": False}
+
+ def test_round_trips_through_resolve(self):
+ for mode in ("none", "deterministic", "llm"):
+ assert resolve_docs_mode(docs_mode_state_fields(mode)) == mode
+
+
+class TestUpdateModePriority:
+ """Explicit flag > --docs/--no-docs > state, on every state shape."""
+
+ def test_index_only_flag_beats_everything(self):
+ assert _resolve_mode(index_only=True, docs_flag=True, state={"docs_mode": "llm"}) is True
+
+ def test_docs_flags_beat_state(self):
+ assert _resolve_mode(index_only=False, docs_flag=False, state={"docs_mode": "llm"}) is True
+ assert _resolve_mode(index_only=False, docs_flag=True, state={"docs_mode": "none"}) is False
+
+ def test_legacy_states_keep_their_old_default(self):
+ assert (
+ _resolve_mode(index_only=False, docs_flag=None, state={"docs_enabled": True}) is False
+ )
+ assert (
+ _resolve_mode(index_only=False, docs_flag=None, state={"docs_enabled": False}) is True
+ )
+ assert (
+ _resolve_mode(index_only=False, docs_flag=None, state={"provider": "openai"}) is False
+ )
+ assert _resolve_mode(index_only=False, docs_flag=None, state={}) is True
diff --git a/tests/unit/cli/test_fast_mode_offer.py b/tests/unit/cli/test_fast_mode_offer.py
index 9e7f57bd5..96d870b43 100644
--- a/tests/unit/cli/test_fast_mode_offer.py
+++ b/tests/unit/cli/test_fast_mode_offer.py
@@ -39,7 +39,7 @@ def test_next_steps_fast_mode_leads_with_full_upgrade():
def test_next_steps_index_only_without_fast():
steps = build_contextual_next_steps(index_only=True, fast_mode=False)
cmds = [c for c, _ in steps]
- assert any("--provider" in c for c in cmds) # the existing generate hint
+ assert any("update --full" in c for c in cmds) # the upgrade-to-prose hint
def test_next_steps_index_only_recommends_serve_as_first_step():
diff --git a/tests/unit/cli/test_restyle_cmd.py b/tests/unit/cli/test_restyle_cmd.py
index 31bee48d2..a19e85f6c 100644
--- a/tests/unit/cli/test_restyle_cmd.py
+++ b/tests/unit/cli/test_restyle_cmd.py
@@ -2,7 +2,7 @@
These cover the validation/guard rails that run *before* any generation — the
expensive regeneration path itself is exercised by the generation suite. The key
-guarantees: unknown styles are rejected, restyle refuses repos with no docs, and
+guarantees: unknown styles are rejected, restyle refuses repos with no pages, and
the listing surfaces the built-in catalogue + current style.
"""
@@ -92,11 +92,20 @@ def test_restyle_requires_index(tmp_path):
assert "No index found" in result.output
-def test_restyle_refuses_index_only_repo(tmp_path):
+def test_restyle_refuses_repo_with_no_pages(tmp_path):
_write_state(tmp_path, {"docs_enabled": False, "last_sync_commit": "abc"})
result = CliRunner().invoke(cli, ["restyle", "caveman", str(tmp_path), "--yes"])
assert result.exit_code == 1
- assert "index-only" in result.output
+ assert "no wiki pages to restyle" in result.output
+
+
+def test_restyle_warns_but_does_not_refuse_on_template_wiki(tmp_path):
+ # Restyling a template wiki is the supported upgrade to model-written
+ # pages, so the guard must let it through after saying what it will cost.
+ _write_state(tmp_path, {"docs_mode": "deterministic", "last_sync_commit": "abc"})
+ result = CliRunner().invoke(cli, ["restyle", "caveman", str(tmp_path), "--yes"])
+ assert "rendered from templates" in result.output
+ assert "no wiki pages to restyle" not in result.output
def test_restyle_known_styles_accepted_past_validation(tmp_path):
diff --git a/tests/unit/cli/test_update_mode_resolution.py b/tests/unit/cli/test_update_mode_resolution.py
index 481960c5c..5120d9070 100644
--- a/tests/unit/cli/test_update_mode_resolution.py
+++ b/tests/unit/cli/test_update_mode_resolution.py
@@ -5,7 +5,8 @@ in this priority order:
1. Explicit `--index-only` flag → index-only.
2. `--no-docs` → index-only; `--docs` → full.
- 3. `state.docs_enabled` from `.repowise/state.json` (default: True).
+ 3. The persisted docs mode from `.repowise/state.json`: only an `llm` repo
+ defaults to a full update.
This is what lets the post-commit hook do the right thing without needing
to know how the user originally indexed the repo.
@@ -13,70 +14,75 @@ to know how the user originally indexed the repo.
from __future__ import annotations
-from repowise.cli.commands.update_cmd import (
- _infer_legacy_docs_enabled,
- _resolve_index_only_mode as _resolve_mode,
-)
+from repowise.cli.commands.update_cmd import _resolve_index_only_mode as _resolve_mode
class TestModeResolution:
def test_explicit_index_only_wins(self):
- assert _resolve_mode(
- index_only=True, docs_flag=True, state={"docs_enabled": True}
- ) is True
+ assert _resolve_mode(index_only=True, docs_flag=True, state={"docs_enabled": True}) is True
def test_no_docs_flag_forces_index_only(self):
- assert _resolve_mode(
- index_only=False, docs_flag=False, state={"docs_enabled": True}
- ) is True
+ assert (
+ _resolve_mode(index_only=False, docs_flag=False, state={"docs_enabled": True}) is True
+ )
def test_docs_flag_forces_full(self):
# User explicitly opts in to LLM regen even though state says no.
- assert _resolve_mode(
- index_only=False, docs_flag=True, state={"docs_enabled": False}
- ) is False
+ assert (
+ _resolve_mode(index_only=False, docs_flag=True, state={"docs_enabled": False}) is False
+ )
def test_state_default_index_only(self):
# No flags → state value drives behavior.
- assert _resolve_mode(
- index_only=False, docs_flag=None, state={"docs_enabled": False}
- ) is True
+ assert (
+ _resolve_mode(index_only=False, docs_flag=None, state={"docs_enabled": False}) is True
+ )
def test_state_default_full(self):
- assert _resolve_mode(
- index_only=False, docs_flag=None, state={"docs_enabled": True}
- ) is False
+ assert (
+ _resolve_mode(index_only=False, docs_flag=None, state={"docs_enabled": True}) is False
+ )
def test_missing_field_with_provider_defaults_to_full(self):
# Pre-migration full init wrote provider/model into state. Those
# users keep the full-mode default after upgrading — no surprise
# change in behavior.
- assert _resolve_mode(
- index_only=False,
- docs_flag=None,
- state={"provider": "openai", "model": "gpt-5.4-mini"},
- ) is False
+ assert (
+ _resolve_mode(
+ index_only=False,
+ docs_flag=None,
+ state={"provider": "openai", "model": "gpt-5.4-mini"},
+ )
+ is False
+ )
def test_missing_field_no_provider_defaults_to_index_only(self):
# Pre-migration `init --index-only` skipped writing provider/model,
# so absence of both signals "this was an index-only init" — and
# we default future updates to index-only too. Critical for not
# surprising those users with an LLM bill on first upgrade.
- assert _resolve_mode(
- index_only=False, docs_flag=None, state={"last_sync_commit": "abc"}
- ) is True
-
-
-class TestLegacyDocsEnabledInference:
- def test_provider_present_means_docs_were_enabled(self):
- assert _infer_legacy_docs_enabled({"provider": "openai"}) is True
-
- def test_model_present_means_docs_were_enabled(self):
- # Older code paths wrote model without provider in some flows.
- assert _infer_legacy_docs_enabled({"model": "gpt-5.4-mini"}) is True
-
- def test_neither_means_index_only(self):
- assert _infer_legacy_docs_enabled({"last_sync_commit": "x"}) is False
-
- def test_empty_state_means_index_only(self):
- assert _infer_legacy_docs_enabled({}) is False
+ assert (
+ _resolve_mode(index_only=False, docs_flag=None, state={"last_sync_commit": "abc"})
+ is True
+ )
+
+ def test_deterministic_mode_defaults_to_index_only(self):
+ # A template wiki has no provider configured, so a full update would
+ # either fail or bill someone who never asked for a model.
+ assert (
+ _resolve_mode(index_only=False, docs_flag=None, state={"docs_mode": "deterministic"})
+ is True
+ )
+
+ def test_llm_mode_defaults_to_full(self):
+ assert _resolve_mode(index_only=False, docs_flag=None, state={"docs_mode": "llm"}) is False
+
+ def test_docs_mode_wins_over_legacy_docs_enabled(self):
+ assert (
+ _resolve_mode(
+ index_only=False,
+ docs_flag=None,
+ state={"docs_mode": "deterministic", "docs_enabled": True},
+ )
+ is True
+ )