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
refactor(generate): extract the scoped-generation engine into core (#982)
Raghav Chamadiya8d82449ed3a5
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py b/packages/cli/src/repowise/cli/commands/generate_cmd/engine.pyindex 34258df77..bc6f25d0a 100644--- a/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py@@ -1,9 +1,10 @@-"""The ``repowise generate`` engine: rehydrate -> scope -> gate -> generate.+"""The ``repowise generate`` engine (CLI wrapper).-Mirrors the upgrade/restyle flows (rehydrate the graph and git from SQL,-re-parse for ASTs, run generation, persist + FTS + embed) but drives the-generation through ``only_page_ids`` so it writes exactly the requested subset,-then marks the uncovered dependents stale and heals backlinks LLM-free.+Composes the portable core service+(:mod:`repowise.core.pipeline.scoped_generation`) with the CLI's environment:+its own DB engine, the interactive chooser / ranked-coverage seed, the cost gate,+and the terminal reporting. The rehydrate + generate + persist + heal half lives+in core so the OSS server and hosted share it."""from __future__ import annotations@@ -12,16 +13,13 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from repowise.cli.helpers import console+from repowise.cli.helpers import console, load_statefrom repowise.core.generation.cascade import CascadeModefrom repowise.core.generation.page_selection import PageSelectionIntent--from .scope import (- ScopePlan,- build_dependencies,- build_ranked_seed,- load_page_records,- resolve_scope,+from repowise.core.generation.scope import ScopePlan, build_ranked_seed, resolve_scope+from repowise.core.pipeline.scoped_generation import (+ execute_scoped_generation,+ rehydrate_repo,)@@ -70,7 +68,6 @@ async def run_scoped_generation(``--dry-run``. ``gate_cost`` is injected (the upgrade flow's estimator +confirm) so this module stays free of the cost-gate UI."""- from repowise.cli.commands.upgrade_flow import _reparsefrom repowise.cli.helpers import get_db_url_for_repofrom repowise.cli.providers import (build_embedder,@@ -79,19 +76,14 @@ async def run_scoped_generation(resolve_embedder,)from repowise.core.generation.cost_tracker import CostTracker- from repowise.core.generation.kg_context import KnowledgeGraphContextfrom repowise.core.persistence import (+ FullTextSearch,create_engine,create_session_factory,- get_session,init_db,- upsert_pages_from_generated,upsert_repository,)- from repowise.core.persistence.crud import backfill_related_pages- from repowise.core.pipeline import rehydrate_graph_builder, run_generation- from repowise.core.pipeline.persist import mark_page_ids_stale- from repowise.core.pipeline.resume.rehydrate import rehydrate_git_meta_map+ from repowise.core.persistence import get_session as _get_sessionurl = get_db_url_for_repo(repo_path)engine = create_engine(url)@@ -99,38 +91,34 @@ async def run_scoped_generation(sf = create_session_factory(engine)try:- async with get_session(sf) as session:+ 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 re-resolve, no re-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)- records = load_page_records(await _load_pages(session, repo_id))-- if not records:+ # Honor the persisted submodule/nested-repo semantics of the original+ # index so the docs re-parse covers the same file set init did.+ state = load_state(repo_path)+ rehydrated = await rehydrate_repo(+ sf,+ repo_id,+ repo_path,+ generation_config=config,+ exclude_patterns=exclude_patterns,+ include_submodules=bool(state.get("include_submodules", False)),+ include_nested_repos=bool(state.get("include_nested_repos", False)),+ )+ if rehydrated is None:console.print("[yellow]This repo has no wiki pages yet.[/yellow] ""Run `repowise init --index-only` or `repowise update --full` first.")return None- 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)."+ f"Re-parsed [cyan]{len(rehydrated.parsed_files)}[/cyan] files "+ "(graph + git reused from index).")- repo_name = repo_path.name- kg_ctx = _load_kg_ctx(repo_path, KnowledgeGraphContext)- deps = build_dependencies(- parsed_files=parsed_files,- graph_builder=graph_builder,- config=config,- kg_ctx=kg_ctx,- records=records,- repo_name=repo_name,- )# Ranked (coverage/top) and interactive runs replace the intent seed# with an importance-ranked page-id set; explicit runs leave it None.ranked_seed: set[str] | None = None@@ -139,15 +127,15 @@ async def run_scoped_generation(choice = run_interactive_chooser(console,- records=records,- parsed_files=parsed_files,- graph_builder=graph_builder,+ records=rehydrated.records,+ parsed_files=rehydrated.parsed_files,+ graph_builder=rehydrated.graph_builder,config=config,- kg_ctx=kg_ctx,+ kg_ctx=rehydrated.kg_ctx,provider=provider,repo_path=repo_path,- repo_name=repo_name,- deps=deps,+ repo_name=rehydrated.repo_name,+ deps=rehydrated.deps,)if choice is None:return None@@ -156,14 +144,14 @@ async def run_scoped_generation(elif coverage_pct is not None or top_n is not None:pct = coverage_pctif pct is None:- pct = _coverage_from_top(top_n or 0, len(parsed_files))+ pct = _coverage_from_top(top_n or 0, len(rehydrated.parsed_files))ranked_seed = build_ranked_seed(- parsed_files=parsed_files,- graph_builder=graph_builder,+ parsed_files=rehydrated.parsed_files,+ graph_builder=rehydrated.graph_builder,config=config,- kg_ctx=kg_ctx,- records=records,- repo_name=repo_name,+ kg_ctx=rehydrated.kg_ctx,+ records=rehydrated.records,+ repo_name=rehydrated.repo_name,coverage_pct=pct,)if not ranked_seed:@@ -174,10 +162,10 @@ async def run_scoped_generation(return Noneplan = resolve_scope(- records=records,+ records=rehydrated.records,intent=intent,cascade_mode=cascade_mode,- deps=deps,+ deps=rehydrated.deps,ranked_seed=ranked_seed,)@@ -203,7 +191,6 @@ async def run_scoped_generation(cost_tracker = CostTracker()else:cost_tracker = CostTracker(session_factory=sf, repo_id=repo_id, buffered=True)- provider._cost_tracker = cost_trackerembedder = Nonevector_store = None@@ -212,64 +199,44 @@ async def run_scoped_generation(vector_store = build_vector_store(repo_path, embedder)except Exception as exc:# Null BOTH on any failure. If the embedder built but the store did- # not, a non-None embedder would make run_generation embed into a+ # not, a non-None embedder would make generation embed into a# throwaway in-memory store — pages silently absent from semantic# search while we claimed embedding was skipped.embedder = Nonevector_store = Noneconsole.print(f"[yellow]Embedding skipped: {exc}[/yellow]")- generated_pages = await run_generation(+ # Best-effort: a failure to open the FTS index must not abort a run whose+ # pages are already generated. Nulling fts skips indexing (as the old+ # blanket-guarded _index_fts did) rather than raising.+ fts: Any | None = FullTextSearch(engine)+ try:+ await fts.ensure_index()+ except Exception as exc:+ console.print(f"[dim]Full-text index unavailable: {exc}[/dim]")+ fts = None++ result = await execute_scoped_generation(+ session_factory=sf,+ repo_id=repo_id,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,+ rehydrated=rehydrated,+ plan=plan,+ provider=provider,+ generation_config=config,embedder=embedder,vector_store=vector_store,- concurrency=config.max_concurrency,+ fts=fts,progress=None,cost_tracker=cost_tracker,- generation_config=config,- only_page_ids=plan.generate_ids,+ concurrency=config.max_concurrency,)- await cost_tracker.flush()-- marked_stale = 0- async with get_session(sf) as session:- await upsert_pages_from_generated(session, generated_pages, repo_id)- # Dependents this run did not regenerate go stale, not wrong.- marked_stale = await mark_page_ids_stale(session, repo_id, plan.stale_ids)- # Heal backlinks + related-pages across the whole wiki, LLM-free. The- # pages this run just wrote already carry fresh metadata, so skip them.- # This is O(total pages), same as the incremental-update path's heal;- # a narrow scope on a huge wiki pays for the whole table. Upgrade path- # if that ever bites: scope the heal to the regenerated pages' import- # neighborhood. Kept whole-wiki for now to match the update flow and- # because it is LLM-free (cheap next to the generation it follows).- try:- from repowise.core.generation.related_pages import file_import_edges-- await backfill_related_pages(- session,- repo_id,- import_edges=file_import_edges(graph_builder),- git_meta_map=git_meta_map,- pagerank=graph_builder.pagerank(),- skip_page_ids={p.page_id for p in generated_pages},- )- except Exception as exc:- console.print(f"[dim]Related-pages backfill skipped: {exc}[/dim]")-- await _index_fts(engine, generated_pages)total_pages, remaining_templates = await _page_stats(sf, repo_id)return GenerateOutcome(- generated_pages=generated_pages,+ generated_pages=result.generated_pages,total_pages=total_pages,- marked_stale=marked_stale,+ marked_stale=result.marked_stale,remaining_template_pages=remaining_templates,plan=plan,)@@ -277,59 +244,6 @@ async def run_scoped_generation(await engine.dispose()-async def _load_pages(session: Any, repo_id: str) -> list[Any]:- """Every non-tombstoned persisted page, lightweight columns only.-- ``load_page_records`` reads just id/type/target/provider/metadata/freshness,- so ``load_only`` keeps the (potentially very large) ``content`` Text column- out of this whole-wiki scan.- """- from sqlalchemy import select- from sqlalchemy.orm import load_only-- from repowise.core.persistence.models import Page-- result = await session.execute(- select(Page)- .options(- load_only(- Page.id,- Page.page_type,- Page.target_path,- Page.provider_name,- Page.metadata_json,- Page.freshness_status,- )- )- .where(- Page.repository_id == repo_id,- Page.freshness_status != "tombstone",- )- )- return list(result.scalars())---def _load_kg_ctx(repo_path: Path, kg_ctx_cls: Any) -> Any:- """Load the persisted KG artifact for layer membership (None-safe)."""- kg_path = repo_path / ".repowise" / "knowledge-graph.json"- if kg_path.exists():- return kg_ctx_cls(kg_path)- return kg_ctx_cls(None)---async def _index_fts(engine: Any, generated_pages: list[Any]) -> None:- """Best-effort full-text (re)index of the freshly generated pages."""- try:- from repowise.core.persistence import FullTextSearch-- 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--async def _page_stats(sf: Any, repo_id: str) -> tuple[int, int]:"""Return ``(total_pages, remaining_template_pages)`` from the DB."""from sqlalchemy import func as sa_funcdiff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/scope.py b/packages/cli/src/repowise/cli/commands/generate_cmd/scope.pyindex 14c3ed984..2e9fed723 100644--- a/packages/cli/src/repowise/cli/commands/generate_cmd/scope.py+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/scope.py@@ -1,307 +1,35 @@-"""Resolve a ``repowise generate`` request into a concrete page-id set.+"""Back-compat shim: the scope resolver now lives in ``repowise.core``.-Pure, side-effect-free helpers: given the persisted pages and the freshly-rehydrated graph, turn the user's intent (all / unwritten / stale / paths /-ids) plus a cascade mode into the ``only_page_ids`` set the engine generates,-the dependents to mark stale, and the cost plan (which includes the cascade-fallout, so the estimate does not under-quote).+The pure scope-resolution logic moved to :mod:`repowise.core.generation.scope`+so the OSS server and hosted can resolve a generation scope the same way the CLI+does, without depending on the CLI package. This module re-exports it unchanged+for existing call sites and tests."""from __future__ import annotations-import json-from dataclasses import dataclass, replace-from typing import Any--from repowise.core.cost_estimator.types import PageTypePlan-from repowise.core.generation import GENERATION_LEVELS-from repowise.core.generation.cascade import (- CascadeMode,- CascadeResult,- PageDependencies,- build_page_dependencies,- expand_cascade,-)-from repowise.core.generation.models import compute_page_id-from repowise.core.generation.page_selection import (- PageRecord,- PageSelectionIntent,- resolve_page_selection,+from repowise.core.generation.scope import (+ ScopePlan,+ _layer_membership,+ _ranked_ids_to_seed,+ _selection_inputs,+ build_cost_plans,+ build_dependencies,+ build_ranked_seed,+ load_page_records,+ resolve_scope,+ selection_page_ids,)-from repowise.core.generation.selection import Selection, SelectionInputs, select_pages--# Page types that describe the whole repository (as opposed to one file/module).-_REPO_WIDE_TYPES = frozenset({"repo_overview", "architecture_diagram", "onboarding"})--# Structural pages the coverage budget does not rank: layer pages come from KG-# membership and onboarding is curated, so init emits every one of them at every-# coverage. A ranked run includes the unwritten ones rather than leaving holes in-# the navigation. (repo_overview / architecture come from the Selection itself.)-_STRUCTURAL_PAGE_TYPES = frozenset({"layer_page", "onboarding"})---@dataclass(frozen=True)-class ScopePlan:- """Everything the engine needs to run and report one scoped generation."""-- generate_ids: set[str]- stale_ids: set[str]- cost_plans: list[PageTypePlan]- unknown_page_ids: tuple[str, ...]- seed_count: int---def load_page_records(pages: list[Any]) -> list[PageRecord]:- """Build :class:`PageRecord` views from persisted ``Page`` rows.-- A page is "template" (unwritten) when a model never touched it: the- template provider stamps ``provider_name='template'`` and- ``metadata.deterministic=True``. Either signal is enough.- """- records: list[PageRecord] = []- for p in pages:- try:- meta = json.loads(getattr(p, "metadata_json", None) or "{}")- except ValueError:- meta = {}- is_template = getattr(p, "provider_name", "") == "template" or bool(- meta.get("deterministic")- )- records.append(- PageRecord(- page_id=p.id,- page_type=p.page_type,- target_path=p.target_path,- is_template=is_template,- freshness_status=getattr(p, "freshness_status", "fresh"),- )- )- return records---def _layer_membership(kg_ctx: Any) -> dict[str, str]:- """Map each file path to its ``layer_page:<id>`` from KG layer membership."""- out: dict[str, str] = {}- if not (kg_ctx and getattr(kg_ctx, "available", False)):- return out- from repowise.core.analysis.knowledge_graph import _slugify-- for layer in kg_ctx.get_layers():- layer_id = layer.get("id") or f"layer:{_slugify(layer.get('name', ''))}"- page_id = compute_page_id("layer_page", layer_id)- for nid in layer.get("nodeIds", []):- if isinstance(nid, str) and nid.startswith("file:"):- out.setdefault(nid[5:], page_id)- return out---def _selection_inputs(- *,- parsed_files: list[Any],- graph_builder: Any,- config: Any,- kg_ctx: Any,- select_all: bool,-) -> SelectionInputs:- """Bundle the inputs :func:`select_pages` needs from the rehydrated graph.-- Shared by the cascade-dependency selection (``select_all=True``) and the- ranked coverage selection (``select_all=False`` + a coverage-scoped config),- so both derive their page ids from the same graph metrics and KG modules.- """- try:- community_info_map = graph_builder.community_info() or {}- except Exception:- community_info_map = {}-- kg_modules = None- if kg_ctx and getattr(kg_ctx, "available", False):- kg_modules = kg_ctx.get_modules() or None-- return SelectionInputs(- parsed_files=parsed_files,- pagerank=graph_builder.pagerank(),- betweenness=graph_builder.betweenness_centrality(),- community=graph_builder.community_detection(),- community_info=community_info_map,- sccs=list(graph_builder.strongly_connected_components()),- git_meta_map=None,- config=config,- kg_modules=kg_modules,- select_all=select_all,- )---def build_dependencies(- *,- parsed_files: list[Any],- graph_builder: Any,- config: Any,- kg_ctx: Any,- records: list[PageRecord],- repo_name: str,-) -> PageDependencies:- """Compute the structural file -> container-page map for cascade.-- Uses the same full-coverage selection the engine will use- (``select_all=True``), so the module/SCC page ids it derives match the ones- generation emits. Repo-wide ids are the overview + architecture pages- (keyed by repo name) plus every persisted onboarding page.- """- selection = select_pages(- _selection_inputs(- parsed_files=parsed_files,- graph_builder=graph_builder,- config=config,- kg_ctx=kg_ctx,- select_all=True,- )- )-- repo_wide_ids = [- compute_page_id("repo_overview", repo_name),- compute_page_id("architecture_diagram", repo_name),- ]- repo_wide_ids += [r.page_id for r in records if r.page_type == "onboarding"]-- return build_page_dependencies(- module_groups=selection.module_groups,- scc_groups=selection.scc_groups,- layer_page_of=_layer_membership(kg_ctx),- repo_wide_ids=repo_wide_ids,- )---def selection_page_ids(sel: Selection, repo_name: str) -> set[str]:- """Turn a budgeted :class:`Selection` into the page ids generation emits.-- Mirrors the id assignment in the page generator's level builders exactly- (``levels.py``), so a ranked coverage pick names the same pages a full run- at that coverage would write. Repo-wide overview/architecture pages are- keyed by the repo name; onboarding is not budgeted here (the caller adds it).- """- ids: set[str] = set()- ids.update(compute_page_id("file_page", p) for p in sel.file_page_paths)- ids.update(compute_page_id("module_page", mg.key) for mg in sel.module_groups)- ids.update(compute_page_id("scc_page", scc_id) for scc_id, _ in sel.scc_groups)- ids.update(compute_page_id("api_contract", p) for p in sel.api_contract_paths)- ids.update(compute_page_id("infra_page", p) for p in sel.infra_paths)- ids.update(- compute_page_id("symbol_spotlight", f"{path}::{name}")- for path, name in sel.symbol_spotlights- )- if sel.emit_repo_overview:- ids.add(compute_page_id("repo_overview", repo_name))- if sel.emit_arch_diagram:- ids.add(compute_page_id("architecture_diagram", repo_name))- return ids---def build_ranked_seed(- *,- parsed_files: list[Any],- graph_builder: Any,- config: Any,- kg_ctx: Any,- records: list[PageRecord],- repo_name: str,- coverage_pct: float,-) -> set[str]:- """The unwritten pages inside the top ``coverage_pct`` by importance.-- Runs the *budgeted* selection at ``coverage_pct`` (the same importance model- ``repowise init`` uses at that coverage) and maps it to page ids. The- file / module / cycle / symbol content pages are what coverage rations;- the repo-wide and structural pages (overview, architecture, layers,- onboarding) are always included when unwritten, as init emits them at every- coverage. Only ids that exist as template pages survive: a written page is- not re-billed, and a selected id with no page yet (a file added since- indexing) is dropped, since ``generate`` only rewrites existing pages.-- One deliberate simplification: the selection here is demand-free- (``demand=None``), whereas a full init pass tilts its file-page picks by- mined session demand. On a fresh install the two are identical; where session- history exists they can pick the same *count* of files but a slightly- different set. Not worth reading every transcript on each generate run.- """- coverage_cfg = replace(- config, coverage_pct=coverage_pct, max_pages_pct=coverage_pct, deterministic=False- )- selection = select_pages(- _selection_inputs(- parsed_files=parsed_files,- graph_builder=graph_builder,- config=coverage_cfg,- kg_ctx=kg_ctx,- select_all=False,- )- )- return _ranked_ids_to_seed(selection_page_ids(selection, repo_name), records)---def _ranked_ids_to_seed(ranked_ids: set[str], records: list[PageRecord]) -> set[str]:- """Restrict ranked ids to the unwritten pages, adding structural pages.-- Layer + onboarding pages are structural: the budgeted selection does not- rank them (layers come from KG membership, onboarding is curated), and init- writes every one of them regardless of coverage. Add the unwritten ones so a- coverage upgrade produces the same navigable wiki init would, then keep only- ids that exist as template pages today.- """- structural_ids = {- r.page_id for r in records if r.page_type in _STRUCTURAL_PAGE_TYPES and r.is_template- }- template_ids = {r.page_id for r in records if r.is_template}- return (ranked_ids | structural_ids) & template_ids---def build_cost_plans(generate_ids: set[str]) -> list[PageTypePlan]:- """Group the id set by page type into cost-estimator plans.-- Because ``generate_ids`` already carries the cascade fallout, the resulting- estimate covers it too — the under-quote the plan warned about.- """- counts: dict[str, int] = {}- for pid in generate_ids:- ptype = pid.split(":", 1)[0]- counts[ptype] = counts.get(ptype, 0) + 1- return [- PageTypePlan(page_type=ptype, count=n, level=GENERATION_LEVELS.get(ptype, 2))- for ptype, n in sorted(counts.items(), key=lambda kv: GENERATION_LEVELS.get(kv[0], 2))- ]---def resolve_scope(- *,- records: list[PageRecord],- intent: PageSelectionIntent,- cascade_mode: CascadeMode,- deps: PageDependencies,- ranked_seed: set[str] | None = None,-) -> ScopePlan:- """Resolve seeds -> cascade -> the full scope plan.-- ``ranked_seed`` short-circuits the intent selectors: a ``--coverage`` /- ``--top`` run has already picked the exact page-id set by importance (see- :func:`build_ranked_seed`), so it is used verbatim as the seed. Otherwise- the intent (all / unwritten / stale / paths / ids) is resolved against the- existing records.- """- if ranked_seed is not None:- seed_ids = set(ranked_seed)- unknown: tuple[str, ...] = ()- seed_count = len(seed_ids)- else:- seeds = resolve_page_selection(records, intent)- seed_ids = set(seeds.page_ids)- unknown = seeds.unknown_page_ids- seed_count = len(seeds)- cascade: CascadeResult = expand_cascade(seed_ids, cascade_mode, deps)- return ScopePlan(- generate_ids=cascade.generate_ids,- stale_ids=cascade.stale_ids,- cost_plans=build_cost_plans(cascade.generate_ids),- unknown_page_ids=unknown,- seed_count=seed_count,- )+__all__ = [+ "ScopePlan",+ "_layer_membership",+ "_ranked_ids_to_seed",+ "_selection_inputs",+ "build_cost_plans",+ "build_dependencies",+ "build_ranked_seed",+ "load_page_records",+ "resolve_scope",+ "selection_page_ids",+]diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.pyindex 176a3a13c..1737e2f43 100644--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py@@ -92,37 +92,23 @@ def _gate_cost(def _reparse(repo_path: Path, exclude_patterns: list[str]) -> tuple[list[Any], dict[str, bytes], Any]:"""Parse files for ASTs + source bytes WITHOUT building/resolving the graph.- The graph is rehydrated from SQL separately; here we only need the parsed- files and raw source the generator consumes. Skipping ``GraphBuilder.build``- is the whole point — that resolution pass is what the fast index already did.+ Thin CLI wrapper over :func:`repowise.core.pipeline.reparse_repo`: reads the+ persisted submodule/nested-repo semantics from ``state.json`` so a fast index+ built with ``--include-submodules`` re-parses the same file set, then defers+ to the shared core parser."""- from repowise.core.ingestion import ASTParser, FileTraverser+ from repowise.core.pipeline import reparse_repo# Honor the persisted submodule semantics of the original index — a# fast index built with --include-submodules must not drop submodule# files from the docs re-parse (missing key → False, legacy behavior).state = load_state(repo_path)- traverser = FileTraverser(+ return reparse_repo(repo_path,- extra_exclude_patterns=exclude_patterns or None,+ exclude_patterns,include_submodules=bool(state.get("include_submodules", False)),include_nested_repos=bool(state.get("include_nested_repos", False)),)- file_infos = list(traverser.traverse())- repo_structure = traverser.get_repo_structure()-- parser = ASTParser()- parsed_files: list[Any] = []- source_map: dict[str, bytes] = {}- for fi in file_infos:- try:- source = Path(fi.abs_path).read_bytes()- parsed = parser.parse_file(fi, source)- parsed_files.append(parsed)- source_map[fi.path] = source- except Exception:- pass # unreadable / unparseable files are skipped, as in init- return parsed_files, source_map, repo_structureasync def _backfill_git(diff --git a/packages/core/src/repowise/core/generation/scope.py b/packages/core/src/repowise/core/generation/scope.pynew file mode 100644index 000000000..9ab9535e9--- /dev/null+++ b/packages/core/src/repowise/core/generation/scope.py@@ -0,0 +1,310 @@+"""Resolve a scoped-generation request into a concrete page-id set.++Pure, side-effect-free helpers: given the persisted pages and a rehydrated+graph, turn a user's intent (all / unwritten / stale / paths / ids) plus a+cascade mode into the ``only_page_ids`` set the engine generates, the dependents+to mark stale, and the cost plan (which includes the cascade fallout, so the+estimate does not under-quote).++This module has no CLI or server dependencies: it imports only from+``repowise.core``, so the OSS CLI, the OSS server, and hosted all resolve a+generation scope the same way.+"""++from __future__ import annotations++import json+from dataclasses import dataclass, replace+from typing import Any++from repowise.core.cost_estimator.types import PageTypePlan+from repowise.core.generation.cascade import (+ CascadeMode,+ CascadeResult,+ PageDependencies,+ build_page_dependencies,+ expand_cascade,+)+from repowise.core.generation.models import GENERATION_LEVELS, compute_page_id+from repowise.core.generation.page_selection import (+ PageRecord,+ PageSelectionIntent,+ resolve_page_selection,+)+from repowise.core.generation.selection import Selection, SelectionInputs, select_pages++# Page types that describe the whole repository (as opposed to one file/module).+_REPO_WIDE_TYPES = frozenset({"repo_overview", "architecture_diagram", "onboarding"})++# Structural pages the coverage budget does not rank: layer pages come from KG+# membership and onboarding is curated, so init emits every one of them at every+# coverage. A ranked run includes the unwritten ones rather than leaving holes in+# the navigation. (repo_overview / architecture come from the Selection itself.)+_STRUCTURAL_PAGE_TYPES = frozenset({"layer_page", "onboarding"})+++@dataclass(frozen=True)+class ScopePlan:+ """Everything the engine needs to run and report one scoped generation."""++ generate_ids: set[str]+ stale_ids: set[str]+ cost_plans: list[PageTypePlan]+ unknown_page_ids: tuple[str, ...]+ seed_count: int+++def load_page_records(pages: list[Any]) -> list[PageRecord]:+ """Build :class:`PageRecord` views from persisted ``Page`` rows.++ A page is "template" (unwritten) when a model never touched it: the+ template provider stamps ``provider_name='template'`` and+ ``metadata.deterministic=True``. Either signal is enough.+ """+ records: list[PageRecord] = []+ for p in pages:+ try:+ meta = json.loads(getattr(p, "metadata_json", None) or "{}")+ except ValueError:+ meta = {}+ is_template = getattr(p, "provider_name", "") == "template" or bool(+ meta.get("deterministic")+ )+ records.append(+ PageRecord(+ page_id=p.id,+ page_type=p.page_type,+ target_path=p.target_path,+ is_template=is_template,+ freshness_status=getattr(p, "freshness_status", "fresh"),+ )+ )+ return records+++def _layer_membership(kg_ctx: Any) -> dict[str, str]:+ """Map each file path to its ``layer_page:<id>`` from KG layer membership."""+ out: dict[str, str] = {}+ if not (kg_ctx and getattr(kg_ctx, "available", False)):+ return out+ from repowise.core.analysis.knowledge_graph import _slugify++ for layer in kg_ctx.get_layers():+ layer_id = layer.get("id") or f"layer:{_slugify(layer.get('name', ''))}"+ page_id = compute_page_id("layer_page", layer_id)+ for nid in layer.get("nodeIds", []):+ if isinstance(nid, str) and nid.startswith("file:"):+ out.setdefault(nid[5:], page_id)+ return out+++def _selection_inputs(+ *,+ parsed_files: list[Any],+ graph_builder: Any,+ config: Any,+ kg_ctx: Any,+ select_all: bool,+) -> SelectionInputs:+ """Bundle the inputs :func:`select_pages` needs from the rehydrated graph.++ Shared by the cascade-dependency selection (``select_all=True``) and the+ ranked coverage selection (``select_all=False`` + a coverage-scoped config),+ so both derive their page ids from the same graph metrics and KG modules.+ """+ try:+ community_info_map = graph_builder.community_info() or {}+ except Exception:+ community_info_map = {}++ kg_modules = None+ if kg_ctx and getattr(kg_ctx, "available", False):+ kg_modules = kg_ctx.get_modules() or None++ return SelectionInputs(+ parsed_files=parsed_files,+ pagerank=graph_builder.pagerank(),+ betweenness=graph_builder.betweenness_centrality(),+ community=graph_builder.community_detection(),+ community_info=community_info_map,+ sccs=list(graph_builder.strongly_connected_components()),+ git_meta_map=None,+ config=config,+ kg_modules=kg_modules,+ select_all=select_all,+ )+++def build_dependencies(+ *,+ parsed_files: list[Any],+ graph_builder: Any,+ config: Any,+ kg_ctx: Any,+ records: list[PageRecord],+ repo_name: str,+) -> PageDependencies:+ """Compute the structural file -> container-page map for cascade.++ Uses the same full-coverage selection the engine will use+ (``select_all=True``), so the module/SCC page ids it derives match the ones+ generation emits. Repo-wide ids are the overview + architecture pages+ (keyed by repo name) plus every persisted onboarding page.+ """+ selection = select_pages(+ _selection_inputs(+ parsed_files=parsed_files,+ graph_builder=graph_builder,+ config=config,+ kg_ctx=kg_ctx,+ select_all=True,+ )+ )++ repo_wide_ids = [+ compute_page_id("repo_overview", repo_name),+ compute_page_id("architecture_diagram", repo_name),+ ]+ repo_wide_ids += [r.page_id for r in records if r.page_type == "onboarding"]++ return build_page_dependencies(+ module_groups=selection.module_groups,+ scc_groups=selection.scc_groups,+ layer_page_of=_layer_membership(kg_ctx),+ repo_wide_ids=repo_wide_ids,+ )+++def selection_page_ids(sel: Selection, repo_name: str) -> set[str]:+ """Turn a budgeted :class:`Selection` into the page ids generation emits.++ Mirrors the id assignment in the page generator's level builders exactly+ (``levels.py``), so a ranked coverage pick names the same pages a full run+ at that coverage would write. Repo-wide overview/architecture pages are+ keyed by the repo name; onboarding is not budgeted here (the caller adds it).+ """+ ids: set[str] = set()+ ids.update(compute_page_id("file_page", p) for p in sel.file_page_paths)+ ids.update(compute_page_id("module_page", mg.key) for mg in sel.module_groups)+ ids.update(compute_page_id("scc_page", scc_id) for scc_id, _ in sel.scc_groups)+ ids.update(compute_page_id("api_contract", p) for p in sel.api_contract_paths)+ ids.update(compute_page_id("infra_page", p) for p in sel.infra_paths)+ ids.update(+ compute_page_id("symbol_spotlight", f"{path}::{name}")+ for path, name in sel.symbol_spotlights+ )+ if sel.emit_repo_overview:+ ids.add(compute_page_id("repo_overview", repo_name))+ if sel.emit_arch_diagram:+ ids.add(compute_page_id("architecture_diagram", repo_name))+ return ids+++def build_ranked_seed(+ *,+ parsed_files: list[Any],+ graph_builder: Any,+ config: Any,+ kg_ctx: Any,+ records: list[PageRecord],+ repo_name: str,+ coverage_pct: float,+) -> set[str]:+ """The unwritten pages inside the top ``coverage_pct`` by importance.++ Runs the *budgeted* selection at ``coverage_pct`` (the same importance model+ ``repowise init`` uses at that coverage) and maps it to page ids. The+ file / module / cycle / symbol content pages are what coverage rations;+ the repo-wide and structural pages (overview, architecture, layers,+ onboarding) are always included when unwritten, as init emits them at every+ coverage. Only ids that exist as template pages survive: a written page is+ not re-billed, and a selected id with no page yet (a file added since+ indexing) is dropped, since ``generate`` only rewrites existing pages.++ One deliberate simplification: the selection here is demand-free+ (``demand=None``), whereas a full init pass tilts its file-page picks by+ mined session demand. On a fresh install the two are identical; where session+ history exists they can pick the same *count* of files but a slightly+ different set. Not worth reading every transcript on each generate run.+ """+ coverage_cfg = replace(+ config, coverage_pct=coverage_pct, max_pages_pct=coverage_pct, deterministic=False+ )+ selection = select_pages(+ _selection_inputs(+ parsed_files=parsed_files,+ graph_builder=graph_builder,+ config=coverage_cfg,+ kg_ctx=kg_ctx,+ select_all=False,+ )+ )+ return _ranked_ids_to_seed(selection_page_ids(selection, repo_name), records)+++def _ranked_ids_to_seed(ranked_ids: set[str], records: list[PageRecord]) -> set[str]:+ """Restrict ranked ids to the unwritten pages, adding structural pages.++ Layer + onboarding pages are structural: the budgeted selection does not+ rank them (layers come from KG membership, onboarding is curated), and init+ writes every one of them regardless of coverage. Add the unwritten ones so a+ coverage upgrade produces the same navigable wiki init would, then keep only+ ids that exist as template pages today.+ """+ structural_ids = {+ r.page_id for r in records if r.page_type in _STRUCTURAL_PAGE_TYPES and r.is_template+ }+ template_ids = {r.page_id for r in records if r.is_template}+ return (ranked_ids | structural_ids) & template_ids+++def build_cost_plans(generate_ids: set[str]) -> list[PageTypePlan]:+ """Group the id set by page type into cost-estimator plans.++ Because ``generate_ids`` already carries the cascade fallout, the resulting+ estimate covers it too — the under-quote the plan warned about.+ """+ counts: dict[str, int] = {}+ for pid in generate_ids:+ ptype = pid.split(":", 1)[0]+ counts[ptype] = counts.get(ptype, 0) + 1+ return [+ PageTypePlan(page_type=ptype, count=n, level=GENERATION_LEVELS.get(ptype, 2))+ for ptype, n in sorted(counts.items(), key=lambda kv: GENERATION_LEVELS.get(kv[0], 2))+ ]+++def resolve_scope(+ *,+ records: list[PageRecord],+ intent: PageSelectionIntent,+ cascade_mode: CascadeMode,+ deps: PageDependencies,+ ranked_seed: set[str] | None = None,+) -> ScopePlan:+ """Resolve seeds -> cascade -> the full scope plan.++ ``ranked_seed`` short-circuits the intent selectors: a ``--coverage`` /+ ``--top`` run has already picked the exact page-id set by importance (see+ :func:`build_ranked_seed`), so it is used verbatim as the seed. Otherwise+ the intent (all / unwritten / stale / paths / ids) is resolved against the+ existing records.+ """+ if ranked_seed is not None:+ seed_ids = set(ranked_seed)+ unknown: tuple[str, ...] = ()+ seed_count = len(seed_ids)+ else:+ seeds = resolve_page_selection(records, intent)+ seed_ids = set(seeds.page_ids)+ unknown = seeds.unknown_page_ids+ seed_count = len(seeds)++ cascade: CascadeResult = expand_cascade(seed_ids, cascade_mode, deps)+ return ScopePlan(+ generate_ids=cascade.generate_ids,+ stale_ids=cascade.stale_ids,+ cost_plans=build_cost_plans(cascade.generate_ids),+ unknown_page_ids=unknown,+ seed_count=seed_count,+ )diff --git a/packages/core/src/repowise/core/pipeline/__init__.py b/packages/core/src/repowise/core/pipeline/__init__.pyindex 0b0497b00..50e753f60 100644--- a/packages/core/src/repowise/core/pipeline/__init__.py+++ b/packages/core/src/repowise/core/pipeline/__init__.py@@ -23,6 +23,7 @@ from .persist import ()from .phase_timing import PhaseTimingRecorderfrom .progress import LoggingProgressCallback, ProgressCallback+from .reparse import reparse_repofrom .upgrade import rehydrate_graph_builder__all__ = [@@ -36,6 +37,7 @@ __all__ = ["persist_ingestion","persist_pipeline_result","rehydrate_graph_builder",+ "reparse_repo","run_generation","run_pipeline","sweep_stale_generated_pages",diff --git a/packages/core/src/repowise/core/pipeline/reparse.py b/packages/core/src/repowise/core/pipeline/reparse.pynew file mode 100644index 000000000..5ec0eb2cf--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/reparse.py@@ -0,0 +1,58 @@+"""Re-parse a repo for ASTs + source bytes without rebuilding the graph.++The scoped-generation and upgrade flows rehydrate the dependency graph from SQL+(no re-resolution, no centrality recompute) but still need live ``ParsedFile``+ASTs and the raw source bytes the generator consumes. This is the one+unavoidable re-work: parsing is parse-cache-backed, so unchanged files skip+tree-sitter.++Kept env-agnostic — the traversal flags are passed in rather than read from+``.repowise/state.json`` here, so the OSS CLI, the OSS server, and hosted can each+resolve those flags their own way and share this parser.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any+++def reparse_repo(+ repo_path: Path,+ exclude_patterns: list[str],+ *,+ include_submodules: bool = False,+ include_nested_repos: bool = False,+) -> tuple[list[Any], dict[str, bytes], Any]:+ """Parse files for ASTs + source bytes WITHOUT building/resolving the graph.++ Returns ``(parsed_files, source_map, repo_structure)``. Unreadable or+ unparseable files are skipped, exactly as ``repowise init`` does.++ ``include_submodules`` / ``include_nested_repos`` must match the semantics of+ the original index — a fast index built with ``--include-submodules`` must+ not drop submodule files from the docs re-parse.+ """+ from repowise.core.ingestion import ASTParser, FileTraverser++ traverser = FileTraverser(+ repo_path,+ extra_exclude_patterns=exclude_patterns or None,+ include_submodules=include_submodules,+ include_nested_repos=include_nested_repos,+ )+ file_infos = list(traverser.traverse())+ repo_structure = traverser.get_repo_structure()++ parser = ASTParser()+ parsed_files: list[Any] = []+ source_map: dict[str, bytes] = {}+ for fi in file_infos:+ try:+ source = Path(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ parsed_files.append(parsed)+ source_map[fi.path] = source+ except Exception:+ pass # unreadable / unparseable files are skipped, as in init+ return parsed_files, source_map, repo_structurediff --git a/packages/core/src/repowise/core/pipeline/scoped_generation.py b/packages/core/src/repowise/core/pipeline/scoped_generation.pynew file mode 100644index 000000000..c8696218e--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/scoped_generation.py@@ -0,0 +1,267 @@+"""Portable scoped-generation service: rehydrate -> generate a subset -> persist.++The engine behind ``repowise generate`` and its server/hosted equivalents. It+writes exactly the requested subset of wiki pages (``only_page_ids``), then marks+the uncovered structural dependents stale and heals backlinks LLM-free.++Two building blocks, deliberately separate so each caller injects its own+environment (DB engine, provider, embedder/vector store, FTS, progress, cost+tracker) and keeps the cost-gate UI to itself:++- :func:`rehydrate_repo` — the shared read half: rehydrate the graph + git from+ SQL (no re-resolve, no re-blame), re-parse for ASTs + source bytes off the+ event loop, load the persisted page records, the KG artifact, and the+ file -> container-page dependency map. Returns everything scope resolution and+ generation need.+- :func:`execute_scoped_generation` — the shared write half: run generation over+ a resolved :class:`~repowise.core.generation.scope.ScopePlan`, persist the+ pages, decay the stale dependents, and heal related pages.++Scope resolution itself (intent/ranked -> ``ScopePlan``) lives in+:mod:`repowise.core.generation.scope`; a caller resolves it between these two+calls so it can gate on the estimate first. Nothing here imports CLI or server+code, so hosted reuses it as-is.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import structlog++from repowise.core.generation.page_selection import PageRecord+from repowise.core.generation.scope import (+ PageDependencies,+ build_dependencies,+ load_page_records,+)++logger = structlog.get_logger(__name__)+++@dataclass+class RehydratedRepo:+ """The rehydrated, re-parsed view a scoped generation runs against.++ Everything downstream (scope resolution, ranked seeds, generation, backlink+ heal) reads from this, so it is built once per run.+ """++ graph_builder: Any+ git_meta_map: dict[str, dict]+ parsed_files: list[Any]+ source_map: dict[str, bytes]+ repo_structure: Any+ records: list[PageRecord]+ kg_ctx: Any+ deps: PageDependencies+ repo_name: str+++@dataclass+class ScopedGenerationResult:+ """What one scoped generation produced, for the caller's report + state."""++ generated_pages: list[Any]+ marked_stale: int+++def load_kg_context(repo_path: Path) -> Any:+ """Load the persisted KG artifact for layer membership (None-safe)."""+ from repowise.core.generation.kg_context import KnowledgeGraphContext++ kg_path = repo_path / ".repowise" / "knowledge-graph.json"+ if kg_path.exists():+ return KnowledgeGraphContext(kg_path)+ return KnowledgeGraphContext(None)+++async def _load_page_rows(session: Any, repo_id: str) -> list[Any]:+ """Every non-tombstoned persisted page, lightweight columns only.++ ``load_page_records`` reads just id/type/target/provider/metadata/freshness,+ so ``load_only`` keeps the (potentially very large) ``content`` Text column+ out of this whole-wiki scan.+ """+ from sqlalchemy import select+ from sqlalchemy.orm import load_only++ from repowise.core.persistence.models import Page++ result = await session.execute(+ select(Page)+ .options(+ load_only(+ Page.id,+ Page.page_type,+ Page.target_path,+ Page.provider_name,+ Page.metadata_json,+ Page.freshness_status,+ )+ )+ .where(+ Page.repository_id == repo_id,+ Page.freshness_status != "tombstone",+ )+ )+ return list(result.scalars())+++async def rehydrate_repo(+ session_factory: Any,+ repo_id: str,+ repo_path: Path,+ *,+ generation_config: Any,+ exclude_patterns: list[str],+ include_submodules: bool = False,+ include_nested_repos: bool = False,+) -> RehydratedRepo | None:+ """Rehydrate the graph + git and re-parse, ready to resolve scope + generate.++ Returns ``None`` when the repo has no persisted wiki pages yet (nothing to+ scope a generation against). The re-parse runs off the event loop so an async+ server caller does not block its loop on the tree-sitter pass.+ """+ from repowise.core.persistence import get_session+ from repowise.core.pipeline import rehydrate_graph_builder, reparse_repo+ from repowise.core.pipeline.resume.rehydrate import rehydrate_git_meta_map++ async with get_session(session_factory) as session:+ graph_builder = await rehydrate_graph_builder(session, repo_id, repo_path)+ git_meta_map = await rehydrate_git_meta_map(session, repo_id)+ records = load_page_records(await _load_page_rows(session, repo_id))++ if not records:+ return None++ parsed_files, source_map, repo_structure = await asyncio.to_thread(+ reparse_repo,+ repo_path,+ exclude_patterns,+ include_submodules=include_submodules,+ include_nested_repos=include_nested_repos,+ )++ repo_name = repo_path.name+ kg_ctx = load_kg_context(repo_path)+ # build_dependencies runs select_pages, which forces pagerank / betweenness /+ # community detection on the rehydrated graph — seconds of pure CPU on a large+ # repo. Offload it so an async server caller (e.g. the estimate endpoint) does+ # not stall its event loop. The metrics memoize on the builder, so the later+ # generation pass reuses them.+ deps = await asyncio.to_thread(+ build_dependencies,+ parsed_files=parsed_files,+ graph_builder=graph_builder,+ config=generation_config,+ kg_ctx=kg_ctx,+ records=records,+ repo_name=repo_name,+ )+ return RehydratedRepo(+ graph_builder=graph_builder,+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ source_map=source_map,+ repo_structure=repo_structure,+ records=records,+ kg_ctx=kg_ctx,+ deps=deps,+ repo_name=repo_name,+ )+++async def execute_scoped_generation(+ *,+ session_factory: Any,+ repo_id: str,+ repo_path: Path,+ rehydrated: RehydratedRepo,+ plan: Any,+ provider: Any,+ generation_config: Any,+ embedder: Any | None = None,+ vector_store: Any | None = None,+ fts: Any | None = None,+ progress: Any | None = None,+ cost_tracker: Any | None = None,+ concurrency: int = 12,+) -> ScopedGenerationResult:+ """Generate the plan's pages, persist them, decay dependents, heal backlinks.++ Injected, UI-free, and DB-agnostic: the caller supplies the session factory,+ provider, and optional embedder / vector store / FTS / progress / cost+ tracker. ``plan`` is a resolved+ :class:`~repowise.core.generation.scope.ScopePlan`.+ """+ from repowise.core.persistence import get_session, upsert_pages_from_generated+ from repowise.core.persistence.crud import backfill_related_pages+ from repowise.core.pipeline import run_generation+ from repowise.core.pipeline.persist import mark_page_ids_stale++ # Bill this run's LLM calls to the caller's tracker. run_generation reads the+ # passed tracker; some providers additionally consult ``_cost_tracker``.+ if cost_tracker is not None:+ provider._cost_tracker = cost_tracker++ generated_pages = await run_generation(+ repo_path=repo_path,+ parsed_files=rehydrated.parsed_files,+ source_map=rehydrated.source_map,+ graph_builder=rehydrated.graph_builder,+ repo_structure=rehydrated.repo_structure,+ git_meta_map=rehydrated.git_meta_map,+ llm_client=provider,+ embedder=embedder,+ vector_store=vector_store,+ concurrency=concurrency,+ progress=progress,+ cost_tracker=cost_tracker,+ generation_config=generation_config,+ only_page_ids=plan.generate_ids,+ )+ if cost_tracker is not None:+ await cost_tracker.flush()++ marked_stale = 0+ async with get_session(session_factory) as session:+ await upsert_pages_from_generated(session, generated_pages, repo_id)+ # Dependents this run did not regenerate go stale, not wrong.+ marked_stale = await mark_page_ids_stale(session, repo_id, plan.stale_ids)+ # Heal backlinks + related-pages across the whole wiki, LLM-free. The+ # pages this run just wrote already carry fresh metadata, so skip them.+ # O(total pages), same as the incremental-update path's heal; a narrow+ # scope on a huge wiki pays for the whole table. Upgrade path if that+ # ever bites: scope the heal to the regenerated pages' import+ # neighborhood. Kept whole-wiki to match the update flow and because it+ # is LLM-free (cheap next to the generation it follows).+ try:+ from repowise.core.generation.related_pages import file_import_edges++ await backfill_related_pages(+ session,+ repo_id,+ import_edges=file_import_edges(rehydrated.graph_builder),+ git_meta_map=rehydrated.git_meta_map,+ pagerank=rehydrated.graph_builder.pagerank(),+ skip_page_ids={p.page_id for p in generated_pages},+ )+ except Exception as exc:+ logger.debug("related_pages_backfill_skipped", error=str(exc))++ if fts is not None:+ try:+ for page in generated_pages:+ await fts.index(page.page_id, page.title, page.content)+ except Exception as exc:+ logger.debug("fts_index_skipped", error=str(exc))++ return ScopedGenerationResult(+ generated_pages=generated_pages,+ marked_stale=marked_stale,+ )