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
feat: deterministic template wiki for workspace and keyless server indexing (#999)
Raghav Chamadiyac47b8d497a3d
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex 3492f5b87..97ebfcc53 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -9,6 +9,7 @@ same helpers as the single-repo flow.from __future__ import annotations+import osimport sysimport timefrom dataclasses import dataclass@@ -151,6 +152,64 @@ def _run_workspace_generation()+def _run_workspace_deterministic_generation(+ *,+ repo_path: Path,+ result: Any,+ embedder_name_resolved: str,+ embedder_was_requested: bool,+ concurrency: int,+ resume: bool,+ onboarding: bool,+ wiki_style: str,+ language: str,+) -> tuple[list[Any], str]:+ """Render one workspace repo's wiki from templates (no model, no cost).++ The multi-repo mirror of init's single-repo+ ``_run_deterministic_generation_phase``: an index-only (or provider-less /+ cost-declined) workspace repo gets a complete, upgradable template wiki+ rather than no pages at all, so it reads as a real wiki in the UI. Returns+ the generated pages plus the embedder actually used (persisted by the caller+ so a later workspace update embeds the same way rather than re-deciding).+ """+ from repowise.core.generation import GenerationConfig+ from repowise.core.providers.llm.template import TemplateProvider++ # "No key, no spend": a template run must not put a hosted embedder on the+ # bill unless the user named it. ``resolve_embedder`` infers one from any LLM+ # key in the environment, which is the wrong default here. Mirror the+ # single-repo phase — mock unless requested — so full-text search still works+ # and semantic search can be built later with ``repowise reindex``.+ # A previously-persisted embedder on THIS repo counts as requested (re-init+ # case): silently dropping it to the mock would re-embed the store at a+ # different vector width, which the LanceDB writer resolves by dropping the+ # table (the single-repo phase reads config.get("embedder") for the same+ # reason; the workspace flag is computed once, before any repo config loads).+ requested = embedder_was_requested or bool(load_config(repo_path).get("embedder"))+ hosted = embedder_name_resolved not in ("mock", "ollama")+ embedder = "mock" if hosted and not requested else embedder_name_resolved++ gen_config = GenerationConfig(+ deterministic=True,+ max_concurrency=concurrency,+ language=language,+ enable_onboarding=onboarding,+ wiki_style=wiki_style,+ )+ generated_pages = run_repo_generation(+ repo_path=repo_path,+ result=result,+ provider=TemplateProvider(),+ gen_config=gen_config,+ concurrency=concurrency,+ embedder_name_resolved=embedder,+ resume=resume,+ verbose=False,+ )+ return generated_pages, embedder++def _workspace_generation_provider_for_repo(provider: Any, repo_path: Path) -> Any:"""Return a generation provider bound to the current workspace repo.@@ -190,6 +249,7 @@ class _WorkspaceCtx:language: strresolved_reasoning: strembedder_name_resolved: str+ embedder_was_requested: boolresolved_commit_limit: intrun_mode: str = "standard"@@ -264,62 +324,94 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtprovider = ctx.providerindex_only = ctx.index_only- # Generation phase (per-repo, only when not index-only).- # Track per-repo whether the user declined cost so the persisted docs mode- # reflects the actual choice instead of the original init mode.- repo_docs_enabled = not index_only and provider is not None+ # Generation phase (per-repo). ``docs_mode`` records what actually happened:+ # "llm" when a model wrote the pages, "deterministic" when they were rendered+ # from templates (index-only, no provider, or a declined cost gate), "none"+ # when nothing was generated (dry run, fast mode, or a generation error).+ # It drives the persisted state so `update` and the web UI see the truth.+ docs_mode = "none"skip_reason: str | None = None- if index_only:- skip_reason = "index-only mode"- elif provider is None:- skip_reason = "no provider configured"pages_generated = 0- if not index_only and provider is not None:- if ctx.dry_run:- console.print(" [yellow]Dry run — skipping generation for this repo.[/yellow]\n")- skip_reason = "dry run"- repo_docs_enabled = False- else:- try:- repo_provider = _workspace_generation_provider_for_repo(provider, repo.path)- generated_pages = _run_workspace_generation(- repo_path=repo.path,- result=result,- provider=repo_provider,- embedder_name_resolved=ctx.embedder_name_resolved,- concurrency=ctx.concurrency,- yes=ctx.yes,- resume=ctx.resume,- skip_tests=ctx.skip_tests,- skip_infra=ctx.skip_infra,- test_run=ctx.test_run,- reasoning=ctx.resolved_reasoning,- onboarding=ctx.onboarding,- coverage_pct=ctx.coverage_pct,- harvest_decisions=ctx.harvest_decisions,- wiki_style=ctx.wiki_style,- language=ctx.language,- )- result.generated_pages = generated_pages- # (result.vector_store is set inside _run_workspace_generation- # so the Phase-2C decision dedup can reuse the same store.)- pages_generated = len(generated_pages)- console.print(f" [green]✓[/green] Generated {len(generated_pages)} pages\n")- except CostGateDeclined:- repo_docs_enabled = False- result.generated_pages = []- skip_reason = "cost gate declined"- except Exception as gen_exc:- console.print(f" [yellow]Generation failed: {gen_exc}[/yellow]\n")- skip_reason = f"generation error: {gen_exc}"- repo_docs_enabled = False- else:+ det_embedder: str | None = None++ def _render_from_templates() -> None:+ """Render the whole wiki from templates and mark this repo deterministic."""+ nonlocal pages_generated, docs_mode, det_embedder+ generated_pages, det_embedder = _run_workspace_deterministic_generation(+ repo_path=repo.path,+ result=result,+ embedder_name_resolved=ctx.embedder_name_resolved,+ embedder_was_requested=ctx.embedder_was_requested,+ concurrency=ctx.concurrency,+ resume=ctx.resume,+ onboarding=ctx.onboarding,+ wiki_style=ctx.wiki_style,+ language=ctx.language,+ )+ result.generated_pages = generated_pages+ pages_generated = len(generated_pages)+ docs_mode = "deterministic"+ console.print(+ f" [green]✓[/green] Rendered {len(generated_pages)} pages from structure "+ "(no model)\n"+ )++ if ctx.dry_run:+ console.print(" [yellow]Dry run — skipping generation for this repo.[/yellow]\n")+ skip_reason = "dry run"+ elif ctx.run_mode == "fast":+ # Fast mode is a graph-and-git index by design; it skips the wiki so a+ # very large repo indexes quickly. Mirror single-repo init.console.print()+ skip_reason = "fast mode"+ elif not index_only and provider is not None:+ try:+ repo_provider = _workspace_generation_provider_for_repo(provider, repo.path)+ generated_pages = _run_workspace_generation(+ repo_path=repo.path,+ result=result,+ provider=repo_provider,+ embedder_name_resolved=ctx.embedder_name_resolved,+ concurrency=ctx.concurrency,+ yes=ctx.yes,+ resume=ctx.resume,+ skip_tests=ctx.skip_tests,+ skip_infra=ctx.skip_infra,+ test_run=ctx.test_run,+ reasoning=ctx.resolved_reasoning,+ onboarding=ctx.onboarding,+ coverage_pct=ctx.coverage_pct,+ harvest_decisions=ctx.harvest_decisions,+ wiki_style=ctx.wiki_style,+ language=ctx.language,+ )+ result.generated_pages = generated_pages+ # (result.vector_store is set inside _run_workspace_generation+ # so the Phase-2C decision dedup can reuse the same store.)+ pages_generated = len(generated_pages)+ docs_mode = "llm"+ console.print(f" [green]✓[/green] Generated {len(generated_pages)} pages\n")+ except CostGateDeclined:+ # Declining only ever meant "not at that price". Fall back to the+ # free template renderer rather than leaving the repo with no wiki+ # at all (parity with single-repo init).+ console.print(+ " [dim]Building this repo's wiki from structure instead. Run "+ "[bold]repowise update --repo "+ f"{repo.alias} --full[/bold] to write it with a model later.[/dim]"+ )+ _render_from_templates()+ except Exception as gen_exc:+ console.print(f" [yellow]Generation failed: {gen_exc}[/yellow]\n")+ skip_reason = f"generation error: {gen_exc}"+ result.generated_pages = []+ else:+ # Index-only, or provider setup failed and fell back to index-only: give+ # the repo a complete template wiki so it is a real, upgradable wiki in+ # the UI rather than an empty index with no upgrade target.+ _render_from_templates()- docs_outcome = (- len(result.generated_pages or []),- None if repo_docs_enabled else skip_reason,- )+ docs_outcome = (len(result.generated_pages or []), skip_reason)# Persist to repo-local DBrun_async(persist_result(result, repo.path))@@ -330,11 +422,12 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtstate: dict[str, Any] = {"last_sync_commit": head,"total_pages": pages_count,- # Workspace init has no template fallback yet, so a repo that skipped- # generation really does end up with no pages at all.- **docs_mode_state_fields("llm" if repo_docs_enabled else "none"),+ # "llm", "deterministic" (template wiki), or "none" — see the generation+ # phase above. An index-only workspace repo now renders a template wiki+ # like single-repo init, so it reads as "deterministic", not "none".+ **docs_mode_state_fields(docs_mode),}- if repo_docs_enabled and provider is not None:+ if docs_mode == "llm" and provider is not None:state["provider"] = provider.provider_namestate["model"] = provider.model_nameif repo_phase_timings:@@ -361,7 +454,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt)# Persist provider/model config per-repo when doing full generation- if not index_only and provider is not None:+ if docs_mode == "llm" and provider is not None:from repowise.cli.providers.embedders import resolve_embedding_modelsave_config(@@ -381,6 +474,24 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt# Same for the output language, so update regenerates in it.if ctx.language != "en":save_config_partial(repo.path, language=ctx.language)+ elif docs_mode == "deterministic":+ # A template wiki still produces (and embeds) pages, so persist the+ # embedder actually used and the index knobs. Without the embedder,+ # a later `repowise update` would re-resolve from the environment and+ # could re-embed the store at a different width, which the LanceDB+ # writer resolves by dropping the table. Provider/model/style/language+ # only reach a model, so they are intentionally not written here.+ from repowise.cli.providers.embedders import resolve_embedding_model++ save_config_partial(+ repo.path,+ exclude_patterns=ctx.exclude_patterns if ctx.exclude_patterns else None,+ commit_limit=ctx.resolved_commit_limit if ctx.resolved_commit_limit else None,+ embedder=det_embedder,+ embedding_model=(+ resolve_embedding_model(det_embedder) if det_embedder else None+ ),+ )return _RepoOutcome(file_count=result.file_count,@@ -479,6 +590,14 @@ def _workspace_init(is_interactive = sys.stdin.isatty() and provider_name is None and not index_only and not yesembedder_name_resolved = resolve_embedder(embedder_name)+ # Whether the user actually asked for this embedder, as opposed to+ # resolve_embedder inferring one from an LLM key in the environment. The+ # deterministic (index-only) path needs the distinction: it advertises+ # itself as costing nothing, so it will not put a hosted embedder on the+ # user's bill unless they named it.+ embedder_was_requested = bool(embedder_name) or bool(+ os.environ.get("REPOWISE_EMBEDDER", "").strip()+ )if is_interactive:mode = interactive_mode_select(console)@@ -612,6 +731,7 @@ def _workspace_init(language=language or "en",resolved_reasoning=resolved_reasoning,embedder_name_resolved=embedder_name_resolved,+ embedder_was_requested=embedder_was_requested,resolved_commit_limit=resolved_commit_limit,run_mode=run_mode,)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.pyindex 78cfa2d83..c29d31d65 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py@@ -42,6 +42,7 @@ def _workspace_update(parallel index-only path. See :func:`_workspace_docs_update`."""from repowise.cli.helpers import load_state+ from repowise.core.docs_mode import resolve_docs_modefrom repowise.core.workspace import (check_repo_staleness,reconcile_repo_head_commit,@@ -88,10 +89,20 @@ def _workspace_update(# collapse into a single count line unless -v lists everything.if is_stale:stale_count += 1- if indexed and not _resolve_index_only_mode(- index_only=index_only, docs_flag=docs_flag, state=load_state(abs_path)- ):- docs_aliases.add(entry.alias)+ if indexed:+ repo_state = load_state(abs_path)+ if not _resolve_index_only_mode(+ index_only=index_only, docs_flag=docs_flag, state=repo_state+ ):+ # LLM docs wanted: full single-repo docs regen.+ docs_aliases.add(entry.alias)+ elif resolve_docs_mode(repo_state) == "deterministic":+ # A template wiki has pages too. The single-repo update path+ # re-renders the changed files' template pages for free+ # (file_pages_only), so route it there rather than the core+ # index-only path, which would freeze the wiki. Model-written+ # pages a user upgraded stay put; only the templates refresh.+ docs_aliases.add(entry.alias)if indexed and not is_stale:up_to_date_count += 1if head:diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex 14b27f661..34a5f2f31 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -30,6 +30,7 @@ from repowise.core.persistence.crud import ()from repowise.core.persistence.database import get_sessionfrom repowise.core.pipeline import persist_pipeline_result, run_pipeline+from repowise.core.pipeline.modes import OrchestratorModefrom repowise.server.job_events import JobEventBuffer, create_event_bufferlogger = structlog.get_logger(__name__)@@ -411,21 +412,34 @@ async def execute_job()return- generate_docs = (- (is_full_resync or is_initial_index)- and llm_client is not None- and bool(config.get("generate_docs", True))+ want_docs = bool(config.get("generate_docs", True))+ # LLM docs: an initial index or full resync with a provider configured.+ generate_docs_llm = (+ (is_full_resync or is_initial_index) and llm_client is not None and want_docs)+ # Keyless deterministic fallback: a first index of a repo with NO+ # provider still renders a complete template wiki (no model, no key, no+ # cost), exactly like `repowise init --index-only`, so the repo reads as+ # a real, upgradable wiki in the web UI rather than an empty index.+ # Scoped to initial_index: a keyless full_resync of a model-written wiki+ # must not overwrite every page with a template (and full_resync writes+ # no docs_mode here anyway).+ deterministic_docs = is_initial_index and llm_client is None and want_docs+ generate_docs = generate_docs_llm or deterministic_docs+ pipeline_mode = (+ OrchestratorMode.DETERMINISTIC if deterministic_docs else OrchestratorMode.STANDARD+ )+if is_initial_index:# First index of an API-registered repo: make sure the repo-local# data directory exists before the pipeline writes artifacts.(Path(repo_path) / ".repowise").mkdir(parents=True, exist_ok=True)- if llm_client is None and config.get("generate_docs", True):+ if deterministic_docs:progress.on_message(- "warning",- "No LLM provider configured; indexing without documentation "- "generation. Configure a provider and run a full resync to "- "generate docs.",+ "info",+ "No LLM provider configured; rendering a template wiki from the "+ "code's structure (no model, no cost). Configure a provider and "+ "run a full resync to write the wiki with a model.",)result = await run_pipeline(@@ -436,6 +450,7 @@ async def execute_job(progress=progress,exclude_patterns=exclude_patterns or None,wiki_style=wiki_style,+ mode=pipeline_mode,)# ---- Incremental page regeneration for sync mode ------------------@@ -537,9 +552,16 @@ async def execute_job(_persist_initial_index_state(Path(repo_path),llm_client=llm_client,- # The API index path has no template fallback: without a- # provider it produces an index and no pages.- docs_mode="llm" if generate_docs else "none",+ # With a provider the pages are model-written ("llm"); with+ # none they are rendered from templates ("deterministic");+ # only a run that asked for no docs ends up with "none".+ docs_mode=(+ "llm"+ if generate_docs_llm+ else "deterministic"+ if deterministic_docs+ else "none"+ ),docs_skip_reason=docs_skip_reason,total_pages=len(all_pages),wiki_style=wiki_style,@@ -1145,6 +1167,13 @@ async def _incremental_page_regen(# Regenerate in the repo's configured output language, not default# English (PageGenerator picks the language up from the config).language=repo_cfg.get("language", "en"),+ # A sync feeds generate_all a parsed_files filtered to the changed+ # files. Levels 3 and up describe the whole repository from+ # parsed_files, so without this a one-commit sync would rewrite the+ # codebase map, module and overview pages from a truncated view (the+ # D4 shape the CLI update path already fixed). Stop the ladder after+ # level 2 and leave the repo-wide pages for a full run.+ file_pages_only=True,)assembler = ContextAssembler(generation_config)# D3: pass the vector store (re-embed re-rendered pages) and prior pagesdiff --git a/tests/unit/cli/test_workspace_deterministic.py b/tests/unit/cli/test_workspace_deterministic.pynew file mode 100644index 000000000..f70d5e2fe--- /dev/null+++ b/tests/unit/cli/test_workspace_deterministic.py@@ -0,0 +1,102 @@+"""Workspace init's deterministic (template) generation path.++An index-only (or provider-less / cost-declined) workspace repo now renders a+complete template wiki like single-repo init, instead of being left with no+pages and ``docs_mode: "none"``. These tests pin the two behaviours that make+that safe: the run uses the null ``TemplateProvider`` with a deterministic+config, and it never puts a hosted embedder on the bill unless the user asked.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from repowise.cli.commands.init_cmd import workspace as ws+++def _capture_run_repo_generation(monkeypatch: Any) -> dict[str, Any]:+ """Patch ``run_repo_generation`` and return a dict capturing its kwargs."""+ captured: dict[str, Any] = {}++ def fake_run_repo_generation(**kwargs: Any) -> list[Any]:+ captured.update(kwargs)+ return ["page1", "page2"]++ monkeypatch.setattr(ws, "run_repo_generation", fake_run_repo_generation)+ return captured+++def test_deterministic_generation_uses_template_provider_and_config(+ tmp_path: Any, monkeypatch: Any+) -> None:+ captured = _capture_run_repo_generation(monkeypatch)++ pages, embedder = ws._run_workspace_deterministic_generation(+ repo_path=tmp_path,+ result=SimpleNamespace(repo_name="demo"),+ embedder_name_resolved="mock",+ embedder_was_requested=False,+ concurrency=8,+ resume=False,+ onboarding=True,+ wiki_style="comprehensive",+ language="en",+ )++ assert pages == ["page1", "page2"]+ # Null provider (no model, no tokens, no key) + deterministic config.+ from repowise.core.providers.llm.template import TemplateProvider++ assert isinstance(captured["provider"], TemplateProvider)+ assert captured["gen_config"].deterministic is True+ assert captured["verbose"] is False+ assert embedder == "mock"+++def test_deterministic_generation_drops_inferred_hosted_embedder(+ tmp_path: Any, monkeypatch: Any+) -> None:+ """A hosted embedder inferred from the environment is dropped to the mock.++ The mode is sold as "no key, no spend"; embedding thousands of pages through+ a hosted embedder is a real bill nobody who ran index-only asked for.+ """+ captured = _capture_run_repo_generation(monkeypatch)++ _pages, embedder = ws._run_workspace_deterministic_generation(+ repo_path=tmp_path,+ result=SimpleNamespace(repo_name="demo"),+ embedder_name_resolved="openai", # hosted, inferred (not requested)+ embedder_was_requested=False,+ concurrency=8,+ resume=False,+ onboarding=True,+ wiki_style="comprehensive",+ language="en",+ )++ assert embedder == "mock"+ assert captured["embedder_name_resolved"] == "mock"+++def test_deterministic_generation_keeps_requested_hosted_embedder(+ tmp_path: Any, monkeypatch: Any+) -> None:+ """A hosted embedder the user explicitly named is honored."""+ captured = _capture_run_repo_generation(monkeypatch)++ _pages, embedder = ws._run_workspace_deterministic_generation(+ repo_path=tmp_path,+ result=SimpleNamespace(repo_name="demo"),+ embedder_name_resolved="openai",+ embedder_was_requested=True,+ concurrency=8,+ resume=False,+ onboarding=True,+ wiki_style="comprehensive",+ language="en",+ )++ assert embedder == "openai"+ assert captured["embedder_name_resolved"] == "openai"diff --git a/tests/unit/server/test_initial_index.py b/tests/unit/server/test_initial_index.pyindex c5ee1b5ae..877fc7413 100644--- a/tests/unit/server/test_initial_index.py+++ b/tests/unit/server/test_initial_index.py@@ -287,14 +287,19 @@ async def test_execute_job_initial_index_writes_state_baseline(session_factory,assert refreshed.status == "completed"state = json.loads((repo_dir / ".repowise" / "state.json").read_text(encoding="utf-8"))+ # A keyless first index now renders a deterministic template wiki rather+ # than skipping docs: docs_mode is "deterministic" (not "none"), there is no+ # skip reason, and docs_enabled stays False (a template wiki is not model+ # docs, so a legacy hook must not launch a provider-less LLM regen).assert state["docs_enabled"] is False- assert "no provider configured" in state["docs_skip_reason"]+ assert state["docs_mode"] == "deterministic"+ assert not state.get("docs_skip_reason")assert state["run_mode"] == "standard"assert state["git_tier"] == "full"assert state["config_fingerprint"]assert state["store_format_version"]- # The no-provider warning reached the event buffer for the SSE stream.+ # The template-wiki notice reached the event buffer for the SSE stream.events = app_state.job_events[job_id].since(0)assert any("No LLM provider configured" in e["text"] for e in events)diff --git a/tests/unit/server/test_job_executor.py b/tests/unit/server/test_job_executor.pyindex 075db6c79..76e24b8c8 100644--- a/tests/unit/server/test_job_executor.py+++ b/tests/unit/server/test_job_executor.py@@ -326,3 +326,238 @@ async def test_incremental_page_regen_passes_repo_path(tmp_path):generator.generate_all.assert_awaited_once()assert generator.generate_all.await_args.kwargs["repo_path"] == Path(repo_path)+++async def test_incremental_page_regen_sets_file_pages_only(tmp_path):+ """A server sync must scope generation to file pages (the D4 fix).++ ``_incremental_page_regen`` feeds generate_all a parsed_files filtered to+ the changed files. Without ``file_pages_only=True`` on the GenerationConfig,+ levels 3+ would rewrite the codebase map, module and overview pages from a+ one-commit view. This asserts the config the PageGenerator receives carries+ the flag, so repo-wide pages are left untouched on a partial sync.+ """+ repo_path = tmp_path+ repowise_dir = repo_path / ".repowise"+ repowise_dir.mkdir()+ (repowise_dir / "state.json").write_text('{"last_sync_commit": "base-sha"}', encoding="utf-8")++ result = SimpleNamespace(+ file_count=10,+ parsed_files=[],+ source_map={},+ graph_builder=SimpleNamespace(graph=lambda: object(), pagerank=lambda: {}),+ repo_structure=object(),+ repo_name="test-repo",+ git_meta_map={},+ )++ head_proc = SimpleNamespace(returncode=0, stdout="head-sha\n")++ detector = MagicMock()+ detector.get_changed_files.return_value = [object()]+ detector.get_affected_pages.return_value = SimpleNamespace(regenerate=["foo.py"])++ generator = MagicMock()+ generator.generate_all = AsyncMock(return_value=[])+ page_generator_cls = MagicMock(return_value=generator)++ # GenerationConfig is left unpatched so we inspect the real one.+ with (+ patch("subprocess.run", return_value=head_proc),+ patch("repowise.core.ingestion.ChangeDetector", return_value=detector),+ patch(+ "repowise.core.ingestion.change_detector.compute_adaptive_budget",+ return_value=5,+ ),+ patch("repowise.core.generation.PageGenerator", page_generator_cls),+ patch("repowise.core.generation.ContextAssembler"),+ patch("repowise.core.reasoning.resolve_reasoning", return_value="low"),+ patch("repowise.core.repo_config.load_repo_config", return_value={}),+ ):+ await _incremental_page_regen(+ Path(repo_path),+ result,+ llm_client=object(),+ job_config={},+ progress=None,+ )++ # PageGenerator(llm_client, assembler, generation_config, ...)+ generation_config = page_generator_cls.call_args.args[2]+ assert generation_config.file_pages_only is True+++# ---------------------------------------------------------------------------+# Deterministic template wiki on a keyless initial index (Part B)+# ---------------------------------------------------------------------------+++async def _seed_job_with_config(session_factory, repo_path, config: dict) -> str:+ """Insert a repo + a pending job carrying ``config``; return the job id."""+ async with session_factory() as session:+ repo = await upsert_repository(+ session, name="test-repo", local_path=str(repo_path), settings={}+ )+ job = await upsert_generation_job(session, repository_id=repo.id, config=config)+ await session.commit()+ return job.id+++def _no_provider():+ return patch(+ "repowise.server.provider_config.get_chat_provider_instance",+ side_effect=RuntimeError("no provider"),+ )+++async def test_initial_index_without_provider_renders_deterministic_wiki(+ session_factory, tmp_path+):+ """A keyless first index renders a template wiki instead of nothing.++ Without a provider, the pipeline runs in DETERMINISTIC mode (it supplies its+ own null TemplateProvider), so the repo gets a complete, upgradable template+ wiki rather than an empty index that reads as blank in the web UI.+ """+ from repowise.core.pipeline.modes import OrchestratorMode++ job_id = await _seed_job_with_config(session_factory, tmp_path, {"mode": "initial_index"})+ 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.job_executor._persist_initial_index_state"),+ _no_provider(),+ ):+ await execute_job(job_id, app_state)++ kwargs = run_pipeline_mock.await_args.kwargs+ assert kwargs["mode"] == OrchestratorMode.DETERMINISTIC+ assert kwargs["generate_docs"] is True+ assert kwargs["llm_client"] is None+++async def test_initial_index_without_provider_writes_deterministic_docs_mode(+ session_factory, tmp_path+):+ """The persisted docs mode is 'deterministic' on a keyless first index."""+ job_id = await _seed_job_with_config(session_factory, tmp_path, {"mode": "initial_index"})+ app_state = SimpleNamespace(session_factory=session_factory, fts=None, vector_store=None)++ persist_state = MagicMock()+ with (+ patch("repowise.server.job_executor.run_pipeline", AsyncMock(return_value=_fake_result())),+ patch("repowise.server.job_executor.persist_pipeline_result", AsyncMock()),+ patch("repowise.server.job_executor._persist_initial_index_state", persist_state),+ _no_provider(),+ ):+ await execute_job(job_id, app_state)++ persist_state.assert_called_once()+ assert persist_state.call_args.kwargs["docs_mode"] == "deterministic"+ assert persist_state.call_args.kwargs["llm_client"] is None+++async def test_initial_index_with_provider_uses_llm_mode(session_factory, tmp_path):+ """With a provider, a first index writes model docs ('llm'), STANDARD mode."""+ from repowise.core.pipeline.modes import OrchestratorMode++ job_id = await _seed_job_with_config(session_factory, tmp_path, {"mode": "initial_index"})+ app_state = SimpleNamespace(session_factory=session_factory, fts=None, vector_store=None)++ provider = SimpleNamespace(provider_name="openai", model_name="gpt-x")+ run_pipeline_mock = AsyncMock(return_value=_fake_result())+ persist_state = MagicMock()+ with (+ patch("repowise.server.job_executor.run_pipeline", run_pipeline_mock),+ patch("repowise.server.job_executor.persist_pipeline_result", AsyncMock()),+ patch("repowise.server.job_executor._persist_initial_index_state", persist_state),+ patch(+ "repowise.server.provider_config.get_chat_provider_instance",+ return_value=provider,+ ),+ ):+ await execute_job(job_id, app_state)++ assert run_pipeline_mock.await_args.kwargs["mode"] == OrchestratorMode.STANDARD+ assert run_pipeline_mock.await_args.kwargs["generate_docs"] is True+ assert persist_state.call_args.kwargs["docs_mode"] == "llm"+++async def test_initial_index_no_provider_generate_docs_false_writes_none(+ session_factory, tmp_path+):+ """An explicit generate_docs=False keyless index generates nothing ('none')."""+ from repowise.core.pipeline.modes import OrchestratorMode++ job_id = await _seed_job_with_config(+ session_factory, tmp_path, {"mode": "initial_index", "generate_docs": False}+ )+ app_state = SimpleNamespace(session_factory=session_factory, fts=None, vector_store=None)++ run_pipeline_mock = AsyncMock(return_value=_fake_result())+ persist_state = MagicMock()+ with (+ patch("repowise.server.job_executor.run_pipeline", run_pipeline_mock),+ patch("repowise.server.job_executor.persist_pipeline_result", AsyncMock()),+ patch("repowise.server.job_executor._persist_initial_index_state", persist_state),+ _no_provider(),+ ):+ await execute_job(job_id, app_state)++ assert run_pipeline_mock.await_args.kwargs["generate_docs"] is False+ assert run_pipeline_mock.await_args.kwargs["mode"] == OrchestratorMode.STANDARD+ assert persist_state.call_args.kwargs["docs_mode"] == "none"+++async def test_full_resync_without_provider_stays_index_only(session_factory, tmp_path):+ """A keyless full_resync must NOT template-overwrite an existing wiki.++ The deterministic fallback is scoped to initial_index; a keyless full_resync+ keeps its index-only behaviour so it can never replace a model-written wiki+ with templates.+ """+ from repowise.core.pipeline.modes import OrchestratorMode++ job_id = await _seed_job_with_config(session_factory, tmp_path, {"mode": "full_resync"})+ 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()),+ _no_provider(),+ ):+ await execute_job(job_id, app_state)++ assert run_pipeline_mock.await_args.kwargs["generate_docs"] is False+ assert run_pipeline_mock.await_args.kwargs["mode"] == OrchestratorMode.STANDARD+++async def test_index_only_job_does_not_generate_docs(session_factory, tmp_path):+ """The cheap index_only analysis refresh never renders a wiki."""+ from repowise.core.pipeline.modes import OrchestratorMode++ job_id = await _seed_job_with_config(session_factory, tmp_path, {"mode": "index_only"})+ 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()),+ _no_provider(),+ ):+ await execute_job(job_id, app_state)++ assert run_pipeline_mock.await_args.kwargs["generate_docs"] is False+ assert run_pipeline_mock.await_args.kwargs["mode"] == OrchestratorMode.STANDARD