Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
Wiki styles: selectable documentation voice (caveman, reference, tutorial) (#468)
Raghav Chamadiyac5a0d3d8d1e9
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex fbcfc935e..56e8f74c5 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -55,6 +55,7 @@ In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (| `--embedder` | Embedder for semantic search: `gemini`, `openai`, `mock` || `--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`). |+| `--wiki-style` | Documentation voice/density: `comprehensive` (default), `caveman` (token-condensed, AI-first), `reference` (API-manual), `tutorial` (beginner-friendly). Interactive full runs prompt when omitted. Saved to config so `update` keeps the style. See [WIKI_STYLES.md](WIKI_STYLES.md). || `--dry-run` | Show generation plan and cost estimate without running. || `--test-run` | Generate docs for only the top 10 files (by PageRank). || `--skip-tests` | Exclude test files from doc generation. |@@ -133,6 +134,41 @@ repowise update --full --provider anthropic # upgrade a fast index to full---+### `repowise restyle [STYLE] [PATH]`++Switch a repo's wiki **style** and regenerate every page in the new voice. Reuses+the existing index — the dependency graph and git metadata are rehydrated from+SQL (no re-resolution, no re-blame), so only the per-file parse + LLM generation+run. Requires a full (docs-enabled) index and a provider.++With no `STYLE`, prints the current style and the available choices.++Styles only differ in voice and density; the markdown structure (headings,+sections) stays the same, so search, the table of contents, and cross-links keep+working. See [WIKI_STYLES.md](WIKI_STYLES.md).++```bash+repowise restyle # show current style + options+repowise restyle caveman # condensed, AI-first+repowise restyle reference --yes # API-manual, skip the confirm+```++> Editing `wiki_style` in `config.yaml` by hand and running `update` does **not**+> regenerate existing pages (that path only re-scores health). Use `restyle`.++---++### `repowise wiki-styles [PATH]`++List the available wiki styles (built-ins plus any custom styles defined under+`.repowise/styles/`) and the repo's current one.++```bash+repowise wiki-styles+```++---+### `repowise serve [PATH]`Start the API server and web UI.diff --git a/docs/CONFIG.md b/docs/CONFIG.mdindex 5a8426169..d99e985aa 100644--- a/docs/CONFIG.md+++ b/docs/CONFIG.md@@ -28,13 +28,14 @@ should not be committed — it's a local cache, not a source of truth.## `config.yaml`The main configuration file. Created after first `init`, updated when you pass-`--commit-limit` or `--follow-renames` flags.+flags like `--commit-limit`, `--follow-renames`, or `--wiki-style`.```yamlprovider: anthropic # LLM providermodel: claude-sonnet-4-6 # Model identifierembedder: gemini # Embedding providerreasoning: auto # auto | off | minimal+wiki_style: comprehensive # comprehensive | caveman | reference | tutorialexclude_patterns: # Gitignore-style patterns- vendor/- "*.generated.*"@@ -55,6 +56,13 @@ requests OpenAI's lowest supported reasoning effort for supported OpenAIreasoning models and maps to OpenRouter's `reasoning.effort=minimal`. Providersor models that cannot translate an explicit mode fail before making an API call.+`wiki_style` controls the voice and density of generated wiki pages. Set it with+`init --wiki-style` or switch later with `repowise restyle <style>` (which also+regenerates the wiki). Power users can define their own style under+`.repowise/styles/<name>/style.yaml`. Full guide: [WIKI_STYLES.md](WIKI_STYLES.md).+Note: hand-editing `wiki_style` here and running `update` does not regenerate+existing pages — use `restyle`.+> **Code-health rules** are configured separately in> `.repowise/health-rules.json` (per-file biomarker overrides) — see> [CODE_HEALTH.md](CODE_HEALTH.md#configuration).diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 630c0c074..cff0a9323 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -183,6 +183,7 @@ repowise init [PATH]| `--model` | Model name override (e.g., `claude-sonnet-4-6`, `gpt-5.4-nano`) || `--embedder` | Embedder for semantic search: `gemini`, `openai`, `mock`. Auto-detected from env vars. || `--index-only` | Skip LLM generation entirely. Only parse, build graph, and index git. Free. |+| `--wiki-style` | Documentation voice: `comprehensive` (default), `caveman` (token-condensed), `reference` (API-manual), `tutorial`. Saved to config; switch later with `repowise restyle`. See [WIKI_STYLES.md](WIKI_STYLES.md). || `--dry-run` | Show generation plan and cost estimate without running anything. || `--test-run` | Generate docs for only the top 10 files (by PageRank) — quick validation. || `--skip-tests` | Exclude test files from documentation generation. |diff --git a/docs/WIKI_STYLES.md b/docs/WIKI_STYLES.mdnew file mode 100644index 000000000..725368588--- /dev/null+++ b/docs/WIKI_STYLES.md@@ -0,0 +1,84 @@+# Wiki styles++Repowise generates wiki pages in a configurable **style** that controls the+*voice and density* of the prose, without changing the structural markdown+(headings and sections stay the same, so search, the table of contents, and+cross-links keep working).++## Built-in styles++| Style | Best for | What it reads like |+|-------|----------|--------------------|+| `comprehensive` | The default. Humans and AI. | Full, narrative documentation. |+| `caveman` | AI agents, token budgets. | Token-condensed fragments, ~70% smaller. |+| `reference` | Library consumers. | API-manual: signature-dense, minimal narrative. |+| `tutorial` | New contributors. | Guided, beginner-friendly walkthroughs. |++List the available styles (and the repo's current one):++```bash+repowise wiki-styles+```++## Choosing a style++At init (full mode), pick a style with a flag or the interactive prompt:++```bash+repowise init --wiki-style caveman+```++The choice is saved to `.repowise/config.yaml` (`wiki_style:`), so `repowise+update` keeps regenerated pages in the same style.++## Switching styles++Switching regenerates every page in the new voice. Use the dedicated command —+it reuses the existing index and git data, so no re-resolution or re-blame is+needed:++```bash+repowise restyle reference+```++In the web app, the repo **Settings → Documentation style** selector does the+same: it saves the style and offers to regenerate the wiki. Individual pages can+also be regenerated in a one-off style from the page's **Regenerate** control.++> Note: editing `wiki_style` in `config.yaml` by hand and running `repowise+> update` will **not** regenerate existing pages (that path only re-scores+> health). Use `repowise restyle` to apply a style change.++## Custom styles (power users)++Define your own style under `.repowise/styles/<name>/style.yaml`:++```yaml+# .repowise/styles/terse/style.yaml+description: Ultra-terse internal style+onboarding_condenses: true # also condense the onboarding pages+style_version: 1 # bump when you edit this file to force regen+system_note: |+ Write for senior engineers who know the domain. Be extremely concise.+user_directive: |+ Write in TERSE style.+ - Keep every required ## heading; bodies are short fragments.+ - No filler, no restating the heading, no closing summary.+ - Keep code identifiers and paths verbatim.+```++Then apply it:++```bash+repowise restyle terse+```++Optionally ship per-page-type Jinja templates in+`.repowise/styles/<name>/templates/` (same filenames as the built-in templates,+e.g. `file_page.j2`). They override the built-ins for the page types you supply;+anything you don't provide falls back to the default template.++Guard rails: style names must match `[a-z0-9][a-z0-9_-]*`; directive and note+text are length-bounded; a style with neither a directive nor a note is ignored.+Built-in style names always take precedence over a custom directory of the same+name.diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex fc9e30036..f04d7a569 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -63,6 +63,7 @@ from repowise.cli.ui import (quick_repo_scan,should_offer_fast_mode,)+from repowise.core.generation.styles import DEFAULT_STYLE, list_styles, resolve_stylefrom repowise.core.reasoning import REASONING_MODESfrom ._interactive import offer_distill_rewrite_hook, offer_hook_install@@ -78,6 +79,27 @@ from .reporting import show_analysis_summary, show_completionfrom .workspace import _workspace_init+def _prompt_wiki_style(console: Any) -> str:+ """Interactive picker for the wiki documentation style (full-mode init only).++ Returns the chosen style name. Defaults to the comprehensive baseline so a+ bare Enter keeps today's behaviour.+ """+ styles = list_styles()+ console.print("\n[bold]Documentation style[/bold]")+ for idx, spec in enumerate(styles, 1):+ marker = " [dim](default)[/dim]" if spec.name == DEFAULT_STYLE else ""+ console.print(f" {idx}. [cyan]{spec.name}[/cyan]{marker} — {spec.description}")+ default_idx = next((i for i, s in enumerate(styles, 1) if s.name == DEFAULT_STYLE), 1)+ choice = click.prompt(+ " Choose a style",+ type=click.IntRange(1, len(styles)),+ default=default_idx,+ show_default=True,+ )+ return styles[choice - 1].name++def _run_generation_phase(*,repo_path: Path,@@ -90,6 +112,7 @@ def _run_generation_phase(onboarding: bool,tier1_top_n: int | None,harvest_decisions: bool,+ wiki_style: str,coverage_pct: float | None,yes: bool,dry_run: bool,@@ -122,6 +145,7 @@ def _run_generation_phase(enable_onboarding=onboarding,tier1_top_n=tier1_top_n,harvest_decisions=harvest_decisions,+ wiki_style=wiki_style,)chosen_pct, _plans, est, gen_config = select_coverage(result=result,@@ -357,6 +381,18 @@ def _run_generation_phase("hit, so the token cost lands only on files that carry one. Default: on."),)+ "--wiki-style",+ "wiki_style",+ type=click.Choice([s.name for s in list_styles()]),+ default=None,+ help=(+ "Documentation voice/density for generated pages: "+ "comprehensive (default), caveman (token-condensed, AI-first), "+ "reference (API-manual), tutorial (beginner-friendly). When omitted in "+ "an interactive full run you'll be prompted; otherwise comprehensive."+ ),+)def init_command(path: str | None,provider_name: str | None,@@ -385,6 +421,7 @@ def init_command(onboarding: bool,coverage_pct: float | None,harvest_decisions: bool,+ wiki_style: str | None,) -> None:"""Generate wiki documentation for a codebase.@@ -437,6 +474,9 @@ def init_command(onboarding=onboarding,coverage_pct=coverage_pct,harvest_decisions=harvest_decisions,+ # Apply the chosen style uniformly across the workspace's repos+ # (no per-repo interactive prompt in the multi-repo flow).+ wiki_style=resolve_style(wiki_style).name,run_mode=run_mode,)return@@ -536,6 +576,15 @@ def init_command(run_mode = "fast"index_only = True+ # Wiki style: prompt in interactive full-mode runs when not set via flag.+ # Index-only runs generate no pages, so the question is skipped (D7).+ if wiki_style is None and not index_only:+ wiki_style = _prompt_wiki_style(console)++ # Resolve the effective style (CLI flag > interactive prompt > default) and+ # canonicalize it. Used by generation and persisted so update/restyle honor it.+ wiki_style = resolve_style(wiki_style).name+editor_options = resolve_editor_setup_options(console,disabled_project_files=get_default_disabled_project_files(@@ -752,6 +801,7 @@ def init_command(onboarding=onboarding,tier1_top_n=tier1_top_n,harvest_decisions=harvest_decisions,+ wiki_style=wiki_style,coverage_pct=coverage_pct,yes=yes,dry_run=dry_run,@@ -784,6 +834,13 @@ def init_command(if not onboarding:save_config_partial(repo_path, enable_onboarding=False)+ # Persist the wiki style so `repowise update` / `restyle` honor it without+ # re-passing the flag. Written before any config_fingerprint is computed+ # below so the first update doesn't false-positive on a config change. The+ # default is omitted to keep config files tidy — only an override is recorded.+ if wiki_style != DEFAULT_STYLE:+ save_config_partial(repo_path, wiki_style=wiki_style)+# ---- Post-run: config, state, MCP, editor project files ----if commit_limit is not None:save_config_partial(repo_path, commit_limit=resolved_commit_limit)diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex db23f396f..9f3b3d295 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -39,6 +39,7 @@ from repowise.cli.helpers import (resolve_reasoning,run_async,save_config,+ save_config_partial,save_state,)from repowise.cli.providers import resolve_embedder@@ -57,6 +58,7 @@ from repowise.cli.ui import (load_dotenv,print_banner,)+from repowise.core.generation.styles import DEFAULT_STYLEfrom ._interactive import offer_distill_rewrite_hook, offer_hook_installfrom .generation import (@@ -86,6 +88,7 @@ def _run_workspace_generation(onboarding: bool = True,coverage_pct: float | None = None,harvest_decisions: bool = True,+ wiki_style: str = DEFAULT_STYLE,) -> list[Any]:"""Run LLM generation for a single repo in the workspace init flow.@@ -101,6 +104,7 @@ def _run_workspace_generation(reasoning=resolve_reasoning(reasoning),enable_onboarding=onboarding,harvest_decisions=harvest_decisions,+ wiki_style=wiki_style,)chosen_pct, _plans, est, gen_config = select_coverage(result=result,@@ -179,6 +183,7 @@ class _WorkspaceCtx:onboarding: boolcoverage_pct: float | Noneharvest_decisions: bool+ wiki_style: strresolved_reasoning: strembedder_name_resolved: strresolved_commit_limit: int@@ -288,6 +293,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtonboarding=ctx.onboarding,coverage_pct=ctx.coverage_pct,harvest_decisions=ctx.harvest_decisions,+ wiki_style=ctx.wiki_style,)result.generated_pages = generated_pages# (result.vector_store is set inside _run_workspace_generation@@ -361,6 +367,10 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtcommit_limit=ctx.resolved_commit_limit,reasoning=ctx.resolved_reasoning,)+ # Persist the wiki style per repo so update/restyle honor it. Default+ # omitted to keep config tidy — only an override is recorded.+ if ctx.wiki_style != DEFAULT_STYLE:+ save_config_partial(repo.path, wiki_style=ctx.wiki_style)return _RepoOutcome(file_count=result.file_count,@@ -413,6 +423,7 @@ def _workspace_init(onboarding: bool = True,coverage_pct: float | None = None,harvest_decisions: bool = True,+ wiki_style: str = DEFAULT_STYLE,run_mode: str = "standard",) -> None:"""Multi-repo workspace initialization.@@ -569,6 +580,7 @@ def _workspace_init(onboarding=onboarding,coverage_pct=coverage_pct,harvest_decisions=harvest_decisions,+ wiki_style=wiki_style,resolved_reasoning=resolved_reasoning,embedder_name_resolved=embedder_name_resolved,resolved_commit_limit=resolved_commit_limit,diff --git a/packages/cli/src/repowise/cli/commands/restyle_cmd.py b/packages/cli/src/repowise/cli/commands/restyle_cmd.pynew file mode 100644index 000000000..a4a4e3b87--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/restyle_cmd.py@@ -0,0 +1,286 @@+"""``repowise restyle`` and ``repowise wiki-styles``.++``restyle`` switches a repo's wiki documentation style and regenerates every LLM+page in the new voice. It reuses the persisted graph (rehydrated from SQL) and the+persisted git metadata (no re-blame) — the only unavoidable rework is re-parsing+files for ASTs, exactly like ``repowise update --full``. Because the chosen style+folds into each page's ``source_hash``, the regeneration is unconditional: every+page is rewritten in the new style.++``wiki-styles`` lists the available styles and shows which one a repo currently uses.+"""++from __future__ import annotations++import time+from pathlib import Path+from typing import Any++import click++from repowise.cli.helpers import (+ config_fingerprint,+ console,+ get_head_commit,+ load_config,+ load_state,+ resolve_provider,+ resolve_reasoning,+ resolve_repo_path,+ run_async,+ save_config_partial,+ save_state,+)+from repowise.cli.ui import load_dotenv+from repowise.core.generation.styles import (+ DEFAULT_STYLE,+ is_known_style,+ list_styles,+ resolve_style,+)+++def _print_styles(current: str | None = None, repo_path: Path | str | None = None) -> None:+ """Render the available styles, marking the default and (optionally) current."""+ console.print("[bold]Available wiki styles[/bold]")+ for spec in list_styles(repo_path):+ tags = []+ if spec.name == DEFAULT_STYLE:+ tags.append("default")+ if current is not None and spec.name == current:+ tags.append("current")+ suffix = f" [green]({', '.join(tags)})[/green]" if tags else ""+ console.print(f" [cyan]{spec.name}[/cyan]{suffix} — {spec.description}")+++async def _run_restyle(+ repo_path: Path,+ provider: Any,+ config: Any,+ *,+ exclude_patterns: list[str],+) -> list[Any]:+ """Regenerate every wiki page in the configured style, reusing the index.++ Mirrors the upgrade flow's regeneration step but loads git metadata from the+ DB instead of re-blaming, and skips the health recompute — a style change+ affects prose only, never the graph, git signals, or health scores.+ """+ from repowise.cli.commands.upgrade_flow import _reparse+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.cli.providers import build_cost_tracker, cost_tracking_disabled+ from repowise.core.generation.cost_tracker import CostTracker+ from repowise.core.persistence import (+ FullTextSearch,+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_page_from_generated,+ upsert_repository,+ )+ from repowise.core.pipeline import rehydrate_graph_builder, run_generation+ from repowise.core.pipeline.resume.rehydrate import rehydrate_git_meta_map++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))+ repo_id = repo.id++ # Rehydrate the graph + git signals from SQL — no parse, no resolve, no blame.+ async with get_session(sf) as session:+ graph_builder = await rehydrate_graph_builder(session, repo_id, repo_path)+ git_meta_map = await rehydrate_git_meta_map(session, repo_id)++ parsed_files, source_map, repo_structure = _reparse(repo_path, exclude_patterns)+ console.print(+ f"Re-parsed [cyan]{len(parsed_files)}[/cyan] files (graph + git reused from index)."+ )++ cost_tracker = CostTracker() if cost_tracking_disabled() else build_cost_tracker(sf, repo_id)+ provider._cost_tracker = cost_tracker++ # No prior_pages are passed: the style change would invalidate them all anyway,+ # and omitting them makes the full-repo rewrite explicit.+ generated_pages = await run_generation(+ repo_path=repo_path,+ parsed_files=parsed_files,+ source_map=source_map,+ graph_builder=graph_builder,+ repo_structure=repo_structure,+ git_meta_map=git_meta_map,+ llm_client=provider,+ embedder=None,+ vector_store=None,+ concurrency=config.max_concurrency,+ progress=None,+ cost_tracker=cost_tracker,+ generation_config=config,+ )+ await cost_tracker.flush()++ async with get_session(sf) as session:+ for page in generated_pages:+ await upsert_page_from_generated(session, page, repo_id)++ try:+ fts = FullTextSearch(engine)+ await fts.ensure_index()+ for page in generated_pages:+ await fts.index(page.page_id, page.title, page.content)+ except Exception:+ pass # FTS indexing is best-effort++ await engine.dispose()+ return generated_pages++[email protected]("restyle")[email protected]("style", required=False, default=None)[email protected]("path", required=False, default=None)[email protected]("--provider", "provider_name", default=None, help="LLM provider name.")[email protected]("--model", default=None, help="Model identifier override.")[email protected]("--concurrency", type=int, default=12, help="Max concurrent LLM calls.")[email protected]("--reasoning", default=None, help="Reasoning mode override.")[email protected]("--yes", "-y", is_flag=True, default=False, help="Skip the confirmation prompt.")+def restyle_command(+ style: str | None,+ path: str | None,+ provider_name: str | None,+ model: str | None,+ concurrency: int,+ reasoning: str | None,+ yes: bool,+) -> None:+ """Switch a repo's wiki STYLE and regenerate every page in the new voice.++ STYLE is one of: comprehensive, caveman, reference, tutorial. With no STYLE,+ prints the current style and the available choices.++ This regenerates the whole wiki with LLM calls (a cost), reusing the existing+ index/graph/git so no re-resolution or re-blame is needed.+ """+ repo_path = resolve_repo_path(path)+ load_dotenv(repo_path)+ state = load_state(repo_path)+ cfg = load_config(repo_path)+ current = resolve_style(cfg.get("wiki_style"), repo_path=repo_path).name++ # No style given → show current + options and exit.+ if style is None:+ console.print(f"Current wiki style: [cyan]{current}[/cyan]\n")+ _print_styles(current=current, repo_path=repo_path)+ console.print("\nRun [bold]repowise restyle <style>[/bold] to switch and regenerate.")+ return++ style = style.strip().lower()+ if not is_known_style(style, repo_path):+ valid = ", ".join(s.name for s in list_styles(repo_path))+ raise click.ClickException(f"Unknown style '{style}'. Choose one of: {valid}.")++ # Restyle only makes sense for a full index (one that has generated docs).+ if not state:+ raise click.ClickException(f"No index found at {repo_path}. Run `repowise init` first.")+ if not state.get("docs_enabled", False):+ raise click.ClickException(+ "This repo is index-only (no wiki pages to restyle). "+ "Run `repowise update --full` to generate docs first."+ )++ if style == current:+ console.print(f"[yellow]Already using the '{style}' style.[/yellow]")+ if not yes and not click.confirm("Regenerate anyway?", default=False):+ return++ provider = resolve_provider(provider_name, model, repo_path=repo_path)++ console.print(+ f"[bold]repowise restyle[/bold] — {repo_path}\n"+ f"Style: [cyan]{current}[/cyan] → [cyan]{style}[/cyan] · "+ f"Provider: [cyan]{provider.provider_name}[/cyan] / [cyan]{provider.model_name}[/cyan]"+ )+ if not yes and not click.confirm(+ "This regenerates the whole wiki (LLM calls, cost). Continue?", default=True+ ):+ console.print("[yellow]Aborted.[/yellow]")+ return++ from repowise.core.generation import GenerationConfig++ config = GenerationConfig(+ max_concurrency=concurrency,+ language=cfg.get("language", "en"),+ reasoning=resolve_reasoning(reasoning, cfg),+ enable_onboarding=bool(cfg.get("enable_onboarding", True)),+ wiki_style=style,+ )+ import dataclasses++ tier1_top_n = cfg.get("tier1_top_n")+ if tier1_top_n is not None:+ config = dataclasses.replace(config, tier1_top_n=tier1_top_n)++ exclude_patterns = list(cfg.get("exclude_patterns") or [])++ start = time.monotonic()+ generated_pages = run_async(+ _run_restyle(repo_path, provider, config, exclude_patterns=exclude_patterns)+ )++ # Persist the new style. The default is removed (not written) to keep config+ # tidy. Recompute the config fingerprint AFTER the write so the next+ # `repowise update` doesn't see a config change and divert to a health rescore.+ if style == DEFAULT_STYLE:+ _remove_config_key(repo_path, "wiki_style")+ else:+ save_config_partial(repo_path, wiki_style=style)++ head = get_head_commit(repo_path)+ state["last_sync_commit"] = head+ state["total_pages"] = len(generated_pages)+ state["config_fingerprint"] = config_fingerprint(repo_path)+ save_state(repo_path, state)++ elapsed = time.monotonic() - start+ console.print(+ f"[bold green]Restyled to '{style}'[/bold green] in {elapsed:.1f}s — "+ f"{len(generated_pages)} pages regenerated."+ )+++def _remove_config_key(repo_path: Path, key: str) -> None:+ """Drop a single key from ``.repowise/config.yaml`` if present (keeps it tidy)."""+ import yaml++ from repowise.cli.helpers import CONFIG_FILENAME, get_repowise_dir++ config_path = get_repowise_dir(repo_path) / CONFIG_FILENAME+ if not config_path.exists():+ return+ existing = load_config(repo_path)+ if key in existing:+ existing.pop(key)+ config_path.write_text(+ yaml.dump(existing, default_flow_style=False, sort_keys=False),+ encoding="utf-8",+ )++[email protected]("wiki-styles")[email protected]("path", required=False, default=None)+def wiki_styles_command(path: str | None) -> None:+ """List the available wiki documentation styles (and the repo's current one)."""+ current = None+ repo_path: Path | str | None = None+ try:+ repo_path = resolve_repo_path(path)+ cfg = load_config(repo_path)+ current = resolve_style(cfg.get("wiki_style"), repo_path=repo_path).name+ except Exception:+ repo_path = None # not in a repo — just list the catalogue+ _print_styles(current=current, repo_path=repo_path)+ console.print("\nSwitch with [bold]repowise restyle <style>[/bold].")diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex 8de56b4b5..a084323c5 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -1009,6 +1009,9 @@ def update_command(language=language,reasoning=resolve_reasoning(reasoning, cfg),enable_onboarding=enable_onboarding_cfg,+ # Honor the wiki style chosen at init (or via `repowise restyle`) so pages+ # regenerated for changed files match the rest of the wiki's voice.+ wiki_style=cfg.get("wiki_style", "comprehensive"),)provider = resolve_provider(provider_name, model, repo_path=repo_path)@@ -1171,6 +1174,7 @@ def update_command(vector_store=decision_vector_store,language=config.language,prior_pages=prior_pages,+ repo_path=repo_path,)repo_name = repo_path.namediff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.pyindex 183dc5fcd..1f5cff875 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py@@ -2,6 +2,7 @@from __future__ import annotations+from datetime import UTCfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -25,7 +26,7 @@ if TYPE_CHECKING:# ----------------------------------------------------------------------------def _require_workspace(start: Path | None = None) -> tuple[Path, "WorkspaceConfig"]: # type: ignore[name-defined]+def _require_workspace(start: Path | None = None) -> tuple[Path, WorkspaceConfig]: # type: ignore[name-defined]"""Load the workspace config or abort with a helpful message.Returns ``(ws_root, ws_config)``.@@ -190,12 +191,12 @@ def _format_relative_time(iso_timestamp: str | None) -> str:if not iso_timestamp:return "-"try:- from datetime import datetime, timezone+ from datetime import datetimedt = datetime.fromisoformat(iso_timestamp)if dt.tzinfo is None:- dt = dt.replace(tzinfo=timezone.utc)- now = datetime.now(timezone.utc)+ dt = dt.replace(tzinfo=UTC)+ now = datetime.now(UTC)delta = now - dtseconds = int(delta.total_seconds())if seconds < 60:@@ -334,7 +335,7 @@ def _resolve_docs_flag(run_docs: bool | None,provider_name: str | None,ws_root: Path,- ws_config: "WorkspaceConfig", # type: ignore[name-defined]+ ws_config: WorkspaceConfig, # type: ignore[name-defined]) -> tuple[bool, str | None]:"""Decide whether ``workspace add`` should generate docs by default.@@ -448,7 +449,7 @@ def _run_index_for_repo(repo_path: Path,alias: str,ws_root: Path,- ws_config: "WorkspaceConfig", # type: ignore[name-defined]+ ws_config: WorkspaceConfig, # type: ignore[name-defined]*,generate_docs: bool = False,provider_name: str | None = None,@@ -463,7 +464,7 @@ def _run_index_for_repo(base commit), saves provider/model into ``config.yaml`` when docs ran,and re-runs cross-repo hooks so contracts/co-changes are fresh."""- from datetime import datetime, timezone+ from datetime import datetimefrom repowise.cli.helpers import (ensure_repowise_dir,@@ -614,7 +615,7 @@ def _run_index_for_repo(# Update workspace config entryentry = ws_config.get_repo(alias)if entry is not None:- entry.indexed_at = datetime.now(timezone.utc).isoformat()+ entry.indexed_at = datetime.now(UTC).isoformat()entry.last_commit_at_index = headws_config.save(ws_root)@@ -694,12 +695,17 @@ def _generate_docs_for_added_repo(continuegraph_builder.build()+ from repowise.core.repo_config import load_repo_config+config = GenerationConfig(max_concurrency=concurrency,reasoning=reasoning,+ wiki_style=load_repo_config(repo_path).get("wiki_style", "comprehensive"),)assembler = ContextAssembler(config)- generator = PageGenerator(provider, assembler, config, language=config.language)+ generator = PageGenerator(+ provider, assembler, config, language=config.language, repo_path=repo_path+ )async def _do() -> int:pages = await generator.generate_all(diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 228a2dbc2..106f85371 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -21,6 +21,7 @@ from repowise.cli.commands.hook_cmd import hook_groupfrom repowise.cli.commands.init_cmd import init_commandfrom repowise.cli.commands.mcp_cmd import mcp_commandfrom repowise.cli.commands.reindex_cmd import reindex_command+from repowise.cli.commands.restyle_cmd import restyle_command, wiki_styles_commandfrom repowise.cli.commands.risk_cmd import risk_commandfrom repowise.cli.commands.saved_cmd import saved_commandfrom repowise.cli.commands.search_cmd import search_command@@ -77,6 +78,8 @@ register_command(watch_command)register_command(serve_command)register_command(mcp_command)register_command(reindex_command)+register_command(restyle_command)+register_command(wiki_styles_command)register_command(workspace_group)cli_registry.apply(cli)diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.pyindex e72a04866..f166b06cd 100644--- a/packages/core/src/repowise/core/generation/models.py+++ b/packages/core/src/repowise/core/generation/models.py@@ -148,6 +148,12 @@ class GenerationConfig:jobs_dir: str = ".repowise/jobs"large_file_source_pct: float = 0.4 # use structural summary when source tokens > budget * thislanguage: str = "en"+ # Wiki documentation style (voice/density). Resolved to a StyleSpec by+ # ``generation.styles.resolve_style``. "comprehensive" (default) is inert and+ # reproduces the pre-style-feature output exactly. A style change folds into+ # each page's source_hash, so `repowise update` regenerates affected pages in+ # the new style. See generation/styles/ and WIKI_STYLES_PLAN.md.+ wiki_style: str = "comprehensive"# ---- Tiered doc generation (large-repo scale) ---------------------# Caps the number of file pages that receive full LLM generation.# The top ``tier1_top_n`` selected file pages by PageRank arediff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.pyindex bd1c41637..70a6b9ad4 100644--- a/packages/core/src/repowise/core/generation/page_generator/core.py+++ b/packages/core/src/repowise/core/generation/page_generator/core.py@@ -34,6 +34,7 @@ from ..models import (compute_page_id,compute_source_hash,)+from ..styles import ONBOARDING_PAGE_TYPE, resolve_stylefrom .decision_harvest import (HARVEST_DIRECTIVE,HARVESTABLE_PAGE_TYPES,@@ -132,12 +133,17 @@ class PageGenerator(PerTypeGenerationMixin):vector_store: Any | None = None,language: str = "en",prior_pages: dict[str, PriorPage] | None = None,+ repo_path: Path | str | None = None,) -> None:self._provider = providerself._assembler = assemblerself._config = configself._vector_store = vector_storeself._language = language+ # Resolve the wiki style once. "comprehensive" (default) is inert, so this+ # is a no-op for repos that never opt in. ``repo_path`` lets a user-defined+ # ``.repowise/styles/<name>`` style resolve (Phase 5).+ self._style = resolve_style(getattr(config, "wiki_style", None), repo_path=repo_path)self._cache: dict[str, GeneratedResponse] = {}# Map of page_id → PriorPage from previous generation runs. When the# rendered prompt's source_hash matches the prior page's hash AND the@@ -149,7 +155,18 @@ class PageGenerator(PerTypeGenerationMixin):if jinja_env is None:templates_dir = Path(__file__).parent.parent / "templates"- loader = jinja2.FileSystemLoader(str(templates_dir))+ # A custom style may ship its own templates/ dir (Layer 2). Resolve it+ # first via ChoiceLoader, falling back to the built-in templates for any+ # page type the style does not override.+ if self._style.template_dir is not None:+ loader: jinja2.BaseLoader = jinja2.ChoiceLoader(+ [+ jinja2.FileSystemLoader(str(self._style.template_dir)),+ jinja2.FileSystemLoader(str(templates_dir)),+ ]+ )+ else:+ loader = jinja2.FileSystemLoader(str(templates_dir))jinja_env = jinja2.Environment(loader=loader,undefined=jinja2.StrictUndefined,@@ -319,7 +336,7 @@ class PageGenerator(PerTypeGenerationMixin):search by the level runner like any other page. No provider call andno hallucination check (the content is factual by construction)."""- content = self._render("file_page_tier2.j2", ctx=ctx)+ content = self._render("file_page_tier2.j2", style_prefix=False, ctx=ctx)now = _now_iso()page = GeneratedPage(page_id=compute_page_id("file_page", parsed.file_info.path),@@ -413,6 +430,11 @@ class PageGenerator(PerTypeGenerationMixin):# The directive is constant per run, so prefix caching still holds.if self._config.harvest_decisions and page_type in HARVESTABLE_PAGE_TYPES:base_system = base_system + HARVEST_DIRECTIVE+ # Wiki style: append the style's framing note. Constant per run (per page+ # type), so prefix caching still holds. Inert for the default style.+ base_system = base_system + self._style.system_prompt_suffix(+ is_onboarding=page_type == ONBOARDING_PAGE_TYPE+ )# Sanitize the configured language code: lower, strip, drop anything that isn't# alphanumeric or underscore. Prevents user-supplied config from injecting# newlines or extra instructions into the system prompt.@@ -433,8 +455,17 @@ class PageGenerator(PerTypeGenerationMixin):return instruction + base_systemdef _compute_cache_key(self, page_type: str, user_prompt: str) -> str:- """Return SHA256(model + language + page_type + user_prompt) as cache key."""- raw = f"{self._provider.model_name}:{self._language}:{page_type}:{user_prompt}"+ """Return SHA256(model + language + style + page_type + user_prompt) as cache key.++ The style fingerprint is already embedded in ``user_prompt`` for active+ styles, but include it explicitly so the in-memory cache never collides+ across styles even if a future change moves the directive out of the prompt+ body. Empty for the default style → key is unchanged from before.+ """+ raw = (+ f"{self._provider.model_name}:{self._language}:"+ f"{self._style.fingerprint}:{page_type}:{user_prompt}"+ )return hashlib.sha256(raw.encode()).hexdigest()def _build_generated_page(@@ -448,7 +479,7 @@ class PageGenerator(PerTypeGenerationMixin):) -> GeneratedPage:"""Wrap a GeneratedResponse in a GeneratedPage."""now = _now_iso()- return GeneratedPage(+ page = GeneratedPage(page_id=compute_page_id(page_type, target_path),page_type=page_type,title=title,@@ -465,8 +496,28 @@ class PageGenerator(PerTypeGenerationMixin):created_at=now,updated_at=now,)+ # Record the effective style as page provenance (D10). Only for active+ # styles, so default ("comprehensive") pages keep byte-identical metadata.+ if self._style.is_active:+ page.metadata["style"] = self._style.name+ return page++ def _render(self, template_name: str, *, style_prefix: bool = True, **kwargs: Any) -> str:+ """Render a Jinja2 template with the given kwargs.- def _render(self, template_name: str, **kwargs: Any) -> str:- """Render a Jinja2 template with the given kwargs."""+ For LLM *prompts* (the default), the active wiki style's directive is+ prepended so the model adjusts its voice and — critically — the directive+ becomes part of the rendered text that ``source_hash`` is computed over, so+ a style change invalidates the cache and regenerates the page on update.++ ``style_prefix=False`` is for deterministic templates whose render output is+ the page *content* itself (tier-2 file pages), not a prompt — those must not+ carry a style directive.+ """template = self._jinja_env.get_template(template_name)- return template.render(**kwargs)+ body = template.render(**kwargs)+ if not style_prefix:+ return body+ is_onboarding = template_name.startswith("onboarding/")+ prefix = self._style.user_prompt_prefix(is_onboarding=is_onboarding)+ return prefix + body if prefix else bodydiff --git a/packages/core/src/repowise/core/generation/styles/__init__.py b/packages/core/src/repowise/core/generation/styles/__init__.pynew file mode 100644index 000000000..72d279524--- /dev/null+++ b/packages/core/src/repowise/core/generation/styles/__init__.py@@ -0,0 +1,25 @@+"""Wiki documentation styles.++A *style* controls the voice and density of generated wiki pages (terse vs+narrative, AI-first vs human-first) without changing their structural markdown+contract. See ``spec.py`` for the model and ``registry.py`` for the built-ins.+"""++from __future__ import annotations++from .registry import (+ DEFAULT_STYLE,+ is_known_style,+ list_styles,+ resolve_style,+)+from .spec import ONBOARDING_PAGE_TYPE, StyleSpec++__all__ = [+ "DEFAULT_STYLE",+ "ONBOARDING_PAGE_TYPE",+ "StyleSpec",+ "is_known_style",+ "list_styles",+ "resolve_style",+]diff --git a/packages/core/src/repowise/core/generation/styles/directives.py b/packages/core/src/repowise/core/generation/styles/directives.pynew file mode 100644index 000000000..400642cb8--- /dev/null+++ b/packages/core/src/repowise/core/generation/styles/directives.py@@ -0,0 +1,80 @@+"""Style directive text — the actual voice instructions for each built-in style.++Kept separate from the wiring in ``registry.py`` so the prose a style injects is+easy to read, diff, and tune in one place. Each constant is the ``user_directive``+(prepended to the LLM user prompt) or ``system_note`` (appended to the system+prompt) for a style.++These are the load-bearing content of the feature: editing a directive changes the+style's ``fingerprint`` (see ``spec.py``), which regenerates affected pages on the+next update. Keep them concrete and example-driven — the model follows showed+behaviour far better than abstract adjectives.+"""++from __future__ import annotations++# ---------------------------------------------------------------------------+# caveman — token-condensed, AI-first+# ---------------------------------------------------------------------------++CAVEMAN_SYSTEM_NOTE = (+ "STYLE OVERRIDE — caveman: this page is read by an LLM agent, not a human. "+ "Optimise for facts-per-token. Be terse and dense, never comprehensive prose. "+ "Preserve accuracy and every required section heading; cut everything else."+)++CAVEMAN_DIRECTIVE = (+ "Write this page in CAVEMAN style — maximally token-condensed for an AI reader.\n"+ "- Keep every required `##` heading, but write the body as terse fragments, not sentences.\n"+ "- Drop articles (a/an/the), linking verbs (is/are/was), and filler words.\n"+ "- One fact per line. Prefer bullet lists and `key -> value` arrows over prose.\n"+ "- Use compact notation: `->` for flows-to/returns, `&` for and, `w/` for with.\n"+ "- No hedging, no restating the heading, no adjectives for flavour, no closing summary.\n"+ "- Keep code identifiers, file paths, and signatures verbatim — never abbreviate those.\n"+ "- Aim for ~60-75% fewer tokens than normal prose while preserving every fact.\n"+ "Example — instead of: 'This module is responsible for parsing the user's "+ "configuration files and validating them against the schema.'\n"+ "Write: 'Parses user config files -> validates vs schema.'"+)++# ---------------------------------------------------------------------------+# reference — API-manual, signature-dense, minimal narrative+# ---------------------------------------------------------------------------++REFERENCE_SYSTEM_NOTE = (+ "STYLE OVERRIDE — reference: write like an API reference manual. Lead with the "+ "contract (signatures, parameters, returns). Document the public surface "+ "exhaustively and precisely; omit motivation and tutorial narration."+)++REFERENCE_DIRECTIVE = (+ "Write this page in REFERENCE style — an API manual, not a narrative.\n"+ "- Keep every required `##` heading.\n"+ "- For each symbol: signature first, then a one-line purpose, then Parameters, "+ "Returns, and Raises as compact lists or tables.\n"+ "- Document the public surface exhaustively; mention internals only when they "+ "affect callers.\n"+ "- Prefer tables for parameters and returns. Keep types and default values exact.\n"+ "- Neutral, precise, present tense. No second person, no motivation prose, no marketing.\n"+ "- Do not invent symbols, parameters, or behaviour absent from the context."+)++# ---------------------------------------------------------------------------+# tutorial — narrative, beginner-friendly, teaches the codebase+# ---------------------------------------------------------------------------++TUTORIAL_SYSTEM_NOTE = (+ "STYLE OVERRIDE — tutorial: write for a developer new to this codebase. Teach, "+ "don't merely describe — build understanding step by step while staying strictly "+ "accurate to the supplied context."+)++TUTORIAL_DIRECTIVE = (+ "Write this page in TUTORIAL style — guided and beginner-friendly.\n"+ "- Keep every required `##` heading. Within each section, build understanding "+ "step by step: what it does, why it exists, how it fits the bigger picture.\n"+ "- Use plain language and short worked examples grounded only in the supplied context.\n"+ "- Define jargon on first use. Add a one-line 'In short:' takeaway where it helps.\n"+ "- Friendly second person ('you') is welcome. Stay accurate; do not pad or repeat.\n"+ "- Never invent APIs, file paths, or behaviour that is not present in the context."+)diff --git a/packages/core/src/repowise/core/generation/styles/registry.py b/packages/core/src/repowise/core/generation/styles/registry.pynew file mode 100644index 000000000..325cd9e67--- /dev/null+++ b/packages/core/src/repowise/core/generation/styles/registry.py@@ -0,0 +1,174 @@+"""Style registry — declares the built-in styles and resolves a name to a StyleSpec.++Resolution order is built-in first, then a user-defined custom style under+``.repowise/styles/<name>/`` (a power-user feature). ``comprehensive`` is the+canonical default and fallback.++Custom styles are plain data: a ``style.yaml`` describing the voice plus an+optional ``templates/`` directory (Layer 2). User-supplied text is treated as+untrusted: names are pattern-validated to prevent path traversal, and directive+text is length-bounded so a runaway file can't balloon every prompt.+"""++from __future__ import annotations++import re+from pathlib import Path++import structlog++from . import directives as d+from .spec import StyleSpec++log = structlog.get_logger(__name__)++DEFAULT_STYLE = "comprehensive"++# Custom-style guard rails.+_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$")+_MAX_DIRECTIVE_CHARS = 8000+_STYLES_DIRNAME = "styles"++# ---------------------------------------------------------------------------+# Built-in styles (see WIKI_STYLES_PLAN.md D1). ``comprehensive`` is inert by+# design — empty directive and note — so it reproduces the pre-feature output+# byte-for-byte and never invalidates existing cached pages.+# ---------------------------------------------------------------------------++_BUILTIN_STYLES: dict[str, StyleSpec] = {+ "comprehensive": StyleSpec(+ name="comprehensive",+ description="Full, narrative documentation for humans and AI (default).",+ ),+ "caveman": StyleSpec(+ name="caveman",+ description="Token-condensed, AI-first pages — terse fragments, ~70% smaller.",+ user_directive=d.CAVEMAN_DIRECTIVE,+ system_note=d.CAVEMAN_SYSTEM_NOTE,+ onboarding_condenses=True,+ ),+ "reference": StyleSpec(+ name="reference",+ description="API-manual style — signature-dense, exhaustive, minimal narrative.",+ user_directive=d.REFERENCE_DIRECTIVE,+ system_note=d.REFERENCE_SYSTEM_NOTE,+ onboarding_condenses=False,+ ),+ "tutorial": StyleSpec(+ name="tutorial",+ description="Guided, beginner-friendly walkthroughs that teach the codebase.",+ user_directive=d.TUTORIAL_DIRECTIVE,+ system_note=d.TUTORIAL_SYSTEM_NOTE,+ onboarding_condenses=True,+ ),+}+++def _styles_root(repo_path: Path | str | None) -> Path | None:+ """Return the ``.repowise/styles`` directory for a repo, or None."""+ if repo_path is None:+ return None+ return Path(repo_path) / ".repowise" / _STYLES_DIRNAME+++def _clip(value: object) -> str:+ """Coerce to a length-bounded string (untrusted directive/note text)."""+ text = str(value or "")+ return text[:_MAX_DIRECTIVE_CHARS]+++def _load_custom_style(name: str, repo_path: Path | str | None) -> StyleSpec | None:+ """Load a user-defined style from ``.repowise/styles/<name>/style.yaml``.++ Returns None when the repo, directory, or manifest is absent or unreadable, or+ when *name* is not a safe identifier. Never raises — a broken custom style+ degrades to "not found" (callers fall back to the default).+ """+ if not _NAME_RE.match(name):+ return None+ root = _styles_root(repo_path)+ if root is None:+ return None+ style_dir = root / name+ manifest = style_dir / "style.yaml"+ if not manifest.is_file():+ return None++ try:+ import yaml++ data = yaml.safe_load(manifest.read_text(encoding="utf-8")) or {}+ except Exception as exc: # malformed YAML / IO error → treat as absent+ log.warning("custom_style_unreadable", name=name, error=str(exc))+ return None+ if not isinstance(data, dict):+ return None++ user_directive = _clip(data.get("user_directive"))+ system_note = _clip(data.get("system_note"))+ # A custom style with no voice is pointless (and would be inert); reject so the+ # caller falls back rather than silently producing default output.+ if not user_directive and not system_note:+ log.warning("custom_style_empty", name=name)+ return None++ templates_dir = style_dir / "templates"+ template_dir = templates_dir if templates_dir.is_dir() else None++ try:+ version = int(data.get("style_version", 1))+ except (TypeError, ValueError):+ version = 1++ return StyleSpec(+ name=name,+ description=str(data.get("description") or f"Custom style '{name}'."),+ is_builtin=False,+ user_directive=user_directive,+ system_note=system_note,+ onboarding_condenses=bool(data.get("onboarding_condenses", False)),+ template_dir=template_dir,+ style_version=version,+ )+++def list_styles(repo_path: Path | str | None = None) -> list[StyleSpec]:+ """Return all available styles: built-ins plus discovered custom styles."""+ styles = list(_BUILTIN_STYLES.values())+ root = _styles_root(repo_path)+ if root is not None and root.is_dir():+ for child in sorted(root.iterdir()):+ if not child.is_dir() or child.name in _BUILTIN_STYLES:+ continue+ spec = _load_custom_style(child.name, repo_path)+ if spec is not None:+ styles.append(spec)+ return styles+++def is_known_style(name: str | None, repo_path: Path | str | None = None) -> bool:+ """True when *name* resolves to a built-in or a valid custom style."""+ if not name:+ return False+ key = name.strip().lower()+ if key in _BUILTIN_STYLES:+ return True+ return _load_custom_style(key, repo_path) is not None+++def resolve_style(name: str | None, repo_path: Path | str | None = None) -> StyleSpec:+ """Resolve a style name to a :class:`StyleSpec`, defaulting to ``comprehensive``.++ Built-ins win; then a custom ``.repowise/styles/<name>/`` style; otherwise the+ default. Unknown names fall back rather than raising — generation should never+ hard-fail on a stale or mistyped config value; the CLI/API validate up front+ where a crisp error is more useful.+ """+ key = (name or DEFAULT_STYLE).strip().lower()+ builtin = _BUILTIN_STYLES.get(key)+ if builtin is not None:+ return builtin+ custom = _load_custom_style(key, repo_path)+ if custom is not None:+ return custom+ return _BUILTIN_STYLES[DEFAULT_STYLE]diff --git a/packages/core/src/repowise/core/generation/styles/spec.py b/packages/core/src/repowise/core/generation/styles/spec.pynew file mode 100644index 000000000..9eebbb400--- /dev/null+++ b/packages/core/src/repowise/core/generation/styles/spec.py@@ -0,0 +1,116 @@+"""StyleSpec — the value object describing one wiki documentation style.++A *style* governs the **voice and density** of generated wiki pages, never their+structural contract: every style still emits the same required ``##`` headings and+section skeleton (see WIKI_STYLES_PLAN.md, decision D3). Styles differ in two ways:++* ``user_directive`` — a constant block **prepended to the user prompt** of every+ LLM page. This is the primary lever: the model reads it and adjusts its prose.+* ``system_note`` — a constant block **appended to the system prompt**, used to+ re-frame the base "comprehensive, accurate" instruction when a style needs a+ different posture (e.g. "be terse").++The class is deliberately data-only. All built-in styles are declared in+``registry.py``; resolution (built-in, and later custom ``.repowise/styles/``)+goes through ``resolve_style``.++Cache contract (the load-bearing detail — see WIKI_STYLES_PLAN.md §2):+the per-style ``fingerprint`` is woven into the rendered user prompt for active+styles, so a style change flows into each page's ``source_hash`` and the existing+incremental-update machinery regenerates exactly the affected pages. The+``comprehensive`` style is inert (empty directive + note) and therefore produces+byte-identical prompts to the pre-feature behaviour — existing wikis never+regenerate spuriously when the feature lands.+"""++from __future__ import annotations++import hashlib+from dataclasses import dataclass+from pathlib import Path++# The page_type used by the curated onboarding collection. Onboarding pages are+# narrative by design; whether a style condenses them is a per-style policy (D9).+ONBOARDING_PAGE_TYPE = "onboarding"+++@dataclass(frozen=True)+class StyleSpec:+ """One wiki documentation style (voice + density), resolved at generation time.++ Attributes:+ name: Stable identifier typed by users (CLI/config value).+ description: One-line, user-facing summary (shown in selectors).+ is_builtin: True for shipped styles; False for ``.repowise/styles``.+ user_directive: Constant block prepended to every LLM user prompt.+ Empty string = inert (the ``comprehensive`` baseline).+ system_note: Constant block appended to every system prompt.+ onboarding_condenses: When False, the onboarding collection keeps the+ baseline narrative voice even under this style (D9).+ template_dir: Optional per-style template directory (Layer 2 /+ custom styles). ``None`` = use the base templates.+ style_version: Bump to force regeneration when a style's text+ changes in a way the fingerprint must capture.+ """++ name: str+ description: str+ is_builtin: bool = True+ user_directive: str = ""+ system_note: str = ""+ onboarding_condenses: bool = False+ template_dir: Path | None = None+ style_version: int = 1++ @property+ def is_active(self) -> bool:+ """True when this style changes output vs the inert baseline.++ An inert style (no directive and no note) renders prompts identically to+ the pre-feature code path, so it must contribute nothing to any hash.+ """+ return bool(self.user_directive or self.system_note)++ @property+ def fingerprint(self) -> str:+ """Short content hash over everything that affects this style's output.++ Empty for inert styles (so they leave prompt hashes untouched). For active+ styles it covers name, version, directive, and note — so editing any of+ them invalidates cached pages on the next update.+ """+ if not self.is_active:+ return ""+ h = hashlib.sha256()+ h.update(self.name.encode())+ h.update(str(self.style_version).encode())+ h.update(self.user_directive.encode())+ h.update(self.system_note.encode())+ return h.hexdigest()[:16]++ def _applies_to(self, *, is_onboarding: bool) -> bool:+ """Whether this style's voice applies to a page of the given kind."""+ if not self.is_active:+ return False+ return not (is_onboarding and not self.onboarding_condenses)++ def user_prompt_prefix(self, *, is_onboarding: bool) -> str:+ """Block to prepend to a page's user prompt (``""`` to leave it untouched).++ The leading marker comment carries the fingerprint so that *any* change to+ the style — including a ``system_note``-only change that wouldn't otherwise+ alter the user prompt — flows into ``source_hash`` and triggers regen.+ """+ if not self._applies_to(is_onboarding=is_onboarding):+ return ""+ marker = f"<!-- repowise-style:{self.name} fp:{self.fingerprint} -->"+ body = self.user_directive.strip()+ block = marker if not body else f"{marker}\n{body}"+ return f"{block}\n\n"++ def system_prompt_suffix(self, *, is_onboarding: bool) -> str:+ """Block to append to a page's system prompt (``""`` to leave it untouched)."""+ if not self._applies_to(is_onboarding=is_onboarding):+ return ""+ note = self.system_note.strip()+ return f"\n\n{note}" if note else ""diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 3e18bb3d0..4f5b3320b 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -174,6 +174,7 @@ async def run_pipeline(progress: ProgressCallback | None = None,cost_tracker: Any | None = None,generation_config: Any | None = None,+ wiki_style: str | None = None,existing_kg_fingerprint: str | None = None,on_page_ready: Any | None = None,resume_controller: ResumeController | None = None,@@ -595,9 +596,14 @@ async def run_pipeline(from repowise.core.reasoning import resolve_reasoningfrom repowise.core.repo_config import load_repo_config+ _cfg = load_repo_config(repo_path)+ # Wiki style precedence: explicit param (server passes the DB-settings+ # value) > repo-local config.yaml (CLI/init) > default.+ _style = wiki_style or _cfg.get("wiki_style", "comprehensive")resolved_generation_config = GenerationConfig(max_concurrency=concurrency,- reasoning=resolve_reasoning(config=load_repo_config(repo_path)),+ reasoning=resolve_reasoning(config=_cfg),+ wiki_style=_style,)# Phase 2 enrichment: flag framework-defined HTTP surfaces (FastAPI,diff --git a/packages/core/src/repowise/core/pipeline/phases/generation.py b/packages/core/src/repowise/core/pipeline/phases/generation.pyindex d2a642224..5eccbd0c9 100644--- a/packages/core/src/repowise/core/pipeline/phases/generation.py+++ b/packages/core/src/repowise/core/pipeline/phases/generation.py@@ -120,6 +120,7 @@ async def run_generation(vector_store=vector_store,language=config.language,prior_pages=prior_pages or {},+ repo_path=repo_path,)generated_pages = await generator.generate_all(diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex 5060faed3..d3252e456 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -67,6 +67,38 @@ def _repo_exclude_patterns(repo: Any, repo_path: str) -> list[str]:return patterns+def _repo_wiki_style(repo: Any, repo_path: str) -> str:+ """Resolve a server job's effective wiki style from both config sources.++ Web-managed repos store the style in ``Repository.settings_json`` (set via the+ PATCH endpoint); CLI/``repowise init`` write it to ``.repowise/config.yaml``.+ Settings take precedence (the web UI is the more deliberate, recent signal),+ then config.yaml, then the default. Unknown values resolve to the default+ rather than failing the job.+ """+ from repowise.core.generation.styles import resolve_style++ style: str | None = None+ try:+ settings = json.loads(getattr(repo, "settings_json", "") or "{}")+ if isinstance(settings, dict):+ style = settings.get("wiki_style")+ except (TypeError, ValueError):+ logger.debug("repo_settings_json_unparsable", repo_path=repo_path)++ if not style:+ try:+ from repowise.core.repo_config import load_repo_config++ cfg = load_repo_config(Path(repo_path))+ if isinstance(cfg, dict):+ style = cfg.get("wiki_style")+ except Exception:+ logger.debug("repo_config_yaml_unreadable", repo_path=repo_path)++ return resolve_style(style, repo_path=repo_path).name++# Phase → numeric level mapping for job.current_level_PHASE_LEVELS = {"traverse": 0,@@ -260,6 +292,8 @@ async def execute_job(# Resolve excludes while ``repo`` is still session-attached. Every# job entry point flows through here, so this covers them all.exclude_patterns = _repo_exclude_patterns(repo, repo_path)+ # Resolve the wiki style while ``repo`` is still session-attached.+ wiki_style = _repo_wiki_style(repo, repo_path)config = json.loads(job.config_json) if job.config_json else {}is_full_resync = config.get("mode") == "full_resync"@@ -296,6 +330,7 @@ async def execute_job(vector_store=vector_store,progress=progress,exclude_patterns=exclude_patterns or None,+ wiki_style=wiki_style,)# ---- Incremental page regeneration for sync mode ------------------@@ -310,6 +345,7 @@ async def execute_job(llm_client,config,progress,+ repo_wiki_style=wiki_style,)# ---- Persist results -----------------------------------------------@@ -456,6 +492,7 @@ async def _incremental_page_regen(llm_client: Any,job_config: dict,progress: Any | None,+ repo_wiki_style: str = "comprehensive",) -> list:"""Regenerate only wiki pages affected by recent changes.@@ -529,14 +566,24 @@ async def _incremental_page_regen(affected_source = {p: s for p, s in result.source_map.items() if p in regen_set}from repowise.core.generation import ContextAssembler, GenerationConfig, PageGenerator++ # Effective style: a per-page override carried in the job config (set by+ # the regenerate endpoint, D10) wins over the repo's default style.+ from repowise.core.generation.styles import resolve_stylefrom repowise.core.reasoning import resolve_reasoningfrom repowise.core.repo_config import load_repo_config+ effective_style = resolve_style(+ job_config.get("style") or repo_wiki_style, repo_path=repo_path+ ).namegeneration_config = GenerationConfig(- reasoning=resolve_reasoning(config=load_repo_config(repo_path))+ reasoning=resolve_reasoning(config=load_repo_config(repo_path)),+ wiki_style=effective_style,)assembler = ContextAssembler(generation_config)- generator = PageGenerator(llm_client, assembler, generation_config)+ generator = PageGenerator(+ llm_client, assembler, generation_config, repo_path=repo_path+ )pages = await generator.generate_all(affected_parsed,diff --git a/packages/server/src/repowise/server/routers/pages.py b/packages/server/src/repowise/server/routers/pages.pyindex 261837354..3896b946b 100644--- a/packages/server/src/repowise/server/routers/pages.py+++ b/packages/server/src/repowise/server/routers/pages.py@@ -7,10 +7,10 @@ parameter greedily matches the suffix as part of the page_id.from __future__ import annotations+from fastapi import APIRouter, Depends, HTTPException, Queryfrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSession-from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import _now_utcfrom repowise.server.deps import get_db_session, verify_api_key@@ -102,18 +102,39 @@ async def update_page_notes(@router.post("/lookup/regenerate", status_code=202)async def regenerate_page_by_query(page_id: str = Query(..., description="Page ID"),+ style: str | None = Query(+ None,+ description="Optional wiki style to regenerate this page in (per-page override).",+ ),session: AsyncSession = Depends(get_db_session), # noqa: B008) -> dict:- """Force-regenerate a single wiki page (page_id as query param)."""+ """Force-regenerate a single wiki page (page_id as query param).++ An optional ``style`` overrides the repo's default style for this page only+ (D10). It is validated here and carried in the job config; the executor+ resolves it when regenerating.+ """page = await crud.get_page(session, page_id)if page is None:raise HTTPException(status_code=404, detail="Page not found")+ job_config: dict = {"mode": "single_page", "page_id": page_id}+ if style is not None:+ from repowise.core.generation.styles import is_known_style, list_styles++ if not is_known_style(style):+ valid = ", ".join(s.name for s in list_styles())+ raise HTTPException(+ status_code=400,+ detail=f"Unknown style '{style}'. Valid styles: {valid}.",+ )+ job_config["style"] = style+job = await crud.upsert_generation_job(session,repository_id=page.repository_id,status="pending",- config={"mode": "single_page", "page_id": page_id},+ config=job_config,)return {"job_id": job.id, "status": "accepted"}diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex 8b44ce5f5..00ca33fd8 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -8,11 +8,11 @@ import loggingimport zipfilefrom pathlib import Path, PurePosixPath+from fastapi import APIRouter, Depends, HTTPException, Query, Request+from fastapi.responses import PlainTextResponse, StreamingResponsefrom sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSession-from fastapi import APIRouter, Depends, HTTPException, Query, Request-from fastapi.responses import PlainTextResponse, StreamingResponsefrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (@@ -99,8 +99,8 @@ async def list_repos(if ws_config is None or ws_root is None:return responses- from pathlib import Path as _Pimport json as _json+ from pathlib import Path as _Pws_root_path = _P(ws_root)# Map local_path → alias entry for quick attach on indexed rows.@@ -131,7 +131,8 @@ async def list_repos(pass# Synthesize entries for repos in the workspace that aren't indexed yet.- from datetime import datetime, UTC as _UTC+ from datetime import UTC as _UTC+ from datetime import datetimenow = datetime.now(_UTC)for entry in ws_config.repos:@@ -199,6 +200,17 @@ async def update_repo(if body.settings is not None:import json+ from repowise.core.generation.styles import is_known_style, list_styles++ # Validate a wiki_style setting up front so a typo surfaces as a 400 here+ # rather than silently falling back to the default during generation.+ style = body.settings.get("wiki_style")+ if style is not None and not is_known_style(style):+ valid = ", ".join(s.name for s in list_styles())+ raise HTTPException(+ status_code=400,+ detail=f"Unknown wiki_style '{style}'. Valid styles: {valid}.",+ )repo.settings_json = json.dumps(body.settings)await session.flush()return RepoResponse.from_orm(repo)@@ -322,7 +334,9 @@ async def sync_repo(.limit(1))if active.scalar_one_or_none() is not None:- raise HTTPException(status_code=409, detail="A sync job is already in progress for this repository")+ raise HTTPException(+ status_code=409, detail="A sync job is already in progress for this repository"+ )job = await crud.upsert_generation_job(session,@@ -360,7 +374,9 @@ async def full_resync(.limit(1))if active.scalar_one_or_none() is not None:- raise HTTPException(status_code=409, detail="A sync job is already in progress for this repository")+ raise HTTPException(+ status_code=409, detail="A sync job is already in progress for this repository"+ )job = await crud.upsert_generation_job(session,@@ -382,7 +398,7 @@ def _resolve_repo_session_factory(app_state, repo_id: str):``resolve_session_factory`` (or its request-scoped sibling``resolve_request_session_factory``) directly."""- from repowise.server.deps import resolve_session_factory # noqa: PLC0415+ from repowise.server.deps import resolve_session_factoryreturn resolve_session_factory(app_state, repo_id)@@ -460,7 +476,9 @@ async def export_wiki(if repo is None:raise HTTPException(status_code=404, detail="Repository not found")- pages = (await session.execute(select(Page).where(Page.repository_id == repo_id))).scalars().all()+ pages = (+ (await session.execute(select(Page).where(Page.repository_id == repo_id))).scalars().all()+ )if not pages:raise HTTPException(status_code=404, detail="No pages to export")@@ -468,11 +486,7 @@ async def export_wiki(with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:for page in pages:target = page.target_path or page.id- safe = (- target.replace("::", "/")- .replace("->", "--")- .replace("\\", "/")- )+ safe = target.replace("::", "/").replace("->", "--").replace("\\", "/")path = PurePosixPath("wiki") / page.page_type / safeif path.suffix != ".md":path = path.with_suffix(path.suffix + ".md")@@ -492,7 +506,7 @@ async def export_wiki(@router.get("/{repo_id}/file-content")async def get_file_content(repo_id: str,- file_path: str = Query(...), # noqa: B008+ file_path: str = Query(...),session: AsyncSession = Depends(get_db_session), # noqa: B008) -> PlainTextResponse:"""Return raw file content from the repository's local checkout."""diff --git a/packages/types/src/settings.ts b/packages/types/src/settings.tsindex 31626d353..7ec29bdd4 100644--- a/packages/types/src/settings.ts+++ b/packages/types/src/settings.ts@@ -6,8 +6,48 @@* the full save round-trip via its own `updateRepo` API.*/+/**+ * Built-in wiki documentation styles. Mirrors the Python registry in+ * `packages/core/.../generation/styles/registry.py`. Custom styles+ * (`.repowise/styles/`) are a CLI/power-user feature and are not surfaced here.+ */+export type WikiStyle = "comprehensive" | "caveman" | "reference" | "tutorial";++export const DEFAULT_WIKI_STYLE: WikiStyle = "comprehensive";++export interface WikiStyleOption {+ id: WikiStyle;+ label: string;+ description: string;+}++export const WIKI_STYLES: readonly WikiStyleOption[] = [+ {+ id: "comprehensive",+ label: "Comprehensive",+ description: "Full, narrative documentation for humans and AI (default).",+ },+ {+ id: "caveman",+ label: "Caveman",+ description: "Token-condensed, AI-first pages — terse fragments, ~70% smaller.",+ },+ {+ id: "reference",+ label: "Reference",+ description: "API-manual style — signature-dense, exhaustive, minimal narrative.",+ },+ {+ id: "tutorial",+ label: "Tutorial",+ description: "Guided, beginner-friendly walkthroughs that teach the codebase.",+ },+] as const;+export interface RepoSettingsValue {name: string;default_branch: string;exclude_patterns: string[];+ /** Documentation voice/density. Defaults to "comprehensive" when unset. */+ wiki_style?: WikiStyle;}diff --git a/packages/ui/__tests__/settings/general-form.test.tsx b/packages/ui/__tests__/settings/general-form.test.tsxindex cce45ee6a..a1e8371cc 100644--- a/packages/ui/__tests__/settings/general-form.test.tsx+++ b/packages/ui/__tests__/settings/general-form.test.tsx@@ -42,4 +42,45 @@ describe("GeneralForm", () => {// Add-pattern input is suppressed in read-only mode.expect(screen.queryByLabelText("New excluded pattern")).not.toBeInTheDocument();});++ it("defaults the style to comprehensive and submits it", async () => {+ const onSubmit = vi.fn().mockResolvedValue(undefined);+ render(<GeneralForm value={baseValue} onSubmit={onSubmit} />);+ // The comprehensive option is selected by default.+ const comprehensive = screen.getByRole("radio", { name: /Comprehensive/i });+ expect(comprehensive).toHaveAttribute("aria-checked", "true");++ fireEvent.change(screen.getByLabelText("Repository name"), {+ target: { value: "renamed" },+ });+ fireEvent.click(screen.getByRole("button", { name: /Save changes/i }));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));+ expect(onSubmit.mock.calls[0]![0]).toMatchObject({ wiki_style: "comprehensive" });+ });++ it("selecting a different style enables save and submits the new style", async () => {+ const onSubmit = vi.fn().mockResolvedValue(undefined);+ render(<GeneralForm value={baseValue} onSubmit={onSubmit} />);+ const save = screen.getByRole("button", { name: /Save changes/i });+ expect(save).toBeDisabled();++ fireEvent.click(screen.getByRole("radio", { name: /Caveman/i }));+ expect(save).toBeEnabled();+ fireEvent.click(save);+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));+ expect(onSubmit.mock.calls[0]![0]).toMatchObject({ wiki_style: "caveman" });+ });++ it("reflects a preset wiki_style from the value", () => {+ render(+ <GeneralForm+ value={{ ...baseValue, wiki_style: "reference" }}+ onSubmit={vi.fn()}+ />,+ );+ expect(screen.getByRole("radio", { name: /Reference/i })).toHaveAttribute(+ "aria-checked",+ "true",+ );+ });});diff --git a/packages/ui/src/settings/general-form.tsx b/packages/ui/src/settings/general-form.tsxindex 478646d59..111641367 100644--- a/packages/ui/src/settings/general-form.tsx+++ b/packages/ui/src/settings/general-form.tsx@@ -12,7 +12,8 @@ import {TooltipProvider,TooltipTrigger,} from "../ui/tooltip";-import type { RepoSettingsValue } from "@repowise-dev/types/settings";+import { DEFAULT_WIKI_STYLE, WIKI_STYLES } from "@repowise-dev/types";+import type { RepoSettingsValue, WikiStyle } from "@repowise-dev/types/settings";const SUGGESTIONS = ["vendor/",@@ -57,13 +58,17 @@ export function GeneralForm({const [branch, setBranch] = useState(value.default_branch);const [patterns, setPatterns] = useState<string[]>(value.exclude_patterns);const [newPattern, setNewPattern] = useState("");+ const [wikiStyle, setWikiStyle] = useState<WikiStyle>(+ value.wiki_style ?? DEFAULT_WIKI_STYLE,+ );const [saving, setSaving] = useState(false);const readOnly = onSubmit === undefined;const hasChanges =name !== value.name ||branch !== value.default_branch ||- !arraysEqual(patterns, value.exclude_patterns);+ !arraysEqual(patterns, value.exclude_patterns) ||+ wikiStyle !== (value.wiki_style ?? DEFAULT_WIKI_STYLE);function addPattern(pattern: string) {const trimmed = pattern.trim();@@ -84,6 +89,7 @@ export function GeneralForm({name,default_branch: branch,exclude_patterns: patterns,+ wiki_style: wikiStyle,});} finally {setSaving(false);@@ -232,6 +238,56 @@ export function GeneralForm({)}</div>+ <div className="space-y-3 border-t border-[var(--color-border-default)] pt-5">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">Documentation style</span>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Info className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ Controls the voice and density of generated wiki pages. Changing+ it regenerates the wiki in the new style.+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ <div+ role="radiogroup"+ aria-label="Documentation style"+ className="grid gap-2 sm:grid-cols-2 max-w-2xl"+ >+ {WIKI_STYLES.map((style) => {+ const selected = wikiStyle === style.id;+ return (+ <button+ key={style.id}+ type="button"+ role="radio"+ aria-checked={selected}+ disabled={readOnly}+ onClick={() => setWikiStyle(style.id)}+ className={`text-left rounded-md border px-3 py-2 transition-colors disabled:opacity-60 disabled:cursor-not-allowed ${+ selected+ ? "border-[var(--color-border-accent)] bg-[var(--color-bg-inset)]"+ : "border-[var(--color-border-default)] hover:bg-[var(--color-bg-inset)]"+ }`}+ >+ <span className="block text-sm font-medium text-[var(--color-text-primary)]">+ {style.label}+ </span>+ <span className="block text-xs text-[var(--color-text-secondary)]">+ {style.description}+ </span>+ </button>+ );+ })}+ </div>+ </div>+<div className="space-y-1.5"><ButtononClick={handleSave}diff --git a/packages/web/src/components/repos/repo-settings-form-wrapper.tsx b/packages/web/src/components/repos/repo-settings-form-wrapper.tsxindex 1489c5791..3c002a9e9 100644--- a/packages/web/src/components/repos/repo-settings-form-wrapper.tsx+++ b/packages/web/src/components/repos/repo-settings-form-wrapper.tsx@@ -1,43 +1,92 @@"use client";+import { useState } from "react";import { toast } from "sonner";import { GeneralForm } from "@repowise-dev/ui/settings/general-form";-import { updateRepo } from "@/lib/api/repos";+import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";+import { fullResyncRepo, updateRepo } from "@/lib/api/repos";import type { RepoResponse } from "@/lib/api/types";-import type { RepoSettingsValue } from "@repowise-dev/types/settings";+import { DEFAULT_WIKI_STYLE } from "@repowise-dev/types";+import type { RepoSettingsValue, WikiStyle } from "@repowise-dev/types/settings";interface Props {repo: RepoResponse;}export function RepoSettingsFormWrapper({ repo }: Props) {+ const currentStyle =+ (repo.settings?.wiki_style as WikiStyle | undefined) ?? DEFAULT_WIKI_STYLE;+const value: RepoSettingsValue = {name: repo.name,default_branch: repo.default_branch,exclude_patterns:(repo.settings?.exclude_patterns as string[] | undefined) ?? [],+ wiki_style: currentStyle,};+ // When the style changes on save, offer to regenerate the wiki in the new+ // voice (the persisted style only takes effect on the next generation).+ const [regenOpen, setRegenOpen] = useState(false);+ const [pendingStyle, setPendingStyle] = useState<WikiStyle | null>(null);+ const [regenLoading, setRegenLoading] = useState(false);+async function handleSubmit(next: RepoSettingsValue) {+ const nextStyle = next.wiki_style ?? DEFAULT_WIKI_STYLE;try {await updateRepo(repo.id, {name: next.name,default_branch: next.default_branch,- settings: { ...repo.settings, exclude_patterns: next.exclude_patterns },+ settings: {+ ...repo.settings,+ exclude_patterns: next.exclude_patterns,+ wiki_style: nextStyle,+ },});toast.success("Repository settings saved");+ if (nextStyle !== currentStyle) {+ setPendingStyle(nextStyle);+ setRegenOpen(true);+ }} catch (err) {toast.error(err instanceof Error ? err.message : "Failed to save settings");throw err;}}+ async function handleRegenerate() {+ setRegenLoading(true);+ try {+ await fullResyncRepo(repo.id);+ toast.info("Wiki regeneration queued");+ setRegenOpen(false);+ } catch (err) {+ toast.error(+ err instanceof Error ? err.message : "Failed to queue regeneration",+ );+ } finally {+ setRegenLoading(false);+ }+ }+return (- <GeneralForm- value={value}- onSubmit={handleSubmit}- localPath={repo.local_path}- remoteUrl={repo.url ?? undefined}- />+ <>+ <GeneralForm+ value={value}+ onSubmit={handleSubmit}+ localPath={repo.local_path}+ remoteUrl={repo.url ?? undefined}+ />+ <ConfirmDialog+ open={regenOpen}+ onOpenChange={setRegenOpen}+ title="Regenerate the wiki now?"+ description={`The documentation style was changed to "${pendingStyle ?? ""}". Regenerate the whole wiki now to apply it? This runs LLM generation (a cost). You can also do it later from Sync.`}+ confirmLabel="Regenerate now"+ cancelLabel="Later"+ loading={regenLoading}+ onConfirm={() => void handleRegenerate()}+ />+ </>);}diff --git a/packages/web/src/components/wiki/regenerate-button.tsx b/packages/web/src/components/wiki/regenerate-button.tsxindex 52bdf4dab..81e56c0f2 100644--- a/packages/web/src/components/wiki/regenerate-button.tsx+++ b/packages/web/src/components/wiki/regenerate-button.tsx@@ -8,6 +8,7 @@ import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";import { formatTokens } from "@repowise-dev/ui/lib/format";import { getPageById, regeneratePage } from "@/lib/api/pages";import { GenerationProgressWrapper as GenerationProgress } from "@/components/jobs/generation-progress-wrapper";+import { WIKI_STYLES } from "@repowise-dev/types";interface Props {pageId: string;@@ -20,6 +21,8 @@ export function RegenerateButtonWrapper({ pageId }: Props) {const [loading, setLoading] = useState(false);const [jobId, setJobId] = useState<string | null>(null);const [confirmOpen, setConfirmOpen] = useState(false);+ // Empty string = use the repo's default style; otherwise a per-page override.+ const [styleOverride, setStyleOverride] = useState("");// Token history for the cost estimate in the confirm dialog. Same SWR key// the wiki page uses, so this is usually already cached.@@ -42,7 +45,7 @@ export function RegenerateButtonWrapper({ pageId }: Props) {setConfirmOpen(false);setLoading(true);try {- const result = await regeneratePage(pageId);+ const result = await regeneratePage(pageId, styleOverride || undefined);setJobId(result.job_id);toast.info("Regeneration queued");} catch (e) {@@ -60,20 +63,39 @@ export function RegenerateButtonWrapper({ pageId }: Props) {setJobId(null);}+ const styleNote = styleOverride+ ? ` This page will be regenerated in the "${styleOverride}" style (overriding the repo default).`+ : "";+return (<>- <RegenerateButtonShell- onRegenerate={() => setConfirmOpen(true)}- isLoading={loading}- isInProgress={!!jobId}- onDialogClose={() => setJobId(null)}- jobSlot={jobId ? <GenerationProgress jobId={jobId} onDone={handleDone} /> : null}- />+ <div className="flex items-center gap-2">+ <select+ aria-label="Regenerate in style"+ value={styleOverride}+ onChange={(e) => setStyleOverride(e.target.value)}+ className="h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-default)] px-2 text-xs text-[var(--color-text-secondary)]"+ >+ <option value="">Repo style</option>+ {WIKI_STYLES.map((s) => (+ <option key={s.id} value={s.id}>+ {s.label}+ </option>+ ))}+ </select>+ <RegenerateButtonShell+ onRegenerate={() => setConfirmOpen(true)}+ isLoading={loading}+ isInProgress={!!jobId}+ onDialogClose={() => setJobId(null)}+ jobSlot={jobId ? <GenerationProgress jobId={jobId} onDone={handleDone} /> : null}+ />+ </div><ConfirmDialogopen={confirmOpen}onOpenChange={setConfirmOpen}title="Regenerate this page?"- description={`The current content is archived as a version and replaced. ${estimate}`}+ description={`The current content is archived as a version and replaced.${styleNote} ${estimate}`}confirmLabel="Regenerate"destructive={false}loading={loading}diff --git a/packages/web/src/lib/api/pages.test.ts b/packages/web/src/lib/api/pages.test.tsnew file mode 100644index 000000000..084d3fcc6--- /dev/null+++ b/packages/web/src/lib/api/pages.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it, vi, beforeEach } from "vitest";++const apiPost = vi.fn();+vi.mock("./client", () => ({+ apiGet: vi.fn(),+ apiPatch: vi.fn(),+ apiPost: (...args: unknown[]) => apiPost(...args),+}));++import { regeneratePage } from "./pages";++describe("regeneratePage", () => {+ beforeEach(() => {+ apiPost.mockReset();+ apiPost.mockResolvedValue({ job_id: "j1" });+ });++ it("sends only page_id when no style override is given", async () => {+ await regeneratePage("file_page:src/main.py");+ const params = apiPost.mock.calls[0]![3];+ expect(params).toEqual({ page_id: "file_page:src/main.py" });+ expect(params).not.toHaveProperty("style");+ });++ it("includes the style param for a per-page override", async () => {+ await regeneratePage("file_page:src/main.py", "caveman");+ expect(apiPost.mock.calls[0]![3]).toEqual({+ page_id: "file_page:src/main.py",+ style: "caveman",+ });+ });++ it("omits the style param for an empty override", async () => {+ await regeneratePage("file_page:src/main.py", "");+ expect(apiPost.mock.calls[0]![3]).toEqual({ page_id: "file_page:src/main.py" });+ });+});diff --git a/packages/web/src/lib/api/pages.ts b/packages/web/src/lib/api/pages.tsindex 229a61e4a..b9094fb3b 100644--- a/packages/web/src/lib/api/pages.ts+++ b/packages/web/src/lib/api/pages.ts@@ -54,7 +54,16 @@ export async function updatePageNotes();}-/** Force-regenerate a page by ID */-export async function regeneratePage(pageId: string): Promise<{ job_id: string }> {- return apiPost<{ job_id: string }>("/api/pages/lookup/regenerate", undefined, undefined, { page_id: pageId });+/**+ * Force-regenerate a page by ID. Pass `style` to regenerate this page in a+ * specific wiki style (per-page override); omit it to use the repo's style.+ */+export async function regeneratePage(+ pageId: string,+ style?: string,+): Promise<{ job_id: string }> {+ return apiPost<{ job_id: string }>("/api/pages/lookup/regenerate", undefined, undefined, {+ page_id: pageId,+ ...(style ? { style } : {}),+ });}diff --git a/tests/unit/cli/test_restyle_cmd.py b/tests/unit/cli/test_restyle_cmd.pynew file mode 100644index 000000000..c77f5e526--- /dev/null+++ b/tests/unit/cli/test_restyle_cmd.py@@ -0,0 +1,87 @@+"""Tests for `repowise restyle` and `repowise wiki-styles` (CLI surface).++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+the listing surfaces the built-in catalogue + current style.+"""++from __future__ import annotations++import json+from pathlib import Path++from click.testing import CliRunner++from repowise.cli.main import cli+++def _write_state(repo: Path, state: dict) -> None:+ d = repo / ".repowise"+ d.mkdir(parents=True, exist_ok=True)+ (d / "state.json").write_text(json.dumps(state), encoding="utf-8")+++def _write_config(repo: Path, cfg: dict) -> None:+ import yaml++ d = repo / ".repowise"+ d.mkdir(parents=True, exist_ok=True)+ (d / "config.yaml").write_text(yaml.dump(cfg), encoding="utf-8")+++def test_wiki_styles_lists_builtins(tmp_path):+ result = CliRunner().invoke(cli, ["wiki-styles", str(tmp_path)])+ assert result.exit_code == 0+ for name in ("comprehensive", "caveman", "reference", "tutorial"):+ assert name in result.output+++def test_wiki_styles_marks_current(tmp_path):+ _write_config(tmp_path, {"wiki_style": "caveman"})+ result = CliRunner().invoke(cli, ["wiki-styles", str(tmp_path)])+ assert result.exit_code == 0+ # caveman line should be flagged current+ caveman_line = next(line for line in result.output.splitlines() if "caveman" in line)+ assert "current" in caveman_line+++def test_restyle_no_style_shows_current_and_options():+ """With no STYLE arg, restyle prints the current style + catalogue (no regen)."""+ runner = CliRunner()+ with runner.isolated_filesystem() as fs:+ _write_config(Path(fs), {"wiki_style": "reference"})+ result = runner.invoke(cli, ["restyle"])+ assert result.exit_code == 0+ assert "Current wiki style" in result.output+ assert "reference" in result.output+ assert "caveman" in result.output # catalogue shown+++def test_restyle_unknown_style_errors(tmp_path):+ result = CliRunner().invoke(cli, ["restyle", "bogus", str(tmp_path)])+ assert result.exit_code == 1+ assert "Unknown style" in result.output+ assert "comprehensive" in result.output # lists valid choices+++def test_restyle_requires_index(tmp_path):+ result = CliRunner().invoke(cli, ["restyle", "caveman", str(tmp_path), "--yes"])+ assert result.exit_code == 1+ assert "No index found" in result.output+++def test_restyle_refuses_index_only_repo(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+++def test_restyle_known_styles_accepted_past_validation(tmp_path):+ """All four built-ins clear name validation (they fail later on no-index)."""+ for style in ("comprehensive", "caveman", "reference", "tutorial"):+ result = CliRunner().invoke(cli, ["restyle", style, str(tmp_path), "--yes"])+ # Past the unknown-style guard → fails on the missing index instead.+ assert "Unknown style" not in result.output+ assert "No index found" in result.outputdiff --git a/tests/unit/generation/test_styles.py b/tests/unit/generation/test_styles.pynew file mode 100644index 000000000..af234ac77--- /dev/null+++ b/tests/unit/generation/test_styles.py@@ -0,0 +1,379 @@+"""Tests for the wiki-style system (generation/styles + page_generator wiring).++The headline test is ``test_style_change_invalidates_cross_run_cache`` — it pins the+feature's load-bearing contract: switching styles must invalidate the persistent+cross-run cache so ``repowise update`` regenerates pages in the new style. If that+test ever goes green while a style change is silently reused, the feature is broken+no matter what else passes (see WIKI_STYLES_PLAN.md §2).+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.generation.context_assembler import ContextAssembler+from repowise.core.generation.models import GenerationConfig+from repowise.core.generation.page_generator import PageGenerator, PriorPage+from repowise.core.generation.styles import (+ DEFAULT_STYLE,+ ONBOARDING_PAGE_TYPE,+ is_known_style,+ list_styles,+ resolve_style,+)++# ---------------------------------------------------------------------------+# Registry+# ---------------------------------------------------------------------------++BUILTIN_NAMES = ["comprehensive", "caveman", "reference", "tutorial"]++[email protected]("name", BUILTIN_NAMES)+def test_builtin_styles_resolve(name):+ spec = resolve_style(name)+ assert spec.name == name+ assert spec.description+++def test_default_style_is_comprehensive():+ assert DEFAULT_STYLE == "comprehensive"+ assert resolve_style(None).name == "comprehensive"+++def test_unknown_style_falls_back_to_default():+ assert resolve_style("does-not-exist").name == DEFAULT_STYLE+ assert resolve_style("").name == DEFAULT_STYLE+++def test_resolve_is_case_insensitive():+ assert resolve_style("CAVEMAN").name == "caveman"+ assert resolve_style(" Reference ").name == "reference"+++def test_is_known_style():+ assert is_known_style("caveman")+ assert not is_known_style("nope")+ assert not is_known_style(None)+++def test_list_styles_covers_builtins():+ names = {s.name for s in list_styles()}+ assert names == set(BUILTIN_NAMES)+++# ---------------------------------------------------------------------------+# StyleSpec semantics+# ---------------------------------------------------------------------------+++def test_comprehensive_is_inert():+ """The default style must contribute nothing — byte-identical to pre-feature."""+ spec = resolve_style("comprehensive")+ assert spec.is_active is False+ assert spec.fingerprint == ""+ assert spec.user_prompt_prefix(is_onboarding=False) == ""+ assert spec.user_prompt_prefix(is_onboarding=True) == ""+ assert spec.system_prompt_suffix(is_onboarding=False) == ""+++def test_active_style_has_prefix_and_suffix():+ spec = resolve_style("caveman")+ assert spec.is_active is True+ assert spec.fingerprint+ prefix = spec.user_prompt_prefix(is_onboarding=False)+ assert prefix.startswith("<!-- repowise-style:caveman")+ assert spec.fingerprint in prefix+ assert spec.system_prompt_suffix(is_onboarding=False)+++def test_prefix_carries_fingerprint_marker():+ """The marker must embed the fingerprint so any style edit busts the hash."""+ spec = resolve_style("reference")+ assert f"fp:{spec.fingerprint}" in spec.user_prompt_prefix(is_onboarding=False)+++def test_onboarding_condense_policy():+ """Per-style D9 policy: caveman condenses onboarding, reference does not."""+ caveman = resolve_style("caveman")+ reference = resolve_style("reference")++ # caveman condenses onboarding → prefix + suffix apply+ assert caveman.user_prompt_prefix(is_onboarding=True) != ""+ assert caveman.system_prompt_suffix(is_onboarding=True) != ""++ # reference keeps onboarding narrative → no prefix/suffix on onboarding pages+ assert reference.user_prompt_prefix(is_onboarding=True) == ""+ assert reference.system_prompt_suffix(is_onboarding=True) == ""+ # ...but reference still applies to ordinary pages+ assert reference.user_prompt_prefix(is_onboarding=False) != ""+++def test_distinct_styles_have_distinct_fingerprints():+ fps = {resolve_style(n).fingerprint for n in ("caveman", "reference", "tutorial")}+ assert len(fps) == 3+++def test_fingerprint_changes_when_directive_changes():+ from repowise.core.generation.styles.spec import StyleSpec++ a = StyleSpec(name="x", description="d", user_directive="alpha")+ b = StyleSpec(name="x", description="d", user_directive="beta")+ assert a.fingerprint != b.fingerprint+++def test_fingerprint_changes_when_system_note_changes():+ """A note-only change must still bust the hash (it rides in the user marker)."""+ from repowise.core.generation.styles.spec import StyleSpec++ a = StyleSpec(name="x", description="d", system_note="note-a")+ b = StyleSpec(name="x", description="d", system_note="note-b")+ assert a.fingerprint != b.fingerprint+ # The note change is observable in the user-prompt marker too.+ assert a.user_prompt_prefix(is_onboarding=False) != b.user_prompt_prefix(is_onboarding=False)+++# ---------------------------------------------------------------------------+# PageGenerator wiring+# ---------------------------------------------------------------------------+++async def test_config_threads_style_into_generator(+ sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ from repowise.core.providers.llm.mock import MockProvider++ config = GenerationConfig(wiki_style="caveman")+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)+ assert gen._style.name == "caveman"+++async def test_comprehensive_prompt_is_unchanged_vs_no_style(+ sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ """Default-style rendering must not alter the prompt the model sees."""+ from repowise.core.providers.llm.mock import MockProvider++ config = GenerationConfig(wiki_style="comprehensive")+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)+ ctx = gen._assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ rendered = gen._render("file_page.j2", ctx=ctx)+ assert not rendered.startswith("<!-- repowise-style")+++async def test_active_style_prepends_directive_to_prompt(+ sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ from repowise.core.providers.llm.mock import MockProvider++ config = GenerationConfig(wiki_style="caveman")+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)+ ctx = gen._assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ rendered = gen._render("file_page.j2", ctx=ctx)+ assert rendered.startswith("<!-- repowise-style:caveman")+ assert "CAVEMAN" in rendered+++def _make_gen(config, source_bytes, prior=None):+ from repowise.core.providers.llm.mock import MockProvider++ provider = MockProvider()+ gen = PageGenerator(provider, ContextAssembler(config), config, prior_pages=prior)+ return provider, gen+++async def _generate(gen, parsed, graph, metrics, source_bytes):+ return await gen.generate_file_page(+ parsed,+ graph,+ metrics["pagerank"],+ metrics["betweenness"],+ metrics["community"],+ source_bytes,+ )+++async def test_same_style_reuses_cross_run_cache(+ sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ """Baseline: identical inputs + same style → cross-run cache hit (no LLM call)."""+ config = GenerationConfig(wiki_style="caveman")+ _, gen1 = _make_gen(config, sample_source_bytes)+ page = await _generate(+ gen1, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+ )++ prior = {+ page.page_id: PriorPage(+ source_hash=page.source_hash,+ model_name=page.model_name,+ content=page.content,+ )+ }+ provider2, gen2 = _make_gen(config, sample_source_bytes, prior=prior)+ await _generate(gen2, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes)+ assert provider2.call_count == 0 # reused, no provider call+ assert gen2._reuse_count == 1+++async def test_style_change_invalidates_cross_run_cache(+ sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ """THE CONTRACT: a style change must miss the cache and regenerate the page.++ Generate under ``comprehensive``, hand the result to a generator running+ ``caveman`` as a prior page, and assert the page is regenerated (provider+ called, nothing reused). This is exactly what `repowise update` does after a+ style switch.+ """+ base_cfg = GenerationConfig(wiki_style="comprehensive")+ _, gen_base = _make_gen(base_cfg, sample_source_bytes)+ page = await _generate(+ gen_base, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+ )++ prior = {+ page.page_id: PriorPage(+ source_hash=page.source_hash,+ model_name=page.model_name,+ content=page.content,+ )+ }+ new_cfg = GenerationConfig(wiki_style="caveman")+ provider2, gen2 = _make_gen(new_cfg, sample_source_bytes, prior=prior)+ page2 = await _generate(+ gen2, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+ )++ assert provider2.call_count == 1 # regenerated, not reused+ assert gen2._reuse_count == 0+ assert page2.source_hash != page.source_hash # style folded into the hash+++async def test_onboarding_page_type_constant_matches_system_prompts():+ """ONBOARDING_PAGE_TYPE must match the key used by the onboarding generators."""+ from repowise.core.generation.page_generator import SYSTEM_PROMPTS++ assert ONBOARDING_PAGE_TYPE in SYSTEM_PROMPTS+++# ---------------------------------------------------------------------------+# Custom styles (Phase 5)+# ---------------------------------------------------------------------------+++def _write_custom_style(repo: Path, name: str, body: str) -> None:+ d = repo / ".repowise" / "styles" / name+ d.mkdir(parents=True, exist_ok=True)+ (d / "style.yaml").write_text(body, encoding="utf-8")+++def test_custom_style_resolves(tmp_path):+ _write_custom_style(+ tmp_path,+ "terse",+ "description: My terse style\nuser_directive: Be very terse.\n"+ "onboarding_condenses: true\n",+ )+ spec = resolve_style("terse", repo_path=tmp_path)+ assert spec.name == "terse"+ assert spec.is_builtin is False+ assert spec.is_active is True+ assert spec.onboarding_condenses is True+ assert "Be very terse." in spec.user_prompt_prefix(is_onboarding=False)+++def test_custom_style_listed_and_known(tmp_path):+ _write_custom_style(tmp_path, "terse", "system_note: Be terse.\n")+ assert is_known_style("terse", tmp_path)+ names = {s.name for s in list_styles(tmp_path)}+ assert "terse" in names+ assert {"comprehensive", "caveman", "reference", "tutorial"} <= names+++def test_custom_style_unknown_without_repo_path(tmp_path):+ """Custom styles require repo_path; without it they don't resolve."""+ _write_custom_style(tmp_path, "terse", "user_directive: Terse.\n")+ assert resolve_style("terse").name == DEFAULT_STYLE+ assert not is_known_style("terse")+++def test_custom_style_empty_is_rejected(tmp_path):+ """A style with neither directive nor note is inert → not a usable style."""+ _write_custom_style(tmp_path, "empty", "description: nothing here\n")+ assert not is_known_style("empty", tmp_path)+ assert resolve_style("empty", repo_path=tmp_path).name == DEFAULT_STYLE+++def test_custom_style_name_traversal_rejected(tmp_path):+ """Unsafe names never touch the filesystem."""+ assert resolve_style("../evil", repo_path=tmp_path).name == DEFAULT_STYLE+ assert not is_known_style("../evil", tmp_path)+ assert not is_known_style("a/b", tmp_path)+++def test_custom_style_directive_is_length_bounded(tmp_path):+ from repowise.core.generation.styles.registry import _MAX_DIRECTIVE_CHARS++ huge = "x" * (_MAX_DIRECTIVE_CHARS + 5000)+ _write_custom_style(tmp_path, "big", f"user_directive: {huge}\n")+ spec = resolve_style("big", repo_path=tmp_path)+ assert len(spec.user_directive) == _MAX_DIRECTIVE_CHARS+++def test_custom_style_template_dir_detected(tmp_path):+ _write_custom_style(tmp_path, "tpl", "user_directive: Terse.\n")+ (tmp_path / ".repowise" / "styles" / "tpl" / "templates").mkdir()+ spec = resolve_style("tpl", repo_path=tmp_path)+ assert spec.template_dir is not None+ assert spec.template_dir.name == "templates"+++def test_builtin_takes_precedence_over_custom(tmp_path):+ """A custom dir named like a built-in must not shadow the built-in."""+ _write_custom_style(tmp_path, "caveman", "user_directive: hijack\n")+ spec = resolve_style("caveman", repo_path=tmp_path)+ assert spec.is_builtin is True+ assert "hijack" not in spec.user_directive+++async def test_custom_style_reaches_rendered_prompt(+ tmp_path, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ """PageGenerator(repo_path=...) resolves a custom style and injects its voice."""+ from repowise.core.providers.llm.mock import MockProvider++ _write_custom_style(+ tmp_path, "terse", "user_directive: TERSE_MARKER be brief.\n"+ )+ config = GenerationConfig(wiki_style="terse")+ gen = PageGenerator(+ MockProvider(), ContextAssembler(config), config, repo_path=tmp_path+ )+ assert gen._style.name == "terse"+ ctx = gen._assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ rendered = gen._render("file_page.j2", ctx=ctx)+ assert "TERSE_MARKER" in rendereddiff --git a/tests/unit/server/test_job_executor.py b/tests/unit/server/test_job_executor.pyindex f966db62f..5f422bf2d 100644--- a/tests/unit/server/test_job_executor.py+++ b/tests/unit/server/test_job_executor.py@@ -131,6 +131,73 @@ def test_repo_exclude_patterns_ignores_malformed_sources(tmp_path):assert _repo_exclude_patterns(repo, str(tmp_path)) == []+async def test_execute_job_passes_wiki_style_from_settings(session_factory, tmp_path):+ """The repo's settings wiki_style must reach run_pipeline."""+ job_id = await _seed_repo_and_job(+ session_factory,+ tmp_path,+ settings={"wiki_style": "caveman"},+ )++ app_state = SimpleNamespace(session_factory=session_factory, fts=None, vector_store=None)++ run_pipeline_mock = AsyncMock(return_value=_fake_result())+ with (+ patch("repowise.server.job_executor.run_pipeline", run_pipeline_mock),+ patch("repowise.server.job_executor.persist_pipeline_result", AsyncMock()),+ patch(+ "repowise.server.provider_config.get_chat_provider_instance",+ side_effect=RuntimeError("no provider"),+ ),+ ):+ await execute_job(job_id, app_state)++ run_pipeline_mock.assert_awaited_once()+ assert run_pipeline_mock.await_args.kwargs["wiki_style"] == "caveman"+++def test_repo_wiki_style_settings_precedence(tmp_path):+ """DB settings (web) win over .repowise/config.yaml (CLI) for wiki_style."""+ import json++ from repowise.server.job_executor import _repo_wiki_style++ config_dir = tmp_path / ".repowise"+ config_dir.mkdir()+ (config_dir / "config.yaml").write_text("wiki_style: reference\n", encoding="utf-8")++ repo = SimpleNamespace(settings_json=json.dumps({"wiki_style": "caveman"}))+ assert _repo_wiki_style(repo, str(tmp_path)) == "caveman"+++def test_repo_wiki_style_falls_back_to_config(tmp_path):+ """With no DB setting, the config.yaml style is used."""+ from repowise.server.job_executor import _repo_wiki_style++ config_dir = tmp_path / ".repowise"+ config_dir.mkdir()+ (config_dir / "config.yaml").write_text("wiki_style: tutorial\n", encoding="utf-8")++ repo = SimpleNamespace(settings_json="{}")+ assert _repo_wiki_style(repo, str(tmp_path)) == "tutorial"+++def test_repo_wiki_style_defaults_and_tolerates_bad_input(tmp_path):+ """Unknown / missing / malformed style resolves to the comprehensive default."""+ from repowise.server.job_executor import _repo_wiki_style++ assert _repo_wiki_style(SimpleNamespace(settings_json="{}"), str(tmp_path)) == "comprehensive"+ assert (+ _repo_wiki_style(SimpleNamespace(settings_json='{"wiki_style": "nope"}'), str(tmp_path))+ == "comprehensive"+ )+ assert (+ _repo_wiki_style(SimpleNamespace(settings_json="{bad json"), str(tmp_path))+ == "comprehensive"+ )++@pytest.mark.asyncioasync def test_execute_job_merges_config_yaml_excludes(session_factory, tmp_path):"""End-to-end regression: the real user case (tools/ excluded).@@ -172,9 +239,7 @@ async def test_incremental_page_regen_passes_repo_path(tmp_path):repo_path = tmp_pathrepowise_dir = repo_path / ".repowise"repowise_dir.mkdir()- (repowise_dir / "state.json").write_text(- '{"last_sync_commit": "base-sha"}', encoding="utf-8"- )+ (repowise_dir / "state.json").write_text('{"last_sync_commit": "base-sha"}', encoding="utf-8")result = SimpleNamespace(file_count=10,diff --git a/tests/unit/server/test_pages.py b/tests/unit/server/test_pages.pyindex 4c2be9534..cf3ec27ba 100644--- a/tests/unit/server/test_pages.py+++ b/tests/unit/server/test_pages.py@@ -131,3 +131,25 @@ async def test_regenerate_page_not_found(client: AsyncClient) -> None:params={"page_id": "file_page:nonexistent.py"},)assert resp.status_code == 404+++async def test_regenerate_page_with_known_style_accepted(client: AsyncClient, app) -> None:+ _, page_id = await _create_page(client, app.state.session_factory)+ resp = await client.post(+ "/api/pages/lookup/regenerate",+ params={"page_id": page_id, "style": "caveman"},+ )+ assert resp.status_code == 202+ assert "job_id" in resp.json()+++async def test_regenerate_page_rejects_unknown_style(client: AsyncClient, app) -> None:+ _, page_id = await _create_page(client, app.state.session_factory)+ resp = await client.post(+ "/api/pages/lookup/regenerate",+ params={"page_id": page_id, "style": "bogus"},+ )+ assert resp.status_code == 400+ assert "style" in resp.json()["detail"].lower()diff --git a/tests/unit/server/test_repos.py b/tests/unit/server/test_repos.pyindex 02867e7ba..ea02844bd 100644--- a/tests/unit/server/test_repos.py+++ b/tests/unit/server/test_repos.py@@ -76,6 +76,28 @@ async def test_update_repo(client: AsyncClient) -> None:assert resp.json()["name"] == "updated-name"+async def test_update_repo_accepts_known_wiki_style(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.patch(+ f"/api/repos/{repo['id']}",+ json={"settings": {"wiki_style": "caveman"}},+ )+ assert resp.status_code == 200+ assert resp.json()["settings"]["wiki_style"] == "caveman"+++async def test_update_repo_rejects_unknown_wiki_style(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.patch(+ f"/api/repos/{repo['id']}",+ json={"settings": {"wiki_style": "bogus"}},+ )+ assert resp.status_code == 400+ assert "wiki_style" in resp.json()["detail"]++@pytest.mark.asyncioasync def test_sync_repo_returns_202(client: AsyncClient) -> None:repo = await create_test_repo(client)