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(pipeline): split incremental.py into an incremental/ package (#4004)
Raghav Chamadiyab1e0c0f5852a
diff --git a/docs/architecture/dead-code.md b/docs/architecture/dead-code.mdindex 13d743d3c..bf2277764 100644--- a/docs/architecture/dead-code.md+++ b/docs/architecture/dead-code.md@@ -34,7 +34,7 @@ a path says otherwise.Related: `analysis/finding_registry.py` decides which finding kinds a defaultsurface shows (`unused_internal` is `hidden`). Storage and triage live in`persistence/crud/analysis/dead_code.py`. The analyzer runs from-`pipeline/phases/analysis.py` (init), `pipeline/incremental.py` (update), and+`pipeline/phases/analysis.py` (init), `pipeline/incremental/analysis.py` (update), andthe CLI's live path in `cli/commands/dead_code_cmd.py`.## Flowdiff --git a/packages/core/src/repowise/core/ingestion/source_text.py b/packages/core/src/repowise/core/ingestion/source_text.pyindex 13406791a..00d65e6ec 100644--- a/packages/core/src/repowise/core/ingestion/source_text.py+++ b/packages/core/src/repowise/core/ingestion/source_text.py@@ -20,7 +20,7 @@ at each site:replaces. :func:`decode_source` normalises, so a map hit and a disk fallbackproduce the same string for the same file.-The fallback is not optional. ``pipeline/incremental.py`` fills the map only+The fallback is not optional. ``pipeline/incremental/graph.py`` fills the map onlywhen its caller asks for sources, so it can be partial or absent entirely."""diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pydeleted file mode 100644index 3db852344..000000000--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ /dev/null@@ -1,2451 +0,0 @@-"""Incremental (changed-files) index refresh.--The orchestration that `repowise update` runs for an already-indexed repo:-re-ingest the graph (parse-cache backed), re-index git metadata for the-changed files only, run partial health/dead-code analysis, and upsert the-results — without the full pipeline's delete-then-insert persistence or LLM-generation.--Extracted from the CLI update command so workspace updates can route-already-indexed member repos through the same incremental path instead of-re-running the full init pipeline per repo. The CLI keeps thin wrappers-that delegate here.--Progress/diagnostic messages go through an optional ``log`` callback (the-CLI passes ``console.print``; messages use rich markup). When ``log`` is-omitted the messages are dropped — every one of them annotates a-best-effort step that already degrades gracefully.-"""--from __future__ import annotations--import asyncio-from collections.abc import Callable, Iterable-from dataclasses import dataclass-from functools import partial-from pathlib import Path-from typing import Any--import structlog--from repowise.core.pipeline.phase_timing import PhaseTimings, timed--logger = structlog.get_logger(__name__)--LogFn = Callable[[str], None]---def _noop_log(message: str) -> None: # pragma: no cover - trivial- return None---def build_filtered_changed_paths(file_diffs: list, exclude_patterns: list[str]) -> list[str]:- """Extract paths from file_diffs, filtering out excluded patterns."""- paths = [fd.path for fd in file_diffs]- if not exclude_patterns:- return paths- import pathspec-- spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)- return [p for p in paths if not spec.match_file(p)]---def _record_structural_episodes(repo_path: Any, traverser: Any) -> None:- """Best-effort structural episodes from the walk, without the formatter check."""- try:- from repowise.core.precedent.structural import record_structural_episodes-- record_structural_episodes(repo_path, traverser, allow_formatter_check=False)- except Exception:- pass---def _parse_misses(- cached_hits: dict[int, Any],- to_parse: list,- parse_cache: Any,- timings: PhaseTimings | None,-) -> dict[int, Any]:- """Parse the parse-cache misses and merge them over the cached hits by index."""- from repowise.core.ingestion import ASTParser- from repowise.core.pipeline.phases.ingestion import _cache_parsed-- parser: Any = None # constructed lazily — every-file-cached updates skip query compilation- merged: dict[int, Any] = dict(cached_hits)- with timed(timings, "rebuild.parse"):- for idx, (fi, source), content_hash in to_parse:- try:- if parser is None:- parser = ASTParser()- parsed = parser.parse_file(fi, source)- except Exception:- continue- merged[idx] = parsed- if content_hash:- _cache_parsed(parse_cache, parsed, content_hash)- return merged---def _add_parsed_files(- graph_builder: Any,- fi_and_bytes: list,- merged: dict[int, Any],- collect_sources: bool,-) -> tuple[list, dict[str, bytes], int]:- """Add every parsed file to the graph, in read order.-- Returns ``(parsed_files, source_map, unparsed)``, where ``unparsed`` counts- the read files that have no parse result.- """- parsed_files: list = []- source_map: dict[str, bytes] = {}- unparsed = 0- for idx, (fi, source) in enumerate(fi_and_bytes):- parsed = merged.get(idx)- if parsed is None:- unparsed += 1- continue- parsed_files.append(parsed)- if collect_sources:- source_map[fi.path] = source- graph_builder.add_file(parsed)- return parsed_files, source_map, unparsed---def _add_synthetic_edges(- repo_path: Any,- graph_builder: Any,- file_infos: list,- source_map: dict[str, bytes],- log: LogFn,- timings: PhaseTimings | None,-) -> None:- """Add the framework-aware and dynamic-hint edges to a built graph."""- # Add framework-aware synthetic edges (conftest, Django, FastAPI, Flask).- # Best-effort, but not silent: the update path has to report the failure the- # init path reports, or an index degrades differently depending on how it- # was built and nothing says which.- try:- from repowise.core.generation.editor_files.tech_stack import detect_tech_stack-- with timed(timings, "rebuild.framework"):- tech_items = detect_tech_stack(repo_path)- fw_count = graph_builder.add_framework_edges([item.name for item in tech_items])- if fw_count:- log(f"Framework edges added: [cyan]{fw_count}[/cyan]")- except Exception as fw_exc:- logger.warning("framework_edges_failed", error=str(fw_exc))- log(- f"[yellow]Framework edge detection skipped: {fw_exc}; framework-invoked "- "symbols will have no callers in the graph and may read as dead.[/yellow]"- )-- # Add dynamic-hint edges, mirroring the init pipeline's ingestion phase.- # Without this the update-built graph was missing every dynamic edge the- # init graph had: metrics computed on update diverged from init's, and- # the first post-init update could never hit the centrality cache.- try:- from repowise.core.ingestion.dynamic_hints import HintRegistry-- with timed(timings, "rebuild.dynamic_hints"):- dynamic_edges = HintRegistry().extract_all(- Path(repo_path),- dotnet_index=graph_builder.dotnet_index,- file_paths=[fi.path for fi in file_infos],- source_map=source_map or None,- )- graph_builder.add_dynamic_edges(dynamic_edges)- if dynamic_edges:- log(f"Dynamic hint edges added: [cyan]{len(dynamic_edges)}[/cyan]")-- except Exception as exc:- logger.warning("dynamic_hints_extraction_failed", error=str(exc))- log(- f"[yellow]Dynamic hint extraction failed: {exc}. Dynamic edges"- "will be missing from this update.[/yellow]"- )---def build_repo_graph(- repo_path: Any,- exclude_patterns: list[str],- *,- collect_sources: bool = False,- include_submodules: bool = False,- include_nested_repos: bool = False,- log: LogFn | None = None,- timings: PhaseTimings | None = None,- read_only: bool = False,-) -> tuple[list, dict[str, bytes], Any, Any, int]:- """Traverse + parse the repo and build the graph (+ framework-aware edges).-- Shared by the incremental rebuild path (:func:`rebuild_graph_and_git`),- the config-triggered re-score path and the commands that analyze the- working tree live, so all of them build the same graph from the same- parser and the same synthetic edge steps.-- ``read_only`` is for those live commands: the parse cache is read but- never written, and no structural episodes or centrality cache are kept.-- Files that fail to read/parse are skipped and reported as a count rather than- swallowed silently. ``source_map`` is populated only when ``collect_sources``- is set; every path that persists the graph sets it, since the framework-edge-pass reads the sources.-- ``timings`` is the run's shared :class:`PhaseTimings` table; each step- below records into it under a ``rebuild.*`` name. ``None`` records nothing.-- Returns ``(parsed_files, source_map, graph_builder, repo_structure,- file_count)``.- """- import os- from concurrent.futures import ThreadPoolExecutor-- from repowise.core.ingestion import FileTraverser, GraphBuilder-- log = log or _noop_log-- traverser = FileTraverser(- repo_path,- extra_exclude_patterns=exclude_patterns or None,- include_submodules=include_submodules,- include_nested_repos=include_nested_repos,- )- # Parallel stat + header sniffing, mirroring the init ingestion phase.- # A serial traverse() pays per-file I/O latency sequentially; on a cold- # OS file cache that was ~50s of every PowerToys-scale update. Passing- # the file_infos into get_repo_structure also avoids its re-walk.- with timed(timings, "rebuild.traverse"):- all_paths = list(traverser._walk())- io_workers = min(32, max(4, (os.cpu_count() or 4) * 2))- with ThreadPoolExecutor(max_workers=io_workers) as io_pool:- maybe_infos = list(io_pool.map(traverser._build_file_info, all_paths))- file_infos = [fi for fi in maybe_infos if fi is not None]- repo_structure = traverser.get_repo_structure(file_infos)-- # Structural episodes, minus the formatter check: this path is the hot one- # (every update, plus the config-triggered re-score), so it derives only- # what the walk has already paid for and never spawns a subprocess.- if not read_only:- _record_structural_episodes(repo_path, traverser)-- # Thread-pool source reads + content-hash parse cache split, shared with- # the init parse phase: only changed files need a tree-sitter parse.- # Cache failures degrade to all-miss (full parse), as before.- from repowise.core.pipeline.phases.ingestion import (- _read_sources,- _split_cached,- )- from repowise.core.workspace.update import get_head_commit-- with timed(timings, "rebuild.read"):- fi_and_bytes = _read_sources(file_infos, None)- parse_cache, cached_hits, to_parse = _split_cached(Path(repo_path), fi_and_bytes, None)- if read_only:- parse_cache = None # hits above still count; misses are not stored-- graph_builder = GraphBuilder(- repo_path,- exclude_patterns=exclude_patterns,- centrality_cache_dir=None if read_only else Path(repo_path) / ".repowise",- head_commit=get_head_commit(Path(repo_path)),- include_submodules=include_submodules,- include_nested_repos=include_nested_repos,- )- graph_builder.console_scripts = traverser.console_script_names- # Carry the walk's skip record to the dead-code analyzer. This report is- # persisted repo-wide, so an update that could not see the skipped source- # files would re-derive and write back the verdicts init had clamped.- graph_builder.traversal_stats = traverser.stats- # Reconciliation authority is the successful traversal, not the successful- # parse set. A transient read/parser failure must not make an existing- # in-scope file look deleted and prune its persisted rows.- graph_builder.traversed_file_paths = {- file_info.path for file_info in file_infos- }-- # Parse the misses in process and serially: on the update path they are- # change-sized. (Ceiling: a wiped/stale cache re-parses everything on one- # core; routing large miss counts through init's process pool would lift- # it, at the cost of Windows spawn overhead on every routine update.)- merged = _parse_misses(cached_hits, to_parse, parse_cache, timings)-- skipped = len(file_infos) - len(fi_and_bytes) # unreadable files- # Opened here and closed after build(): graph construction is the add_file- # loop plus the resolver, and the tsconfig wiring sits between them.- if timings is not None:- timings.start("rebuild.graph")- parsed_files, source_map, unparsed = _add_parsed_files(- graph_builder, fi_and_bytes, merged, collect_sources- )- skipped += unparsed-- # TS/JS path aliases (``@/components/...``) resolve only when the- # tsconfig resolver is attached before build(); without it the alias- # targets read as external nodes and every aliased file looks- # unreachable to the dead-code analyzer (#648 — this rebuild path was- # missed when the CLI commands were wired).- from repowise.core.ingestion import wire_tsconfig_resolver-- wire_tsconfig_resolver(- graph_builder,- repo_path,- include_submodules=include_submodules,- include_nested_repos=include_nested_repos,- )- graph_builder.set_source_map(source_map)- graph_builder.set_pytest_roots(traverser.pytest_roots)- graph_builder.build()- if timings is not None:- timings.stop("rebuild.graph")- if parse_cache is not None:- with timed(timings, "rebuild.cache_save"):- parse_cache.save()-- if skipped:- log(f"[yellow]Skipped {skipped} file(s) that failed to parse.[/yellow]")-- _add_synthetic_edges(repo_path, graph_builder, file_infos, source_map, log, timings)-- return parsed_files, source_map, graph_builder, repo_structure, len(file_infos)---async def rebuild_graph_and_git(- repo_path: Any,- file_diffs: list,- cfg: dict,- exclude_patterns: list[str],- *,- git_tier: str | None = None,- include_submodules: bool = False,- include_nested_repos: bool = False,- idle_decay_sink: dict[str, dict] | None = None,- force_full_git: bool = False,- git_summary_sink: list[Any] | None = None,- log: LogFn | None = None,- timings: PhaseTimings | None = None,-) -> tuple[list, dict[str, bytes], Any, Any, int, dict[str, dict]]:- """Re-traverse + parse the repo, rebuild the graph (+ framework edges), and- re-index git metadata for the changed files.-- ``timings`` records the whole step as ``rebuild`` plus one ``rebuild.*``- row per sub-step, so a slow update names the stage that made it slow.-- ``idle_decay_sink``, when provided, is filled with a decay-only partial- metadata row for every idle (unchanged) file whose time-decayed history- fields the anchor advance moved (issue #728). These rows are for the git- persist step only — they are deliberately kept out of the returned- ``git_meta_map`` so the partial health analysis (whose repo-wide aggregates- read every entry) is unaffected.-- ``git_tier`` is the persisted ``state.json:git_tier`` value: a fast-mode- (ESSENTIAL) repo must not pay per-file blame on every update for signals- its index never had. Unknown/missing values fall back to FULL, matching- the historical behavior for legacy state files.-- ``include_submodules`` / ``include_nested_repos`` are likewise read from- state.json: a repo indexed with ``init --include-submodules`` must not- silently drop its submodule files on every incremental update. Missing- keys fall back to False (legacy behavior).-- ``force_full_git`` is reserved for changes to Git-history/traversal- configuration. Those settings invalidate every per-file row, not merely- files in the commit diff. The optional sink carries the resulting summary- to persistence so per-commit/fix-event rows can be replaced from the same- walk.-- Returns ``(parsed_files, source_map, graph_builder, repo_structure,- file_count, git_meta_map)``.- """- log = log or _noop_log- if timings is not None:- timings.start("rebuild")-- # Full re-ingest for graph (needed for cascade analysis)- parsed_files, source_map, graph_builder, repo_structure, file_count = build_repo_graph(- repo_path,- exclude_patterns,- collect_sources=True,- include_submodules=include_submodules,- include_nested_repos=include_nested_repos,- log=log,- timings=timings,- )-- # Re-index git metadata for changed files- git_meta_map: dict[str, dict] = {}- if timings is not None:- timings.start("rebuild.git")- try:- from repowise.core.ingestion.git_indexer import GitIndexer- from repowise.core.ingestion.git_indexer.tiers import GitIndexTier- from repowise.core.pipeline.phases.git import label_co_change_structure-- try:- tier = GitIndexTier(git_tier) if git_tier else GitIndexTier.FULL- except ValueError:- tier = GitIndexTier.FULL- _commit_limit = cfg.get("commit_limit")- _follow_renames = cfg.get("follow_renames", False)- git_indexer = GitIndexer(- repo_path,- commit_limit=_commit_limit,- follow_renames=_follow_renames,- exclude_patterns=exclude_patterns or None,- tier=tier,- )- if force_full_git:- summary, updated_meta = await git_indexer.index_repo(repo_path.name, on_warning=log)- if git_summary_sink is not None:- git_summary_sink.append(summary)- git_meta_map = {m["file_path"]: m for m in updated_meta}- label_co_change_structure(graph_builder, git_meta_map)- graph_builder.update_co_change_edges(git_meta_map)- else:- changed_paths = build_filtered_changed_paths(file_diffs, exclude_patterns)- # The full tracked-file set lets the indexer re-run the repo-wide- # co-change walk so partners aren't wiped to "[]" for changed files.- # The sink captures that walk's FULL per-file partner map: the graph- # was just rebuilt from scratch, so co_changes edges must be re-added- # for every file (not only the changed ones) or the update graph- # diverges from the init graph and the centrality cache can't hit.- co_change_full: dict[str, list[dict]] = {}- updated_meta = await git_indexer.index_changed_files(- changed_paths,- all_files=set(source_map.keys()),- co_change_sink=co_change_full,- idle_decay_sink=idle_decay_sink,- on_warning=log,- timings=timings,- )- git_meta_map = {m["file_path"]: m for m in updated_meta}- label_co_change_structure(graph_builder, git_meta_map)- if idle_decay_sink:- # Idle rows carry the same column and are persisted on their own- # path, having been serialized before the graph existed.- label_co_change_structure(graph_builder, idle_decay_sink)- if co_change_full:- graph_builder.update_co_change_edges(- {- fp: {"co_change_partners_json": partners}- for fp, partners in co_change_full.items()- }- )- else:- graph_builder.update_co_change_edges(git_meta_map)- except Exception as exc:- log(f"[yellow]Git re-index skipped: {exc}[/yellow]")- if force_full_git:- raise- finally:- if timings is not None:- timings.stop("rebuild.git")-- # Pre-compute centrality/community metrics with the init path's fan-out- # parallelism. Without this, persist_graph_nodes computes the same- # metrics lazily one-by-one. Runs after the co-change edge refresh so- # the cached subgraphs reflect the final structure. Best-effort: every- # metric still falls back to lazy computation.- try:- with timed(timings, "rebuild.metrics"):- await graph_builder.compute_metrics_parallel()- except Exception as exc:- log(f"[yellow]Metric pre-computation skipped: {exc}[/yellow]")-- if timings is not None:- timings.stop("rebuild")- return parsed_files, source_map, graph_builder, repo_structure, file_count, git_meta_map---async def load_stored_git_meta(- repo_path: Any, *, log: LogFn | None = None-) -> dict[str, dict] | None:- """Read the persisted per-file git fields the dead-code analyzer scores on.-- Returns ``None`` when the store could not be read, and a mapping (possibly- an empty one) when it could. The caller has to tell those apart: an empty- mapping is a repository whose ``git_metadata`` genuinely holds nothing,- which scores exactly the way a full index would score it, whereas a failed- read means this run knows less than a full index does and must not- overwrite what a full index wrote.-- Not every indexed file has a row even on a healthy repository — ``git- metadata`` covers what ``index_repo`` produced, which excludes skipped- paths — so a *missing file* is not evidence of a failure and a coverage- count cannot stand in for one.- """- log = log or _noop_log- # Never create the store as a side effect of reading it. A repo whose- # wiki.db was deleted to force a rebuild would otherwise be handed an- # empty one here, and an empty database reads as "indexed" downstream.- # Same guard, and the same reason, as the head-commit stamper.- if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():- log("[yellow]No store to read git metadata from; dead-code scope narrowed[/yellow]")- return None- try:- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_dead_code_git_fields,- get_session,- )- from repowise.core.persistence.crud import get_repository_by_path- from repowise.core.persistence.database import resolve_db_url-- engine = create_engine(resolve_db_url(repo_path))- try:- async with get_session(create_session_factory(engine)) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo is None:- # The persist path resolves the repository with an upsert,- # so a miss here means this run would be writing against a- # row that does not exist yet. Unknown, not empty.- log(- f"[yellow]No stored repository for {repo_path}; "- "dead-code scope narrowed[/yellow]"- )- return None- return await get_dead_code_git_fields(session, repo.id)- finally:- await engine.dispose()- except Exception as exc:- log(f"[yellow]Stored git metadata unavailable for dead-code scoring: {exc}[/yellow]")- return None---async def load_stored_performance_callers(- repo_path: Any,- changed_paths: set[str],- *,- log: LogFn | None = None,-) -> set[str] | None:- """Load callers whose persisted performance paths touched changed files.-- The current graph cannot retain an edge to a deleted or renamed symbol.- One bounded store read supplies that old-side reverse evidence so partial- analysis can remove stale caller findings. ``None`` means the store was- unavailable and therefore must not widen authoritative persistence scope.- """- log = log or _noop_log- if not changed_paths:- return set()- if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():- return None- try:- import json-- from sqlalchemy import select-- from repowise.core.persistence import create_engine, get_session- from repowise.core.persistence.crud import get_repository_by_path- from repowise.core.persistence.database import (- create_session_factory,- resolve_db_url,- )- from repowise.core.persistence.models import HealthFinding-- engine = create_engine(resolve_db_url(repo_path))- try:- async with get_session(create_session_factory(engine)) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo is None:- return None- rows = (- await session.execute(- select(HealthFinding.file_path, HealthFinding.details_json).where(- HealthFinding.repository_id == repo.id,- HealthFinding.status == "open",- HealthFinding.dimension == "performance",- )- )- ).all()- finally:- await engine.dispose()- callers: set[str] = set()- for file_path, details_json in rows:- try:- path = json.loads(details_json or "{}").get("path", ())- except (TypeError, ValueError, AttributeError):- continue- if any(- isinstance(node, str) and node.split("::", 1)[0] in changed_paths for node in path- ):- callers.add(file_path)- return callers- except Exception as exc:- log(f"[yellow]Stored performance callers unavailable: {exc}[/yellow]")- return None---async def load_stored_function_mod_p80(repo_path: Any, *, log: LogFn | None = None) -> int | None:- """Load the repo-wide p80 of per-function modification counts.-- Computed from the persisted ``git_function_blame`` rollup, which a FULL- index writes for every modified function. The incremental health pass- reuses this value so the Function Hotspot gate is scored against the- full repo rather than the churn-heavy changed-files subset (issue- #1484) — a hotspot verdict then no longer flips when a full ``init``- is later replaced by an incremental ``update``.-- Returns ``None`` when the store is unreadable, the repository row is- missing, or no blame rollup has been persisted (ESSENTIAL tier, or a- repo that has never been fully indexed) — callers fall back to the- walked-set computation in that case.- """- log = log or _noop_log- if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():- return None- try:- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- )- from repowise.core.persistence.crud import (- get_git_function_mod_counts,- get_repository_by_path,- )- from repowise.core.persistence.database import resolve_db_url-- engine = create_engine(resolve_db_url(repo_path))- try:- async with get_session(create_session_factory(engine)) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo is None:- return None- # What the last full index measured over every walked function.- stored = getattr(repo, "function_mod_p80", None)- if stored:- return int(stored)- counts = await get_git_function_mod_counts(session, repo.id)- finally:- await engine.dispose()- if not counts:- return None- # Fallback for a store whose last full index predates the column above.- # The rollup is keyed by ``{path}::{name}``, so a file's same-named- # functions collapse to one row and this percentile is taken over a- # population missing those samples. Closer than the changed-files- # subset, still not the number a full index computes.- from repowise.core.analysis.health.engine import _percentile_p80-- return _percentile_p80(counts)- except Exception as exc:- log(f"[yellow]Stored function-mod percentile unavailable: {exc}[/yellow]")- return None---async def load_stored_coverage_map(repo_path: Any, *, log: LogFn | None = None) -> dict[str, dict]:- """Load the persisted coverage map for health scoring on an incremental run.-- The incremental health pass re-scores changed files only, but if it builds- its ``HealthAnalyzer`` without a ``coverage_map`` every re-analyzed file is- scored as if no coverage had ever been ingested — and the partial-health- writer then overwrites the stored ``line_coverage_pct`` with ``None`` for- exactly the files that just changed, eroding coverage one file per update- (issue #1739).-- Returns ``{path: coverage-dict}`` by reloading the persisted ``CoverageFile``- rows, mirroring ``_coverage_for_rescore`` in the CLI update path. Empty dict- when no coverage is stored, the store is unreadable, or the repository row- is missing — the analyzer then scores without coverage, matching the- established safe default.- """- log = log or _noop_log-- if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():- return {}- try:- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- )- from repowise.core.persistence.crud import (- get_repository_by_path,- load_coverage_map,- )- from repowise.core.persistence.database import resolve_db_url-- engine = create_engine(resolve_db_url(repo_path))- try:- async with get_session(create_session_factory(engine)) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo is None:- return {}- coverage_map = await load_coverage_map(session, repo.id)- finally:- await engine.dispose()- return coverage_map- except Exception as exc:- log(f"[yellow]Stored coverage unavailable: {exc}[/yellow]")- return {}---def _performance_only_config(config: dict | None, performance_only: set[str]) -> dict | None:- """Disable every non-performance detector on the closure's files.-- The closure adds files whose call paths reach a changed sink. Only their- performance findings survive the filter below; every other detector's- output for them is computed and discarded, and on a central helper the- closure runs to hundreds of files. The walk still covers them, because the- performance detectors read it.- """- if not performance_only:- return config- from repowise.core.analysis.health.biomarkers import registered_biomarkers- from repowise.core.analysis.health.scoring import dimensions_for-- non_performance = {- b.name for b in registered_biomarkers() if "performance" not in dimensions_for(b.name)- }- out = dict(config or {})- per_file = {k: set(v) for k, v in (out.get("per_file_disabled") or {}).items()}- for path in performance_only:- per_file[path] = per_file.get(path, set()) | non_performance- out["per_file_disabled"] = per_file- return out---def run_partial_analysis(- repo_path: Any,- graph_builder: Any,- git_meta_map: dict,- parsed_files: list,- file_diffs: list,- *,- source_map: dict[str, bytes] | None = None,- stored_git_meta: dict[str, dict] | None = None,- stored_performance_callers: set[str] | None = None,- repo_function_mod_p80: int | None = None,- coverage_map: dict[str, dict] | None = None,- log: LogFn | None = None,- timings: PhaseTimings | None = None,-) -> tuple[Any, Any]:- """Run partial code-health + repo-wide dead-code analysis.-- Returns ``(partial_health_report, dead_code_report)`` — either may be- ``None`` if its analysis failed (both are best-effort).-- *source_map* is ingestion's ``{path: raw bytes}`` for this rebuild; the- dead-code prepasses read it instead of re-reading the repo from disk.-- *stored_git_meta* is the persisted per-file git metadata. ``git_meta_map`` holds this run's freshly- indexed rows, which on an incremental update means the changed files and- nothing else; every other file would otherwise be scored against an empty- dict and land on the ``commit_count_90d == 0`` rung of the confidence- ladder at 0.7 / ``safe_to_delete=True``. It is supplied whole to dead-code- and to performance ranking, but deliberately not merged into health's- general ``git_meta_map``: widening that aggregate would silently move- nonperformance scores (the same reason idle-decay rows stay out of it).-- *stored_performance_callers* is the old-side caller set recovered in one- store read. It keeps deletion and rename updates authoritative when the- rebuilt graph can no longer contain the removed execution edge.-- *repo_function_mod_p80* is the repo-wide 80th percentile of per-function- modification counts, loaded from the persisted ``git_function_blame``- rollup (see :func:`load_stored_function_mod_p80`). It is passed through to- the health analyzer so the Function Hotspot gate is scored against the full- repo instead of this run's changed-files subset (issue #1484). ``None``- makes the analyzer fall back to deriving it from the walked files.-- ``None`` means the store could not be read, which is different from an- empty mapping and narrows what the resulting report is allowed to- overwrite. See ``load_stored_git_meta``.-- ``timings`` records the two analyses as ``analysis.health`` and- ``analysis.dead_code``. Their costs move independently with the edit, so- they are never folded into one row.- """- log = log or _noop_log-- # Run partial code-health analysis up front so both the index-only- # and full paths can upsert findings/metrics for changed files only.- # The full file-list is needed because duplication is cross-file —- # but only files in ``changed_paths`` produce new findings/metrics.- partial_health_report = None- if timings is not None:- timings.start("analysis.health")- try:- # Performance is interprocedural. Recompute one bounded bidirectional- # execution closure so a changed caller can still see an unchanged sink- # and an unchanged caller can react to a changed sink. The index is- # built once; this is a multi-source walk, not one walk per finding.- from repowise.core.analysis.communities import file_community_labels- from repowise.core.analysis.execution_graph import ExecutionGraphIndex- from repowise.core.analysis.health import HealthAnalyzer- from repowise.core.analysis.health.config import HealthConfig-- _health_changed = {- fd.path for fd in file_diffs if fd.status in ("added", "modified", "renamed")- }- parsed_paths = {pf.file_info.path for pf in parsed_files}- execution_index = ExecutionGraphIndex(graph_builder.graph())- _performance_changed = execution_index.affected_files(_health_changed) & parsed_paths- if stored_performance_callers is not None:- historical_callers = stored_performance_callers & parsed_paths- _performance_changed |= (- execution_index.affected_files(historical_callers) & parsed_paths- )- _health_scope = _health_changed | _performance_changed- _health_analyzer = HealthAnalyzer(- graph_builder.graph(),- git_meta_map=git_meta_map,- parsed_files=parsed_files,- community_label_map=file_community_labels(graph_builder),- duplication_cache_dir=Path(repo_path) / ".repowise",- repo_root=repo_path,- coverage_map=coverage_map,- )- if _health_scope:- _hcfg = HealthConfig.load(repo_path)- _analyzer_config = (- _hcfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])- if _hcfg.has_overrides()- else None- )- _analyzer_config = _performance_only_config(- _analyzer_config, _performance_changed - _health_changed- )- partial_health_report = _health_analyzer.analyze(- _analyzer_config,- changed_files=_health_scope,- repo_function_mod_p80=repo_function_mod_p80,- timings=timings,- duplication_files=_health_changed,- )- # The closure exists only to refresh interprocedural performance.- # Preserve the historical changed-file scope for every other- # dimension, metric, blame row, and refactoring detector.- partial_health_report.authoritative_paths = set(_health_changed)- partial_health_report.performance_authoritative_paths = set(_performance_changed)- partial_health_report.metrics = [- metric- for metric in partial_health_report.metrics- if metric.file_path in _health_changed- ]- partial_health_report.findings = [- finding- for finding in partial_health_report.findings- if finding.file_path in _health_changed or finding.dimension == "performance"- ]- partial_health_report.refactoring_suggestions = [- suggestion- for suggestion in partial_health_report.refactoring_suggestions- if suggestion.file_path in _health_changed- or suggestion.refactoring_type == "performance_fix"- ]- partial_health_report.function_blame_rows = [- row- for row in partial_health_report.function_blame_rows- if row.get("file_path") in _health_changed- ]- log(- f"Health analysis (partial): [cyan]{len(_health_changed)} changed[/cyan], "- f"[cyan]{len(_performance_changed)} performance-affected[/cyan], "- f"[yellow]{len(partial_health_report.findings)} findings[/yellow]"- )- except Exception as exc:- log(f"[yellow]Health analysis skipped: {exc}[/yellow]")- finally:- if timings is not None:- timings.stop("analysis.health")-- # Run dead-code analysis up front so both branches can persist its- # results. Previously this sat below the ``if index_only``- # short-circuit, which left the closure's reference to- # ``dead_code_report`` unbound and crashed every ``--index-only`` run.- dead_code_report = None- if timings is not None:- timings.start("analysis.dead_code")- try:- from repowise.core.analysis.dead_code import DeadCodeAnalyzer-- # parsed_files enables the source-scan rescues (dynamic markers,- # bundler aliases, export aliases) on the update path, matching init.- #- # This run's freshly indexed rows win over the stored ones for the- # files they cover; the stored rows carry every other file, which is- # what init's analyzer had and this path did not.- _dead_code_git_meta = {**(stored_git_meta or {}), **git_meta_map}- # Files the walk dropped (size, no language spec, generated). This- # report is persisted repo-wide (see below), so without them an update- # would re-derive the verdicts init had clamped and write them back- # unclamped — the #1237 cascade would return, looking like the fix had- # regressed.- _traversal_stats = getattr(graph_builder, "traversal_stats", None)- _dead_code_analyzer = DeadCodeAnalyzer(- graph_builder.graph(),- _dead_code_git_meta,- parsed_files=graph_builder._parsed_files,- source_map=source_map,- repo_root=repo_path,- unindexed_source_files=(- _traversal_stats.unindexed_source_files() if _traversal_stats is not None else []- ),- dotnet_index=getattr(graph_builder, "dotnet_index", None),- )- # Repo-wide, and persisted repo-wide. The detectors were always- # repo-wide — the update path just discarded everything outside the- # change set before writing, which is why an unchanged file that the- # change had made dead (or brought back to life) kept its old verdict- # until someone re-indexed from scratch.- dead_code_report = _dead_code_analyzer.analyze()-- # What this report is allowed to overwrite.- #- # When the stored read succeeded, this run's git knowledge is the same- # knowledge a full index had — the stored rows ARE what the last full- # index wrote, with this run's fresher ones on top — so every file is- # scored at least as well here as it was there and the report speaks- # for the whole repository. That includes files with no git row at- # all: a full index had no row for them either and scored them the- # same way, so holding them back would protect nothing while leaving- # exactly the stale verdicts this is meant to fix. Coverage is not the- # test, and cannot be: ``git_metadata`` legitimately covers only the- # files ``index_repo`` produced.- #- # When the read FAILED, this run knows strictly less than the index it- # would be overwriting: every file outside the change set would be- # scored with no git row, which the analyzer holds below the- # deletion-ready threshold, so a verdict a full index scored at 1.0- # would be written back as an unscored 0.5. So it speaks only for the- # files it re-indexed this run, which is the behavior this path had- # before it was widened.- dead_code_report.authoritative_paths = (- None if stored_git_meta is not None else frozenset(git_meta_map)- )- if dead_code_report.authoritative_paths is not None:- log(- "[yellow]Dead-code findings limited to "- f"{len(dead_code_report.authoritative_paths)} re-indexed files; "- "the rest keep their previous verdict[/yellow]"- )- if dead_code_report.total_findings:- log(- f"Dead code findings: [yellow]{dead_code_report.total_findings}[/yellow]"- " repo-wide, every kind"- )- except Exception as exc:- log(f"[yellow]Dead code analysis skipped: {exc}[/yellow]")- finally:- if timings is not None:- timings.stop("analysis.dead_code")-- return partial_health_report, dead_code_report---@dataclass(frozen=True)-class DocDriftUpdate:- """What an update tells the drift pass about the change it is applying."""-- base_ref: str | None = None- """The commit the update diffs from, to the working tree."""- changed_paths: tuple[str, ...] = ()- """Every path the update adds, edits, deletes or renames (both sides)."""- symbol_names: frozenset[str] | None = None- """The index's symbol names; ``None`` reads them from the graph."""-- @classmethod- def from_file_diffs(cls, base_ref: str | None, file_diffs: Iterable[Any]) -> DocDriftUpdate:- paths = tuple(p for fd in file_diffs for p in (fd.path, fd.old_path) if p)- return cls(base_ref=base_ref, changed_paths=paths)---def run_doc_drift_partial(- graph_builder: Any,- source_map: dict[str, bytes] | None,- *,- repo_path: Any | None = None,- log: LogFn | None = None,- timings: PhaseTimings | None = None,- update: DocDriftUpdate | None = None,-) -> Any | None:- """Re-check the repository's own markdown on the incremental path.-- Its own function rather than a third member of- :func:`run_partial_analysis`'s tuple, mirroring the full path where drift is- its own phase. Returns ``None`` when the pass could not run, which the- caller must treat as "write nothing".-- The cheap kinds are re-derived for every document. Symbol references are- re-resolved only where *update* could have changed them (see- :class:`~repowise.core.analysis.doc_drift.symbols.SymbolRecheck`); the rest- carry forward in the store.- """- log = log or _noop_log- if not source_map:- return None-- with timed(timings, "analysis.doc_drift"):- try:- from repowise.core.analysis.doc_drift import DocDriftAnalyzer-- # The traversal, not the parse set. ``source_map`` omits files that- # failed to read or parse, and resolving against that narrower tree- # turns a live path into a fabricated "missing" finding.- tracked_paths = getattr(graph_builder, "traversed_file_paths", None)- if not tracked_paths:- return None-- root = Path(repo_path) if repo_path else None- report = DocDriftAnalyzer(- source_map=source_map,- tracked_paths=tracked_paths,- repo_root=root,- symbols=_drift_symbol_options(graph_builder, root, update or DocDriftUpdate()),- ).analyze()- report.authoritative_paths = report.documents- if report.total_findings:- log(f"Doc drift findings: [yellow]{report.total_findings}[/yellow]")- return report- except Exception as exc:- log(f"[yellow]Doc drift analysis skipped: {exc}[/yellow]")- return None---def _drift_symbol_options(graph_builder: Any, root: Path | None, update: DocDriftUpdate) -> Any:- """The drift pass's symbol options for *update*; ``None`` without a working tree."""- from repowise.core.analysis.doc_drift.symbols import (- SymbolOptions,- graph_symbol_names,- symbol_recheck,- )-- if root is None:- return None- names = update.symbol_names- if names is None:- names = graph_symbol_names(graph_builder.graph())- return SymbolOptions(names, symbol_recheck(root, update.base_ref, update.changed_paths))---async def refresh_knowledge_graph(- repo_path: Any,- parsed_files: list,- graph_builder: Any,- repo_structure: Any,- git_meta_map: dict,- dead_code_report: Any,- *,- prior_fingerprint: str | None,- log: LogFn | None = None,-) -> Any | None:- """Rebuild the KG skeleton + curation when the graph shape changed.-- The knowledge graph (layers, tour, entry points, curated node meta) was- historically rebuilt only by the full init pipeline, so every incremental- ``repowise update`` carried the init-time KG forward verbatim and agents- read a stale orientation snapshot (#669). This reruns the deterministic- skeleton + curation passes against the freshly rebuilt graph, then carries- forward the prior artifact's LLM-enriched layer names and node summaries- by stable id — so index-only updates stay LLM-free without regressing- enrichment. LLM re-enrichment stays with the caller (docs mode only).-- Returns the refreshed result, or ``None`` when the graph fingerprint is- unchanged (the persisted artifact is already current) or the rebuild- failed (keep the prior artifact rather than export a broken one).- """- log = log or _noop_log- try:- from repowise.core.analysis.knowledge_graph import (- KnowledgeGraphResult,- build_knowledge_graph_skeleton,- compute_kg_fingerprint,- should_skip_kg_rebuild,- )-- kg_json_path = Path(repo_path) / ".repowise" / "knowledge-graph.json"- new_fingerprint = compute_kg_fingerprint(graph_builder)- if should_skip_kg_rebuild(prior_fingerprint, new_fingerprint, kg_json_path):- return None-- tech_stack: list[dict] = []- try:- from repowise.core.generation.editor_files.tech_stack import detect_tech_stack-- tech_stack = [- {"name": t.name, "version": t.version, "category": t.category}- for t in detect_tech_stack(repo_path)- ]- except Exception:- pass # tech stack is contextual metadata, not structural-- prior_kg = KnowledgeGraphResult.from_file(kg_json_path)-- kg = build_knowledge_graph_skeleton(- parsed_files=parsed_files,- graph_builder=graph_builder,- repo_structure=repo_structure,- tech_stack=tech_stack,- external_systems=[],- git_meta_map=git_meta_map,- dead_code_report=dead_code_report,- repo_path=Path(repo_path),- )- kg.fingerprint = new_fingerprint-- from repowise.core.analysis.kg_curation import (- apply_summary_floor,- curate_knowledge_graph,- curation_enabled,- )-- kg = curate_knowledge_graph(- kg,- parsed_files=parsed_files,- graph_builder=graph_builder,- repo_structure=repo_structure,- community_info=graph_builder.community_info(),- git_meta_map=git_meta_map,- enabled=curation_enabled(),- # Floor after the prior-artifact carry-forward below so carried- # page-derived summaries win over the deterministic floor.- defer_summary_floor=True,- )-- if prior_kg is not None:- _carry_forward_kg_enrichment(kg, prior_kg)-- # Summaries degrade to empty on failure, same as the init-path seam.- import contextlib-- with contextlib.suppress(Exception):- apply_summary_floor(kg, parsed_files)-- log(- f"Knowledge graph refreshed: [cyan]{len(kg.layers)}[/cyan] layers, "- f"[cyan]{len(kg.tour)}[/cyan] tour steps"- )- return kg- except Exception as exc:- log(f"[yellow]Knowledge-graph refresh skipped: {exc}[/yellow]")- return None---def _carry_forward_kg_enrichment(kg: Any, prior_kg: Any) -> None:- """Adopt the prior artifact's LLM-enriched prose onto the rebuilt KG.-- Matching is by stable id, and only fields the deterministic passes left- empty are filled — structural changes always win over stale prose. Layer- descriptions exist only after LLM enrichment (curation names layers but- leaves descriptions empty), so a non-empty prior description is the- signal that the prior name/description pair is the enriched one.- """- prior_layers = {layer.get("id"): layer for layer in prior_kg.layers or []}- for layer in kg.layers or []:- prior = prior_layers.get(layer.get("id"))- if prior and prior.get("description") and not layer.get("description"):- layer["name"] = prior.get("name") or layer.get("name")- layer["description"] = prior["description"]-- prior_summaries = {n.get("id"): n["summary"] for n in prior_kg.nodes or [] if n.get("summary")}- for node in kg.nodes or []:- if not node.get("summary"):- prior_summary = prior_summaries.get(node.get("id"))- if prior_summary:- node["summary"] = prior_summary-- # With curation disabled the skeleton carries no tour and only the LLM- # path builds one — keep the prior tour rather than exporting none.- if not kg.tour and prior_kg.tour:- kg.tour = prior_kg.tour---async def refresh_unchanged_history(- session: Any, repo_id: str, repo_path: Any, *, skip_paths: set[str]-) -> int:- """Re-score the git-derived markers on files this run did not walk.-- The update refreshes git metadata for the whole repository, so a file the- change set never touched can still have moved in every way history- measures — new co-change partners, a fix that landed elsewhere in the same- commit, an owner who left. Only those markers are re-evaluated; each file- keeps the structural findings its last parse produced, so nothing here- needs the source.-- Returns the number of files rewritten. Best-effort: the update is not worth- failing over a refresh.- """- from repowise.core.analysis.health.config import HealthConfig- from repowise.core.analysis.health.history_refresh import (- REFRESHABLE_MARKERS,- active_contributors,- git_meta_rows_to_map,- refresh_history,- )- from repowise.core.persistence.crud import (- get_all_git_metadata,- get_file_language_map,- get_health_findings,- get_health_metrics,- upsert_health_findings,- upsert_health_metrics,- )- from repowise.core.pipeline.persist import _analyzed_commit-- stored = {- m.file_path: m- for m in await get_health_metrics(session, repo_id)- if m.file_path not in skip_paths- }- if not stored:- return 0- git_meta = git_meta_rows_to_map((await get_all_git_metadata(session, repo_id)).values())- if not git_meta:- return 0-- findings_by_path: dict[str, list[Any]] = {}- for finding in await get_health_findings(session, repo_id, include_withheld=True):- findings_by_path.setdefault(finding.file_path, []).append(finding)-- cfg = HealthConfig.load(repo_path)- refreshed = refresh_history(- metrics=list(stored.values()),- findings_by_path=findings_by_path,- git_meta_by_path=git_meta,- languages=await get_file_language_map(session, repo_id),- repo_active_contributors_90d=active_contributors(git_meta),- severity_overrides=cfg.severity_overrides or None,- )- if not refreshed:- return 0-- # The two writes are scoped separately on purpose. A metric row is cheap to- # rewrite and carries no identity, but rewriting findings deletes and- # re-inserts them, which means new ids and a reset ``created_at`` — so that- # only happens for a file whose history findings actually changed, not for- # every file whose stored split was merely never recorded.- commit = await _analyzed_commit(session, repo_id)- metric_writes = [- _refreshed_metric(r, stored[r.file_path], commit)- for r in refreshed- if _numbers_moved(r, stored[r.file_path])- ]- finding_writes = [- r for r in refreshed if _history_findings_moved(r, findings_by_path.get(r.file_path, []))- ]- if not metric_writes and not finding_writes:- return 0-- # One savepoint over both: a file whose findings were rewritten but whose- # score was not would report a deduction its own findings cannot account- # for, and the caller logs this step and carries on to commit the rest.- async with session.begin_nested():- if finding_writes:- await upsert_health_findings(- session,- repo_id,- [f for r in finding_writes for f in r.findings],- file_paths=[r.file_path for r in finding_writes],- )- if metric_writes:- await upsert_health_metrics(session, repo_id, metric_writes)- logger.debug(- "health_history_refreshed",- repo_id=repo_id,- metric_rows=len(metric_writes),- finding_rows=len(finding_writes),- markers=len(REFRESHABLE_MARKERS),- )- return len(finding_writes)---def _numbers_moved(refreshed: Any, stored: Any) -> bool:- """Whether the stored row's numbers differ from the re-scored ones.-- Includes a row whose split was never recorded, so the first update after- the split ships backfills it without touching any finding.- """- return (- _differs(refreshed.score, stored.score, 2)- or _differs(refreshed.structure_deduction, stored.structure_deduction, 3)- or _differs(refreshed.history_deduction, stored.history_deduction, 3)- )---def _differs(new: float | None, old: float | None, places: int) -> bool:- """``None`` is a value here: a file that is no longer scored has moved."""- if new is None or old is None:- return (new is None) != (old is None)- return round(new, places) != round(float(old), places)---def _history_findings_moved(refreshed: Any, stored_findings: list[Any]) -> bool:- """Whether the git-derived findings themselves changed.-- Compared on what a reader sees — which markers fired, where, and how- severely — so a file keeps its finding ids and their ages across an update- that re-derived the same history.- """-- def key(findings: Any) -> set:- return {- (- getattr(f, "biomarker_type", ""),- str(getattr(f, "severity", "")),- getattr(f, "function_name", None),- round(float(getattr(f, "health_impact", 0.0) or 0.0), 3),- )- for f in findings- }-- return key(refreshed.findings) != key(stored_findings)---def _refreshed_metric(refreshed: Any, stored: Any, commit: str | None) -> dict:- """The stored metric row with the rescored numbers written over it.-- A dict rather than a dataclass so the fields this pass cannot know — the- complexity and coverage columns, which need a parse — keep their stored- values instead of being reset to a default.-- ``commit`` is the one the row was rescored against: its history is read at- it, and the file is unchanged since its last parse. Keeping the old stamp- made the newest row name a commit 100 behind, which the health basis- reads. Set here, not as the writer's default, so an unreadable HEAD- clears the stamp: "not recorded" is honest and the old commit is not.- """- # A file health never walked carries no complexity figures either, which- # also clears the ones a store written before that rule kept.- walked = refreshed.score is not None- return {- "file_path": refreshed.file_path,- "analyzed_commit": commit,- "score": refreshed.score,- "max_ccn": stored.max_ccn if walked else None,- "max_nesting": stored.max_nesting if walked else None,- "nloc": stored.nloc,- "duplication_pct": stored.duplication_pct,- "has_test_file": stored.has_test_file,- "line_coverage_pct": stored.line_coverage_pct,- "branch_coverage_pct": stored.branch_coverage_pct,- "module": stored.module,- "defect_score": refreshed.defect_score,- "maintainability_score": refreshed.maintainability_score,- "performance_score": refreshed.performance_score,- "structure_deduction": refreshed.structure_deduction,- "history_deduction": refreshed.history_deduction,- "is_test": stored.is_test,- "code_origin": getattr(stored, "code_origin", None),- }---async def persist_partial_health(- session: Any, repo_id: str, report: Any, repo_path: Any = None-) -> None:- """Upsert health findings + metrics for the changed-files subset.-- Unlike ``persist_pipeline_result`` (which delete-then-inserts the- whole repo), this writer only touches rows whose ``file_path`` is in- the partial report — so unchanged files keep their existing findings- and metrics across an incremental ``repowise update``.- """- from repowise.core.persistence.crud import (- PayoffContext,- finalize_performance_opportunities,- finalize_refactoring_opportunities,- upsert_health_findings,- upsert_health_metrics,- upsert_refactoring_suggestions,- write_function_facts,- )- from repowise.core.pipeline.persist import _analyzed_commit, path_liveness-- changed_paths = sorted(- set(getattr(report, "authoritative_paths", None) or ())- or {m.file_path for m in report.metrics or []}- )- performance_paths = sorted(- set(getattr(report, "performance_authoritative_paths", None) or ()) - set(changed_paths)- )- # Nothing analysed: a deletion-only update runs no health analysis, so it- # has no role map to restamp stored roles with. Roles, like performance- # findings, refresh on the next run that analyses any file.- if not changed_paths and not performance_paths:- return- analyzed_commit = await _analyzed_commit(session, repo_id)- # One savepoint over the findings and everything derived from them. This- # writer's caller logs a failed step and carries on to commit the rest of- # the run, so without the savepoint a rebuild that failed halfway would- # leave the queue describing findings that were never stored.- async with session.begin_nested():- if changed_paths:- await upsert_health_metrics(- session,- repo_id,- report.metrics or [],- analyzed_commit=analyzed_commit,- )- await upsert_health_findings(- session, repo_id, list(report.findings or []), file_paths=changed_paths- )- if performance_paths:- await upsert_health_findings(- session,- repo_id,- list(report.findings or []),- file_paths=performance_paths,- dimension="performance",- )- # Refactoring suggestions for the changed files only (unchanged files- # keep theirs). Scoped reconciliation across the full changed-file set,- # so a file that became clean has its plans resolved rather than left- # standing, and a plan that survived the edit keeps its id.- if changed_paths:- await upsert_refactoring_suggestions(- session,- repo_id,- [- suggestion- for suggestion in (getattr(report, "refactoring_suggestions", None) or [])- if suggestion.refactoring_type != "performance_fix"- ],- file_paths=changed_paths,- # Before the facts below replace the stored ones: those are the- # measures a resolved plan was detected against.- payoff=PayoffContext(- fact_rows=getattr(report, "function_facts", None),- is_live=path_liveness(repo_path),- commit=analyzed_commit,- ),- )- # Facts for the files this run walked; roles and nearest tests for every- # stored row, written only where they moved. No rows means no graph to- # key them on: the stored ones stay. Before the finalizers, which read- # each plan's nearest tests off these rows.- fact_rows = getattr(report, "function_facts", None)- if fact_rows is not None:- await write_function_facts(- session,- repo_id,- fact_rows,- file_paths={*changed_paths, *performance_paths},- roles=getattr(report, "execution_roles", None),- tests=getattr(report, "function_tests", None),- )- # A partial run sees a subset of the findings, so the plans and the- # queue it would derive are a subset too. Both are rebuilt here instead,- # from the merged stored rows, by the same writer the full path uses.- # That is what makes the two paths agree, and it retires the file-scoped- # plan bookkeeping that used to try to reach a shared intervention from- # its callers.- await finalize_performance_opportunities(- session,- repo_id,- analyzed_commit=analyzed_commit,- plan_policy=getattr(report, "performance_plan_policy", None),- execution_roles=getattr(report, "execution_roles", None),- )- # Repository-wide, like the queue above and for the same reason: an- # opportunity folds a file's plans, and a file this run did not touch- # can still lose one when a cross-file plan elsewhere resolves.- await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)- # Per-function blame rollup for the changed files (keeps git_function_blame- # current between full indexes; FULL git tier only — empty otherwise).- fn_blame_rows = getattr(report, "function_blame_rows", None)- if fn_blame_rows:- from repowise.core.persistence.crud import upsert_git_function_blame_bulk-- await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)- # Only a full index rewrites the whole population, so rows an older version- # scored for prose or configuration go here rather than lingering in the- # average, and rows written before ``is_test`` existed get it from their- # path. Both before the refresh, which should not re-score a row that is- # about to be deleted.- from repowise.core.persistence.crud import (- backfill_is_test,- clear_unanalysed_scores,- prune_unscored_health_rows,- )-- await prune_unscored_health_rows(session, repo_id)- await clear_unanalysed_scores(session, repo_id)- await backfill_is_test(session, repo_id)- # Then the files this run did not walk, whose git-derived markers the fresh- # metadata may have moved. Before the snapshot, or the trend would describe- # the store as it stood one update ago.- if repo_path is not None:- try:- await refresh_unchanged_history(- session, repo_id, repo_path, skip_paths=set(changed_paths)- )- except Exception as exc:- # Never fails the run: the next update re-derives the whole thing- # from the stored git metadata, so nothing is stranded behind.- logger.debug("health_history_refresh_skipped", repo_id=repo_id, error=str(exc))- # The store now holds the merged repository, so the snapshot describes the- # whole of it, not this run's changed files.- from repowise.core.pipeline.persist import snapshot_health_from_store-- await snapshot_health_from_store(session, repo_id)---async def persist_incremental_commits(- session: Any, repo_id: str, repo_path: Any, *, timings: PhaseTimings | None = None-) -> None:- """Capture + upsert ``git_commits`` rows for commits new since the last index.-- Foundation 1 only populated the per-commit table on the full orchestrator- index; without this, the commits/change-risk surface goes stale between full- re-indexes. Bounds the walk to commits newer than the newest persisted- ``committed_at`` (one ``git log`` pass) and upserts (idempotent on sha).- """- from repowise.core.ingestion.git_indexer import GitIndexer- from repowise.core.persistence.crud import (- clear_attribution_if_disabled,- get_latest_commit_committed_at,- get_repository,- update_repo_git_totals,- upsert_git_commit_files_bulk,- upsert_git_commits_bulk,- )- from repowise.core.repo_config import load_repo_config-- cfg = load_repo_config(repo_path)- indexer = GitIndexer(- repo_path,- commit_limit=cfg.get("commit_limit"),- follow_renames=cfg.get("follow_renames", False),- # The fix-event capture walks the tracked-file set itself, so without- # the repo's excludes an update would store events for files a full- # index never sees, and they would never age out.- exclude_patterns=cfg.get("exclude_patterns"),- # Git episodes ride the same capture and inherit those excludes.- record_episodes=True,- )- newest = await get_latest_commit_committed_at(session, repo_id)- since_ts: int | None = None- if newest is not None:- # SQLite drops tzinfo, so a naive read must be interpreted as UTC (the- # column is stored tz-aware) rather than local time.- from datetime import UTC-- dt = newest if newest.tzinfo is not None else newest.replace(tzinfo=UTC)- since_ts = int(dt.timestamp())- with timed(timings, "persist.commits.capture"):- # One walk fills both, so they describe the same commit set.- file_rows: list[dict] = []- rows = await asyncio.to_thread(- partial(- indexer.capture_new_commit_rows,- since_ts=since_ts,- file_rows_sink=file_rows,- )- )- if rows:- await upsert_git_commits_bulk(session, repo_id, rows)- if file_rows:- await upsert_git_commit_files_bulk(session, repo_id, file_rows)- await clear_attribution_if_disabled(session, repo_id)-- # What the new commits did to health is scanned by the caller once this- # transaction commits (commit_health.refresh_commit_health_after_update):- # the scan can take minutes and must not hold the write lock.-- with timed(timings, "persist.commits.experience"):- await reconcile_commit_experience(session, repo_id, indexer)- # Fills the commit-offset column on indexes written before it existed, so a- # new capture never needs a re-index to become useful.- with timed(timings, "persist.commits.offsets"):- await reconcile_commit_offsets(session, repo_id, indexer)- with timed(timings, "persist.commits.changes"):- from repowise.core.changes.store import reconcile_categories, refresh_changes-- await refresh_changes(session, repo_id, repo_path, rebuild=False)- try:- await reconcile_categories(session, repo_id)- except Exception as exc:- logger.debug("category_reconcile_failed", error=str(exc))-- # Refresh the repo-level whole-history totals so age / commit / contributor- # counts keep growing between full re-indexes (#730). Cheap git calls, and- # cheap to run every update since they don't touch the bounded sample —- # except lifetime churn, which walks the history. Handing the capture what- # was stored last time lets it add only the range since, and it re-proves- # that range is safe to add before doing so.- prior = _churn_prior(await get_repository(session, repo_id))- with timed(timings, "persist.commits.totals"):- totals = await asyncio.to_thread(indexer.capture_repo_totals, prior)- await update_repo_git_totals(- session,- repo_id,- total_commit_count=totals.total_commit_count,- total_merge_commit_count=totals.total_merge_commit_count,- first_commit_at=totals.first_commit_at,- total_contributor_count=totals.total_contributor_count,- first_commit_author=totals.first_commit_author,- first_commit_subject=totals.first_commit_subject,- total_lines_added=totals.total_lines_added,- total_lines_deleted=totals.total_lines_deleted,- churn_anchor_sha=totals.churn_anchor_sha,- )-- with timed(timings, "persist.commits.fix_events"):- await persist_incremental_fix_events(session, repo_id, indexer)---def _churn_prior(repo_row: Any) -> Any:- """The stored totals lifetime churn can resume from, or ``None``.-- Only the four fields the fold reads are carried across, so this never- becomes a second way to read repo-level git facts. ``None`` for a repo row- that is missing or has no anchor yet, which makes the capture walk the whole- history exactly as it always did.- """- from repowise.core.ingestion.git_indexer.records import RepoTotals-- if repo_row is None:- return None- anchor = getattr(repo_row, "churn_anchor_sha", None)- if not anchor:- return None- return RepoTotals(- total_commit_count=repo_row.total_commit_count,- total_lines_added=repo_row.total_lines_added,- total_lines_deleted=repo_row.total_lines_deleted,- churn_anchor_sha=anchor,- )---async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any) -> None:- """Re-tally author experience across the whole commit table and re-score.-- ``build_commit_rows`` can only count the commits it is handed. On a full- index that is the entire window, so the number lands right; on an update it- is just the commits newer than the last one persisted, so every author's- count restarts at zero and an established author's new commits look like a- first-timer's. That is not only a cosmetic badge: ``author_experience`` is a- change-risk feature, so the stored ``change_risk_score`` inherits the error- and the review queue ranks on it.-- Rather than seed the batch tally, this re-derives experience over the full- persisted history after the append. The batch-local pass then has no lasting- say, so there is no second code path to keep correct, and rows written by- earlier (wrong) updates are repaired on the next one instead of waiting for- a re-index.-- Two things have to happen together. Unreachable commits are dropped first:- an update run on a feature branch persists that branch's shas, and once it- is squash-merged they survive as orphans that no full index would produce- and inflate every author's count. Then each surviving commit is re-scored- from its stored features, because a corrected experience that leaves the old- score in place would just move the inconsistency somewhere less visible.-- Bounded by the commit count and git-free apart from one ``rev-list``, and- failure-isolated like the rest of the git-phase refreshes.- """- from repowise.core.persistence.crud import (- delete_commit_health_by_sha,- delete_git_commit_files_by_sha,- delete_git_commits_by_sha,- get_commit_experience_inputs,- upsert_git_commits_bulk,- )-- try:- stored = await get_commit_experience_inputs(session, repo_id)- if not stored:- return-- reachable = await asyncio.to_thread(indexer.list_reachable_shas)- if reachable is not None:- orphans = [r["sha"] for r in stored if r["sha"] not in reachable]- if orphans:- await delete_git_commits_by_sha(session, repo_id, orphans)- # Per-commit rows leave with their commit; nothing cascades them.- await delete_git_commit_files_by_sha(session, repo_id, orphans)- await delete_commit_health_by_sha(session, repo_id, orphans)- stored = [r for r in stored if r["sha"] in reachable]- logger.info("commit_orphans_pruned", repo_id=repo_id, count=len(orphans))-- updates = _recompute_commit_experience(stored)- if updates:- await upsert_git_commits_bulk(session, repo_id, updates)- logger.info("commit_experience_reconciled", repo_id=repo_id, count=len(updates))- except Exception as exc:- logger.debug("commit_experience_reconcile_failed", error=str(exc))---async def reconcile_commit_offsets(session: Any, repo_id: str, indexer: Any) -> None:- """Backfill ``committed_offset_minutes`` on commits indexed before it existed.-- The offset is captured on the commit walk, so a full re-index gets it for- free — but an update only writes rows for *new* commits, which would leave a- repo indexed earlier with author-local hours on recent commits and UTC on- everything older. A punch card mixing the two is worse than one that is- honestly all-UTC, so the gap is closed here rather than waiting for a- re-index nobody should have to run for a new column.-- One ``git log`` and one bulk update, both skipped entirely once the column- is filled — the common case is a single cheap SELECT that returns nothing.- Failure-isolated like the other update-time reconciles; an unfilled offset- just means those rows keep falling back to UTC.- """- from repowise.core.persistence.crud import (- get_commits_missing_offset,- upsert_git_commits_bulk,- )-- try:- pending = await get_commits_missing_offset(session, repo_id)- if not pending:- return-- offsets = await asyncio.to_thread(indexer.capture_commit_offsets, pending)- if not offsets:- return-- await upsert_git_commits_bulk(- session,- repo_id,- [{"sha": sha, "committed_offset_minutes": minutes} for sha, minutes in offsets.items()],- )- logger.info("commit_offsets_backfilled", repo_id=repo_id, count=len(offsets))- except Exception as exc:- logger.debug("commit_offset_reconcile_failed", error=str(exc))---def _committed_ts(committed_at: Any) -> float:- """``committed_at`` as a sortable epoch, or 0 when the row has no date.-- SQLite drops tzinfo, so a naive read has to be reinterpreted as UTC — the- column is stored tz-aware. Doing that first also keeps ``timestamp()`` off- the platform's local-time conversion, which fails outright on Windows for- pre-epoch dates.- """- if committed_at is None:- return 0.0- from datetime import UTC-- if committed_at.tzinfo is None:- committed_at = committed_at.replace(tzinfo=UTC)- return committed_at.timestamp()---def _recompute_commit_experience(stored: list[dict]) -> list[dict]:- """Rows whose experience or risk moved, as partial upserts keyed by sha.-- Pure, so the ordering and re-scoring can be tested without a database.- Emits only changed rows: on a settled index that is a handful, which keeps a- whole-table read from turning into a whole-table write every update.- """- from repowise.core.analysis.change_risk import change_features_from_stored, score_change- from repowise.core.ingestion.git_indexer.commit_rows import author_experience_by_sha-- exp_by_sha = author_experience_by_sha(- [- {- "sha": r["sha"],- "author_name": r["author_name"] or "",- "author_email": r["author_email"] or "",- # committed_at is the only ordering key the table stores; rows- # without one sort oldest, which is where an unknown date least- # disturbs everyone else's running count.- "ts": _committed_ts(r["committed_at"]),- }- for r in stored- ]- )-- updates: list[dict] = []- for r in stored:- exp = exp_by_sha.get(r["sha"], 0)- risk = score_change(- change_features_from_stored(- la=r["lines_added"],- ld=r["lines_deleted"],- nf=r["files_changed"],- nd=r["dirs_changed"],- ns=r["subsystems_changed"],- entropy=r["entropy"],- exp=exp,- is_fix=r["is_fix"],- author=r["author_name"],- subject=r["subject"],- ref=r["sha"],- )- )- unchanged = (- r["author_experience"] == exp- and r["change_risk_level"] == risk.level- and r["change_risk_score"] is not None- and abs(r["change_risk_score"] - risk.score) < 1e-9- )- if unchanged:- continue- updates.append(- {- "sha": r["sha"],- "author_experience": exp,- "change_risk_score": risk.score,- "change_risk_level": risk.level,- }- )- return updates---async def persist_incremental_fix_events(session: Any, repo_id: str, indexer: Any) -> None:- """Trace + upsert ``fix_events`` for fix commits this index has not seen.-- Two halves, and both are needed for an update to converge on what a fresh- index would produce: append the fix commits missing from the table, then drop- the ones that have aged out of the trailing defect window. Without the prune- the stored set only ever grows past the window's trailing edge; without the- append it goes stale. Failure-isolated, like every other git-phase refresh.- """- from repowise.core.persistence.crud import (- get_fix_event_shas,- prune_fix_events_before,- prune_fix_events_for_missing_paths,- upsert_fix_events_bulk,- )-- try:- known = await get_fix_event_shas(session, repo_id)- rows, oldest_ts, tracked = await asyncio.to_thread(- indexer.capture_new_fix_events, known_shas=known- )- except Exception as exc:- logger.debug("incremental_fix_events_failed", error=str(exc))- return-- if rows:- await upsert_fix_events_bulk(session, repo_id, rows)- # A zero cutoff means the walk or the trace failed; pruning then would drop- # rows nothing replaced.- if oldest_ts:- from datetime import UTC, datetime-- await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))- if tracked:- await prune_fix_events_for_missing_paths(session, repo_id, tracked)-- # Recompute over the whole stored window, not just the rows this update- # appended: decay ages every file's mass whether or not the file changed.- try:- from repowise.core.pipeline.fix_rollups import apply_fix_rollups-- await apply_fix_rollups(session, repo_id)- except Exception as exc:- logger.debug("fix_rollups_failed", error=str(exc))---async def refresh_external_systems(- session: Any,- repo_id: str,- repo_path: Any,- file_diffs: list,- *,- log: LogFn | None = None,-) -> bool:- """Re-extract + reconcile external systems (C4 L1) when a manifest changed.-- The incremental path historically never refreshed the ``external_systems``- table, so the C4 architecture panel served the init-time dependency list- until the next full re-index. Extraction is a bounded repo walk (no LLM, no- network), so it is gated on an actual dependency-manifest change in this- update's diff — the common no-manifest update pays nothing.-- When a manifest did change, the *whole* repo is re-extracted: it's cheap,- and only a complete set supports a clean reconcile that also drops deps- removed from a manifest. The table is then replaced (removed deps pruned)- and ``external:{name}`` graph nodes re-linked so a brand-new dependency's- node isn't left with a NULL FK.-- Ceiling: re-extraction walks the repo (depth ≤ 4) rather than parsing only- the changed manifests — fine because it runs only on a manifest change and- a partial parse can't see cross-manifest removals. Returns ``True`` when a- refresh actually ran.- """- log = log or _noop_log- from repowise.core.ingestion.external_systems import is_manifest_path-- if not any(is_manifest_path(fd.path) for fd in file_diffs or []):- return False-- from repowise.core.ingestion.external_systems import extract_external_systems-- records = await asyncio.to_thread(extract_external_systems, Path(repo_path))- systems = [- {- "name": r.name,- "display_name": r.display_name,- "ecosystem": r.ecosystem,- "category": r.category,- "io_kind": r.io_kind,- "version": r.version,- "declared_in": r.declared_in,- "is_dev_dep": r.is_dev_dep,- }- for r in records- ]-- from repowise.core.persistence.crud import (- build_external_system_link_map,- link_graph_nodes_to_external_systems,- replace_external_systems,- )-- id_map = await replace_external_systems(session, repo_id, systems)- name_to_id = build_external_system_link_map(systems, id_map)- await link_graph_nodes_to_external_systems(session, repo_id, name_to_id)- log(f"External systems refreshed: [cyan]{len(systems)}[/cyan] deps")- return True---async def prune_deleted_files(- session: Any,- repo_id: str,- repo_path: Any,- graph_builder: Any,- live_paths: Iterable[str],- *,- health_report: Any,- skip: Callable[[str, Exception], None],- log: LogFn,- degraded: list[str] | None,- timings: PhaseTimings | None,-) -> None:- """Drop file-scoped rows for deleted files, then rebuild the queues built from them.-- Shared by every update writer. Liveness is asked of disk and git, never of- this run's parse (see prune_deleted_file_rows).-- Call it last in the session: the steps before it upsert, and the git step- indexes deleted paths too, so an earlier prune would be undone.-- The graph's file nodes join *live_paths* because resolver passes mint- file-shaped nodes that name no file (`external:`, `framework:`, Spring SPI- sources); they fail every liveness test, and only changed files' edges are- rebuilt afterwards. A graph that cannot be read skips the prune.- """- pruned = 0- try:- from repowise.core.pipeline.persist import prune_deleted_file_rows-- live_hint = set(live_paths) | {- node- for node, data in graph_builder.graph().nodes(data=True)- if data.get("node_type", "file") == "file"- }- with timed(timings, "persist.prune"):- pruned, refusals = await prune_deleted_file_rows(- session, repo_id, repo_path, live_hint=live_hint- )- if pruned:- log(f"Pruned rows for [cyan]{pruned}[/cyan] deleted file(s)")- for refusal in refusals:- log(f"[yellow]{refusal}[/yellow]")- if degraded is not None:- degraded.append(refusal)- except Exception as exc:- skip("Deleted-file prune", exc)-- # The performance and refactoring queues are materialized from the health- # findings the prune just deleted; without this they keep serving a cause- # whose evidence is gone, on a file the store no longer claims exists.- if not pruned:- return- try:- from repowise.core.persistence.crud import (- finalize_performance_opportunities,- finalize_refactoring_opportunities,- )- from repowise.core.pipeline.persist import _analyzed_commit-- analyzed_commit = await _analyzed_commit(session, repo_id)- await finalize_performance_opportunities(- session,- repo_id,- analyzed_commit=analyzed_commit,- plan_policy=getattr(health_report, "performance_plan_policy", None),- execution_roles=getattr(health_report, "execution_roles", None),- )- await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)- except Exception as exc:- skip("Queue rebuild after prune", exc)---async def persist_incremental_index(- repo_path: Any,- graph_builder: Any,- git_meta_map: dict,- dead_code_report: Any,- partial_health_report: Any,- changed_paths: list[str],- *,- doc_drift_report: Any | None = None,- current_graph_file_paths: set[str] | None = None,- file_diffs: list[Any] | None = None,- knowledge_graph_result: Any | None = None,- parsed_files: list[Any] | None = None,- source_map: dict[str, Any] | None = None,- git_decay_map: dict | None = None,- full_git_summary: Any | None = None,- history_window_changed: bool = False,- reconcile_full_scope: bool = False,- full_generation_page_ids: set[str] | None = None,- vector_store: Any | None = None,- log: LogFn | None = None,- degraded: list[str] | None = None,- failed_steps: list[str] | None = None,- timings: PhaseTimings | None = None,-) -> None:- """Persist an incremental index refresh (graph + symbols + git + dead-code + health).-- Upsert-only: unchanged files keep their existing rows, unlike- ``persist_pipeline_result``'s delete-then-insert. State-file updates stay- with the caller — this writes the DB only.-- ``degraded`` (when supplied) collects a one-line entry for every- best-effort step that failed, so the caller can render an honest- completion report instead of silently claiming success.-- ``failed_steps`` (when supplied) collects the names of the failed steps- whose input was *this commit range* rather than the whole repo. Those are- the only failures a later run cannot heal on its own: their data is scoped- to a range the sync pointer is about to move past, so the caller records- them as a repair marker and re-covers the range next update.-- The test for membership is "would widening the next run's diff base repair- this, and would nothing else". Steps that re-derive the whole repo every- run are deliberately absent (graph nodes, the sweeps, the page tree,- related pages, the knowledge graph, the deleted-file prune): they heal- themselves on the next update, and marking them would let a permanently- broken one pin the repair window open. So is the commit capture, which- looks range-scoped and is not: it bounds its walk by the newest- ``committed_at`` already in the table, so a run it skipped is re-walked by- the next one whatever the diff base says.-- ``timings`` records the whole write as ``persist`` and each step as a- ``persist.*`` row. A step that did not run records nothing, so an absent- row means skipped rather than free.- """- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- upsert_repository,- )- from repowise.core.persistence.database import resolve_db_url-- log = log or _noop_log-- def _skip(step: str, exc: Exception, *, range_scoped: bool = False) -> None:- log(f"[yellow]{step} skipped: {exc}[/yellow]")- if degraded is not None:- degraded.append(f"{step}: {exc}")- if range_scoped and failed_steps is not None:- failed_steps.append(step)-- url = resolve_db_url(repo_path)- engine = create_engine(url)- # Filled by the tombstone step; read after the session closes, so it has to- # survive a step that was skipped.- tombstoned_page_ids: list[str] = []- # Same contract, for rows of a page that has been retired outright.- swept_page_ids: list[str] = []- if timings is not None:- timings.start("persist")- try:- with timed(timings, "persist.open"):- await init_db(engine)- sf = create_session_factory(engine)-- async with get_session(sf) as session:- with timed(timings, "persist.open"):- repo = await upsert_repository(- session, name=repo_path.name, local_path=str(repo_path), stamp_head=True- )- repo_id = repo.id-- if reconcile_full_scope:- try:- from repowise.core.pipeline.persist import (- reconcile_full_index_scope,- )-- current_graph_paths = set(- getattr(- graph_builder,- "traversed_file_paths",- {pf.file_info.path for pf in parsed_files or []},- )- )- current_git_paths = set(git_meta_map)- with timed(timings, "persist.scope_reconcile"):- tombstoned_page_ids = await reconcile_full_index_scope(- session,- repo_id,- current_graph_paths,- current_git_paths,- )- except Exception as exc:- _skip("Config scope reconciliation", exc)-- if full_generation_page_ids is not None:- try:- from repowise.core.pipeline.persist import (- tombstone_pages_outside_generation,- )-- tombstoned_page_ids += await tombstone_pages_outside_generation(- session, repo_id, full_generation_page_ids- )- except Exception as exc:- _skip("Generation scope reconciliation", exc)-- # Delete rows of pages retired since this index was built. This- # path never regenerates a repo-wide page, so nothing else here- # would ever visit one to notice it should be gone, and for a user- # whose updates all come from the post-commit hook this is the only- # place a retirement can land.- try:- from repowise.core.pipeline.persist import (- sweep_absent_cycle_pages,- sweep_absent_symbol_spotlights,- sweep_retired_pages,- )-- with timed(timings, "persist.sweeps"):- swept_page_ids = await sweep_retired_pages(session, repo_id)- # Same reasoning as the retirement sweep above: this path- # never regenerates a cycle page, so asking the rebuilt- # graph whether the cycle still exists is the only way a- # fixed cycle's page can ever be retired for a user who- # only runs `update`. Spotlights of removed symbols too.- swept_page_ids += await sweep_absent_cycle_pages(- session, repo_id, graph_builder- )- swept_page_ids += await sweep_absent_symbol_spotlights(- session, repo_id, graph_builder- )- except Exception as exc:- _skip("Retired page sweep", exc)-- # Tombstone pages for deleted/renamed files FIRST — a fresh page- # for a file that no longer exists misleads every retrieval- # consumer until the next full regeneration.- if file_diffs:- try:- from repowise.core.pipeline.persist import (- mark_tombstone_pages,- tombstone_candidates,- )-- with timed(timings, "persist.tombstones"):- tombstoned_page_ids += await mark_tombstone_pages(- session, repo_id, tombstone_candidates(file_diffs)- )- except Exception as exc:- _skip("Tombstone marking", exc, range_scoped=True)-- # Placement depends on the whole page set, which on an incremental- # run lives in the store rather than in the pages just generated.- try:- from repowise.core.pipeline.page_tree_sync import rebuild_page_tree-- with timed(timings, "persist.page_tree"):- await rebuild_page_tree(session, repo_id)- except Exception as exc:- _skip("Page tree rebuild", exc)-- if git_meta_map or git_decay_map or full_git_summary is not None:- try:- with timed(timings, "persist.git"):- from repowise.core.pipeline.persist import persist_git_refresh-- await persist_git_refresh(- session,- repo_id,- git_meta_map,- git_decay_map,- full_git_summary,- keep_commit_health=not history_window_changed,- )- except Exception as exc:- _skip("Git persist", exc, range_scoped=True)-- try:- with timed(timings, "persist.commits"):- if full_git_summary is None:- await persist_incremental_commits(- session, repo_id, repo_path, timings=timings- )- except Exception as exc:- _skip("Commit capture", exc)-- if dead_code_report is not None:- try:- from repowise.core.persistence.crud import (- replace_dead_code_findings,- )-- # The report is repo-wide, and dead code is a cross-file- # property, so a change-scoped write would drop every- # verdict the change flipped outside the change set. The- # scope is the set of files whose confidence was scored on- # real git metadata; the rest keep what they had.- with timed(timings, "persist.dead_code"):- await replace_dead_code_findings(- session,- repo_id,- dead_code_report.findings,- scope=dead_code_report.authoritative_paths,- )- except Exception as exc:- _skip("Dead-code persist", exc, range_scoped=True)-- if doc_drift_report is not None:- try:- from repowise.core.persistence.crud import (- replace_doc_drift_guarded,- )-- with timed(timings, "persist.doc_drift"):- await replace_doc_drift_guarded(- session, repo_id, doc_drift_report- )- except Exception as exc:- # Not range_scoped: the pass re-derives every document each- # run, so a skipped write heals itself on the next update.- _skip("Doc-drift persist", exc)-- # Re-persist graph_nodes so symbol-level PageRank /- # betweenness / community ids stay in sync with the- # current graph build. Without this, ``repowise update``- # leaves stale per-symbol metrics from the original init- # and the UI shows "Not indexed in graph" for every- # symbol on existing repos. Before health, whose plan- # annotations read each symbol's ``public_api`` from here; a- # failed write leaves them reading the last run's flags.- try:- from repowise.core.pipeline.persist import persist_graph_nodes-- with timed(timings, "persist.graph_nodes"):- await persist_graph_nodes(session, repo_id, graph_builder, timings=timings)- except Exception as exc:- _skip("Graph nodes persist", exc)-- if partial_health_report is not None:- try:- with timed(timings, "persist.health"):- await persist_partial_health(- session, repo_id, partial_health_report, repo_path- )- except Exception as exc:- _skip("Health persist", exc, range_scoped=True)-- # Refresh wiki_symbols for the changed files. Historically the- # incremental path re-parsed but never persisted symbols, so their- # start/end bounds fossilized at the last full index and the- # get_answer hydrator served drifted signatures. Scoped to the- # changed set for cost.- try:- from repowise.core.pipeline.persist import persist_incremental_symbols-- with timed(timings, "persist.symbols"):- await persist_incremental_symbols(session, repo_id, parsed_files, changed_paths)- except Exception as exc:- _skip("Symbol persist", exc, range_scoped=True)-- try:- from repowise.core.pipeline.persist import persist_incremental_security_findings-- with timed(timings, "persist.security"):- await persist_incremental_security_findings(- session, repo_id, parsed_files, source_map, changed_paths- )- except Exception as exc:- _skip("Security persist", exc, range_scoped=True)-- # Refresh graph_edges for the changed files. The full-init path was- # historically the only writer of edges, so adjacency froze at the- # last full index: new imports/calls stayed invisible and dropped- # ones lingered as false paths. Phase E flow-path traversal reads- # adjacency straight from this table, so it decayed on every update.- try:- from repowise.core.pipeline.persist import persist_incremental_edges-- with timed(timings, "persist.edges"):- await persist_incremental_edges(- session, repo_id, graph_builder, parsed_files, changed_paths- )- except Exception as exc:- _skip("Graph edges persist", exc, range_scoped=True)-- # Refresh related-pages metadata across the whole wiki. LLM-free,- # so even index-only updates heal pages generated before the- # feature shipped (or drifted by new imports) in one run.- try:- from repowise.core.generation.related_pages import file_import_edges- from repowise.core.persistence.crud import backfill_related_pages-- with timed(timings, "persist.related_pages"):- changed_rel = await backfill_related_pages(- session,- repo_id,- import_edges=file_import_edges(graph_builder),- git_meta_map=git_meta_map,- pagerank=graph_builder.pagerank(),- )- if changed_rel:- log(f"Related pages refreshed on {changed_rel} pages")- except Exception as exc:- _skip("Related-pages backfill", exc)-- if knowledge_graph_result is not None:- try:- from repowise.core.pipeline.persist import persist_kg-- with timed(timings, "persist.kg"):- await persist_kg(knowledge_graph_result, session, repo_id)- except Exception as exc:- _skip("Knowledge-graph persist", exc)-- # Refresh external systems (C4 L1) when a dependency manifest- # changed — otherwise the architecture panel serves the init-time- # dep list forever. Gated + no LLM (see refresh_external_systems).- if file_diffs:- try:- with timed(timings, "persist.external_systems"):- await refresh_external_systems(- session, repo_id, repo_path, file_diffs, log=log- )- except Exception as exc:- _skip("External systems refresh", exc, range_scoped=True)-- # One-shot drain of proposals from the removed code_comment- # harvest (#751). Runs on the index-only path too, because the- # post-commit hook's updates never reach the full decision- # persist. Confirmed/dismissed rows are kept.- try:- from repowise.core.persistence.crud import (- purge_proposed_decisions_by_source,- )-- await purge_proposed_decisions_by_source(session, repo_id, "code_comment")- # A history-window change re-mines these; a walk that only- # refreshes rows under new rules does not, so it keeps them.- if full_git_summary is not None and history_window_changed:- await purge_proposed_decisions_by_source(- session, repo_id, "git_archaeology"- )- except Exception as exc:- _skip("Decision purge", exc)-- # Last in the session on purpose: everything above upserts, and the- # git step indexes the changed *paths*, deleted ones included, so- # the prune has to have the final say on what the store claims.- await prune_deleted_files(- session,- repo_id,- repo_path,- graph_builder,- (- current_graph_file_paths- if current_graph_file_paths is not None- else {pf.file_info.path for pf in parsed_files or []}- ),- health_report=partial_health_report,- skip=_skip,- log=log,- degraded=degraded,- timings=timings,- )- # The transaction commits as the block exits.- if timings is not None:- timings.start("persist.commit")- if timings is not None:- timings.stop("persist.commit")-- # Every update, not only those with git changes: a backlog an earlier- # budget left drains here, and an empty window costs one query.- from repowise.core.pipeline.commit_health import refresh_commit_health_after_update-- with timed(timings, "persist.commit_health"):- await refresh_commit_health_after_update(sf, repo_id, str(repo_path))-- # After the session closes: on SQLite the full-text index shares the- # database file, so writing to it while the session holds a write lock- # raises "database is locked".- #- # A tombstone can never be an answer — hydration drops it — but- # retrieval fetches a fixed number of rows before that check runs, so- # every tombstone left in the index costs a real candidate its slot.- #- # A swept page's FTS row is worse than a tombstone: search hydrates- # title and snippet from the FTS copy itself, so an orphan answers in- # full while the page it names 404s.- from repowise.core.pipeline.cleanup_debt import (- clear_cleanup_debt,- load_cleanup_debt,- record_cleanup_debt,- )-- cleanup_debt = load_cleanup_debt(Path(repo_path))- fts_cleanup_ids = (- set(tombstoned_page_ids) | set(swept_page_ids) | cleanup_debt["fts"]- )- if fts_cleanup_ids:- try:- from repowise.core.persistence.search import FullTextSearch-- fts = FullTextSearch(engine)- with timed(timings, "persist.fts"):- await fts.ensure_index()- await fts.delete_many(sorted(fts_cleanup_ids))- clear_cleanup_debt(Path(repo_path), "fts", fts_cleanup_ids)- except Exception as exc:- # Range-scoped for the tombstone half: mark_tombstone_pages- # re-marks and re-returns pages that are already tombstones, so- # a widened re-run regenerates these ids and retries the delete.- # The swept half is not repairable this way, because the sweeps- # deleted those rows and a later run finds nothing to sweep.- # Tagging still recovers strictly more than not tagging.- record_cleanup_debt(Path(repo_path), "fts", fts_cleanup_ids)- _skip("Tombstone full-text removal", exc, range_scoped=True)-- vector_cleanup_ids = set(tombstoned_page_ids) | cleanup_debt["vectors"]- if vector_cleanup_ids and vector_store is None:- lance_dir = Path(repo_path) / ".repowise" / "lancedb"- if lance_dir.exists():- try:- from repowise.core.persistence.vector_store import LanceDBVectorStore- from repowise.core.providers.embedding.base import MockEmbedder-- # Delete-only access never embeds or checks dimensions.- vector_store = LanceDBVectorStore(str(lance_dir), embedder=MockEmbedder())- except Exception as exc:- record_cleanup_debt(- Path(repo_path), "vectors", vector_cleanup_ids- )- _skip("Tombstone vector-store open", exc, range_scoped=True)- else:- # No store means there are no vector rows left to clean.- clear_cleanup_debt(Path(repo_path), "vectors", vector_cleanup_ids)-- if vector_cleanup_ids and vector_store is not None:- try:- with timed(timings, "persist.vectors"):- await vector_store.delete_many(sorted(vector_cleanup_ids))- clear_cleanup_debt(Path(repo_path), "vectors", vector_cleanup_ids)- except Exception as exc:- record_cleanup_debt(Path(repo_path), "vectors", vector_cleanup_ids)- _skip("Tombstone vector removal", exc)-- # Ceiling: retired non-file pages' *vector* embeddings survive this path.- # There is no store here to delete them from, and building one would- # pull the lancedb import onto the post-commit hook, which- # ``deterministic.py`` avoids on purpose — and with the default mock- # embedder this path never wrote a page embedding in the first place.- # LanceDB hydrates a hit from its own columns, so a residual embedding- # can still surface in semantic search until the next docs-mode update- # (which does delete it) or a reindex.- finally:- await engine.dispose()- if timings is not None:- timings.stop("persist")diff --git a/packages/core/src/repowise/core/pipeline/incremental/__init__.py b/packages/core/src/repowise/core/pipeline/incremental/__init__.pynew file mode 100644index 000000000..515893edb--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/__init__.py@@ -0,0 +1,124 @@+"""Incremental (changed-files) index refresh.++The orchestration that `repowise update` runs for an already-indexed repo:+re-ingest the graph (parse-cache backed), re-index git metadata for the+changed files only, run partial health/dead-code analysis, and upsert the+results — without the full pipeline's delete-then-insert persistence or LLM+generation.++Extracted from the CLI update command so workspace updates can route+already-indexed member repos through the same incremental path instead of+re-running the full init pipeline per repo. The CLI keeps thin wrappers+that delegate here.++Progress/diagnostic messages go through an optional ``log`` callback (the+CLI passes ``console.print``; messages use rich markup). When ``log`` is+omitted the messages are dropped — every one of them annotates a+best-effort step that already degrades gracefully.++Submodules: :mod:`.graph`, :mod:`.loaders`, :mod:`.analysis`,+:mod:`.knowledge_graph`, :mod:`.health`, :mod:`.commits`,+:mod:`.external_systems`, :mod:`.prune` and :mod:`.persist_index`. Every name+is re-exported here. Patch a name where it is looked up: a patch on this+package does not reach lookups inside the submodules.+"""++from __future__ import annotations++from ._common import (+ LogFn,+ _noop_log,+ logger,+)+from .analysis import (+ DocDriftUpdate,+ _drift_symbol_options,+ _performance_only_config,+ run_doc_drift_partial,+ run_partial_analysis,+)+from .commits import (+ _churn_prior,+ _committed_ts,+ _recompute_commit_experience,+ persist_incremental_commits,+ persist_incremental_fix_events,+ reconcile_commit_experience,+ reconcile_commit_offsets,+)+from .external_systems import (+ refresh_external_systems,+)+from .graph import (+ _add_parsed_files,+ _add_synthetic_edges,+ _parse_misses,+ _record_structural_episodes,+ build_filtered_changed_paths,+ build_repo_graph,+ rebuild_graph_and_git,+)+from .health import (+ _differs,+ _history_findings_moved,+ _numbers_moved,+ _refreshed_metric,+ persist_partial_health,+ refresh_unchanged_history,+)+from .knowledge_graph import (+ _carry_forward_kg_enrichment,+ refresh_knowledge_graph,+)+from .loaders import (+ load_stored_coverage_map,+ load_stored_function_mod_p80,+ load_stored_git_meta,+ load_stored_performance_callers,+)+from .persist_index import (+ persist_incremental_index,+)+from .prune import (+ prune_deleted_files,+)++__all__ = [+ "DocDriftUpdate",+ "LogFn",+ "_add_parsed_files",+ "_add_synthetic_edges",+ "_carry_forward_kg_enrichment",+ "_churn_prior",+ "_committed_ts",+ "_differs",+ "_drift_symbol_options",+ "_history_findings_moved",+ "_noop_log",+ "_numbers_moved",+ "_parse_misses",+ "_performance_only_config",+ "_recompute_commit_experience",+ "_record_structural_episodes",+ "_refreshed_metric",+ "build_filtered_changed_paths",+ "build_repo_graph",+ "load_stored_coverage_map",+ "load_stored_function_mod_p80",+ "load_stored_git_meta",+ "load_stored_performance_callers",+ "logger",+ "persist_incremental_commits",+ "persist_incremental_fix_events",+ "persist_incremental_index",+ "persist_partial_health",+ "prune_deleted_files",+ "rebuild_graph_and_git",+ "reconcile_commit_experience",+ "reconcile_commit_offsets",+ "refresh_external_systems",+ "refresh_knowledge_graph",+ "refresh_unchanged_history",+ "run_doc_drift_partial",+ "run_partial_analysis",+]diff --git a/packages/core/src/repowise/core/pipeline/incremental/_common.py b/packages/core/src/repowise/core/pipeline/incremental/_common.pynew file mode 100644index 000000000..90af6ba48--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/_common.py@@ -0,0 +1,16 @@+"""Shared logging hooks for the incremental refresh steps."""++from __future__ import annotations++from collections.abc import Callable++import structlog++# One logger for the whole package, named as before the split.+logger = structlog.get_logger("repowise.core.pipeline.incremental")++LogFn = Callable[[str], None]+++def _noop_log(message: str) -> None: # pragma: no cover - trivial+ return Nonediff --git a/packages/core/src/repowise/core/pipeline/incremental/analysis.py b/packages/core/src/repowise/core/pipeline/incremental/analysis.pynew file mode 100644index 000000000..df64d9b4b--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/analysis.py@@ -0,0 +1,351 @@+"""Partial health, dead-code and doc-drift analysis for an incremental run."""++from __future__ import annotations++from collections.abc import Iterable+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from repowise.core.pipeline.phase_timing import PhaseTimings, timed++from ._common import LogFn, _noop_log+++def _performance_only_config(config: dict | None, performance_only: set[str]) -> dict | None:+ """Disable every non-performance detector on the closure's files.++ The closure adds files whose call paths reach a changed sink. Only their+ performance findings survive the filter below; every other detector's+ output for them is computed and discarded, and on a central helper the+ closure runs to hundreds of files. The walk still covers them, because the+ performance detectors read it.+ """+ if not performance_only:+ return config+ from repowise.core.analysis.health.biomarkers import registered_biomarkers+ from repowise.core.analysis.health.scoring import dimensions_for++ non_performance = {+ b.name for b in registered_biomarkers() if "performance" not in dimensions_for(b.name)+ }+ out = dict(config or {})+ per_file = {k: set(v) for k, v in (out.get("per_file_disabled") or {}).items()}+ for path in performance_only:+ per_file[path] = per_file.get(path, set()) | non_performance+ out["per_file_disabled"] = per_file+ return out+++def run_partial_analysis(+ repo_path: Any,+ graph_builder: Any,+ git_meta_map: dict,+ parsed_files: list,+ file_diffs: list,+ *,+ source_map: dict[str, bytes] | None = None,+ stored_git_meta: dict[str, dict] | None = None,+ stored_performance_callers: set[str] | None = None,+ repo_function_mod_p80: int | None = None,+ coverage_map: dict[str, dict] | None = None,+ log: LogFn | None = None,+ timings: PhaseTimings | None = None,+) -> tuple[Any, Any]:+ """Run partial code-health + repo-wide dead-code analysis.++ Returns ``(partial_health_report, dead_code_report)`` — either may be+ ``None`` if its analysis failed (both are best-effort).++ *source_map* is ingestion's ``{path: raw bytes}`` for this rebuild; the+ dead-code prepasses read it instead of re-reading the repo from disk.++ *stored_git_meta* is the persisted per-file git metadata. ``git_meta_map`` holds this run's freshly+ indexed rows, which on an incremental update means the changed files and+ nothing else; every other file would otherwise be scored against an empty+ dict and land on the ``commit_count_90d == 0`` rung of the confidence+ ladder at 0.7 / ``safe_to_delete=True``. It is supplied whole to dead-code+ and to performance ranking, but deliberately not merged into health's+ general ``git_meta_map``: widening that aggregate would silently move+ nonperformance scores (the same reason idle-decay rows stay out of it).++ *stored_performance_callers* is the old-side caller set recovered in one+ store read. It keeps deletion and rename updates authoritative when the+ rebuilt graph can no longer contain the removed execution edge.++ *repo_function_mod_p80* is the repo-wide 80th percentile of per-function+ modification counts, loaded from the persisted ``git_function_blame``+ rollup (see :func:`load_stored_function_mod_p80`). It is passed through to+ the health analyzer so the Function Hotspot gate is scored against the full+ repo instead of this run's changed-files subset (issue #1484). ``None``+ makes the analyzer fall back to deriving it from the walked files.++ ``None`` means the store could not be read, which is different from an+ empty mapping and narrows what the resulting report is allowed to+ overwrite. See ``load_stored_git_meta``.++ ``timings`` records the two analyses as ``analysis.health`` and+ ``analysis.dead_code``. Their costs move independently with the edit, so+ they are never folded into one row.+ """+ log = log or _noop_log++ # Run partial code-health analysis up front so both the index-only+ # and full paths can upsert findings/metrics for changed files only.+ # The full file-list is needed because duplication is cross-file —+ # but only files in ``changed_paths`` produce new findings/metrics.+ partial_health_report = None+ if timings is not None:+ timings.start("analysis.health")+ try:+ # Performance is interprocedural. Recompute one bounded bidirectional+ # execution closure so a changed caller can still see an unchanged sink+ # and an unchanged caller can react to a changed sink. The index is+ # built once; this is a multi-source walk, not one walk per finding.+ from repowise.core.analysis.communities import file_community_labels+ from repowise.core.analysis.execution_graph import ExecutionGraphIndex+ from repowise.core.analysis.health import HealthAnalyzer+ from repowise.core.analysis.health.config import HealthConfig++ _health_changed = {+ fd.path for fd in file_diffs if fd.status in ("added", "modified", "renamed")+ }+ parsed_paths = {pf.file_info.path for pf in parsed_files}+ execution_index = ExecutionGraphIndex(graph_builder.graph())+ _performance_changed = execution_index.affected_files(_health_changed) & parsed_paths+ if stored_performance_callers is not None:+ historical_callers = stored_performance_callers & parsed_paths+ _performance_changed |= (+ execution_index.affected_files(historical_callers) & parsed_paths+ )+ _health_scope = _health_changed | _performance_changed+ _health_analyzer = HealthAnalyzer(+ graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ community_label_map=file_community_labels(graph_builder),+ duplication_cache_dir=Path(repo_path) / ".repowise",+ repo_root=repo_path,+ coverage_map=coverage_map,+ )+ if _health_scope:+ _hcfg = HealthConfig.load(repo_path)+ _analyzer_config = (+ _hcfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])+ if _hcfg.has_overrides()+ else None+ )+ _analyzer_config = _performance_only_config(+ _analyzer_config, _performance_changed - _health_changed+ )+ partial_health_report = _health_analyzer.analyze(+ _analyzer_config,+ changed_files=_health_scope,+ repo_function_mod_p80=repo_function_mod_p80,+ timings=timings,+ duplication_files=_health_changed,+ )+ # The closure exists only to refresh interprocedural performance.+ # Preserve the historical changed-file scope for every other+ # dimension, metric, blame row, and refactoring detector.+ partial_health_report.authoritative_paths = set(_health_changed)+ partial_health_report.performance_authoritative_paths = set(_performance_changed)+ partial_health_report.metrics = [+ metric+ for metric in partial_health_report.metrics+ if metric.file_path in _health_changed+ ]+ partial_health_report.findings = [+ finding+ for finding in partial_health_report.findings+ if finding.file_path in _health_changed or finding.dimension == "performance"+ ]+ partial_health_report.refactoring_suggestions = [+ suggestion+ for suggestion in partial_health_report.refactoring_suggestions+ if suggestion.file_path in _health_changed+ or suggestion.refactoring_type == "performance_fix"+ ]+ partial_health_report.function_blame_rows = [+ row+ for row in partial_health_report.function_blame_rows+ if row.get("file_path") in _health_changed+ ]+ log(+ f"Health analysis (partial): [cyan]{len(_health_changed)} changed[/cyan], "+ f"[cyan]{len(_performance_changed)} performance-affected[/cyan], "+ f"[yellow]{len(partial_health_report.findings)} findings[/yellow]"+ )+ except Exception as exc:+ log(f"[yellow]Health analysis skipped: {exc}[/yellow]")+ finally:+ if timings is not None:+ timings.stop("analysis.health")++ # Run dead-code analysis up front so both branches can persist its+ # results. Previously this sat below the ``if index_only``+ # short-circuit, which left the closure's reference to+ # ``dead_code_report`` unbound and crashed every ``--index-only`` run.+ dead_code_report = None+ if timings is not None:+ timings.start("analysis.dead_code")+ try:+ from repowise.core.analysis.dead_code import DeadCodeAnalyzer++ # parsed_files enables the source-scan rescues (dynamic markers,+ # bundler aliases, export aliases) on the update path, matching init.+ #+ # This run's freshly indexed rows win over the stored ones for the+ # files they cover; the stored rows carry every other file, which is+ # what init's analyzer had and this path did not.+ _dead_code_git_meta = {**(stored_git_meta or {}), **git_meta_map}+ # Files the walk dropped (size, no language spec, generated). This+ # report is persisted repo-wide (see below), so without them an update+ # would re-derive the verdicts init had clamped and write them back+ # unclamped — the #1237 cascade would return, looking like the fix had+ # regressed.+ _traversal_stats = getattr(graph_builder, "traversal_stats", None)+ _dead_code_analyzer = DeadCodeAnalyzer(+ graph_builder.graph(),+ _dead_code_git_meta,+ parsed_files=graph_builder._parsed_files,+ source_map=source_map,+ repo_root=repo_path,+ unindexed_source_files=(+ _traversal_stats.unindexed_source_files() if _traversal_stats is not None else []+ ),+ dotnet_index=getattr(graph_builder, "dotnet_index", None),+ )+ # Repo-wide, and persisted repo-wide. The detectors were always+ # repo-wide — the update path just discarded everything outside the+ # change set before writing, which is why an unchanged file that the+ # change had made dead (or brought back to life) kept its old verdict+ # until someone re-indexed from scratch.+ dead_code_report = _dead_code_analyzer.analyze()++ # What this report is allowed to overwrite.+ #+ # When the stored read succeeded, this run's git knowledge is the same+ # knowledge a full index had — the stored rows ARE what the last full+ # index wrote, with this run's fresher ones on top — so every file is+ # scored at least as well here as it was there and the report speaks+ # for the whole repository. That includes files with no git row at+ # all: a full index had no row for them either and scored them the+ # same way, so holding them back would protect nothing while leaving+ # exactly the stale verdicts this is meant to fix. Coverage is not the+ # test, and cannot be: ``git_metadata`` legitimately covers only the+ # files ``index_repo`` produced.+ #+ # When the read FAILED, this run knows strictly less than the index it+ # would be overwriting: every file outside the change set would be+ # scored with no git row, which the analyzer holds below the+ # deletion-ready threshold, so a verdict a full index scored at 1.0+ # would be written back as an unscored 0.5. So it speaks only for the+ # files it re-indexed this run, which is the behavior this path had+ # before it was widened.+ dead_code_report.authoritative_paths = (+ None if stored_git_meta is not None else frozenset(git_meta_map)+ )+ if dead_code_report.authoritative_paths is not None:+ log(+ "[yellow]Dead-code findings limited to "+ f"{len(dead_code_report.authoritative_paths)} re-indexed files; "+ "the rest keep their previous verdict[/yellow]"+ )+ if dead_code_report.total_findings:+ log(+ f"Dead code findings: [yellow]{dead_code_report.total_findings}[/yellow]"+ " repo-wide, every kind"+ )+ except Exception as exc:+ log(f"[yellow]Dead code analysis skipped: {exc}[/yellow]")+ finally:+ if timings is not None:+ timings.stop("analysis.dead_code")++ return partial_health_report, dead_code_report+++@dataclass(frozen=True)+class DocDriftUpdate:+ """What an update tells the drift pass about the change it is applying."""++ base_ref: str | None = None+ """The commit the update diffs from, to the working tree."""+ changed_paths: tuple[str, ...] = ()+ """Every path the update adds, edits, deletes or renames (both sides)."""+ symbol_names: frozenset[str] | None = None+ """The index's symbol names; ``None`` reads them from the graph."""++ @classmethod+ def from_file_diffs(cls, base_ref: str | None, file_diffs: Iterable[Any]) -> DocDriftUpdate:+ paths = tuple(p for fd in file_diffs for p in (fd.path, fd.old_path) if p)+ return cls(base_ref=base_ref, changed_paths=paths)+++def run_doc_drift_partial(+ graph_builder: Any,+ source_map: dict[str, bytes] | None,+ *,+ repo_path: Any | None = None,+ log: LogFn | None = None,+ timings: PhaseTimings | None = None,+ update: DocDriftUpdate | None = None,+) -> Any | None:+ """Re-check the repository's own markdown on the incremental path.++ Its own function rather than a third member of+ :func:`run_partial_analysis`'s tuple, mirroring the full path where drift is+ its own phase. Returns ``None`` when the pass could not run, which the+ caller must treat as "write nothing".++ The cheap kinds are re-derived for every document. Symbol references are+ re-resolved only where *update* could have changed them (see+ :class:`~repowise.core.analysis.doc_drift.symbols.SymbolRecheck`); the rest+ carry forward in the store.+ """+ log = log or _noop_log+ if not source_map:+ return None++ with timed(timings, "analysis.doc_drift"):+ try:+ from repowise.core.analysis.doc_drift import DocDriftAnalyzer++ # The traversal, not the parse set. ``source_map`` omits files that+ # failed to read or parse, and resolving against that narrower tree+ # turns a live path into a fabricated "missing" finding.+ tracked_paths = getattr(graph_builder, "traversed_file_paths", None)+ if not tracked_paths:+ return None++ root = Path(repo_path) if repo_path else None+ report = DocDriftAnalyzer(+ source_map=source_map,+ tracked_paths=tracked_paths,+ repo_root=root,+ symbols=_drift_symbol_options(graph_builder, root, update or DocDriftUpdate()),+ ).analyze()+ report.authoritative_paths = report.documents+ if report.total_findings:+ log(f"Doc drift findings: [yellow]{report.total_findings}[/yellow]")+ return report+ except Exception as exc:+ log(f"[yellow]Doc drift analysis skipped: {exc}[/yellow]")+ return None+++def _drift_symbol_options(graph_builder: Any, root: Path | None, update: DocDriftUpdate) -> Any:+ """The drift pass's symbol options for *update*; ``None`` without a working tree."""+ from repowise.core.analysis.doc_drift.symbols import (+ SymbolOptions,+ graph_symbol_names,+ symbol_recheck,+ )++ if root is None:+ return None+ names = update.symbol_names+ if names is None:+ names = graph_symbol_names(graph_builder.graph())+ return SymbolOptions(names, symbol_recheck(root, update.base_ref, update.changed_paths))diff --git a/packages/core/src/repowise/core/pipeline/incremental/commits.py b/packages/core/src/repowise/core/pipeline/incremental/commits.pynew file mode 100644index 000000000..62c95786d--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/commits.py@@ -0,0 +1,361 @@+"""Commit, fix-event and repo-total capture for an incremental run."""++from __future__ import annotations++import asyncio+from functools import partial+from typing import Any++from repowise.core.pipeline.phase_timing import PhaseTimings, timed++from ._common import logger+++async def persist_incremental_commits(+ session: Any, repo_id: str, repo_path: Any, *, timings: PhaseTimings | None = None+) -> None:+ """Capture + upsert ``git_commits`` rows for commits new since the last index.++ Foundation 1 only populated the per-commit table on the full orchestrator+ index; without this, the commits/change-risk surface goes stale between full+ re-indexes. Bounds the walk to commits newer than the newest persisted+ ``committed_at`` (one ``git log`` pass) and upserts (idempotent on sha).+ """+ from repowise.core.ingestion.git_indexer import GitIndexer+ from repowise.core.persistence.crud import (+ clear_attribution_if_disabled,+ get_latest_commit_committed_at,+ get_repository,+ update_repo_git_totals,+ upsert_git_commit_files_bulk,+ upsert_git_commits_bulk,+ )+ from repowise.core.repo_config import load_repo_config++ cfg = load_repo_config(repo_path)+ indexer = GitIndexer(+ repo_path,+ commit_limit=cfg.get("commit_limit"),+ follow_renames=cfg.get("follow_renames", False),+ # The fix-event capture walks the tracked-file set itself, so without+ # the repo's excludes an update would store events for files a full+ # index never sees, and they would never age out.+ exclude_patterns=cfg.get("exclude_patterns"),+ # Git episodes ride the same capture and inherit those excludes.+ record_episodes=True,+ )+ newest = await get_latest_commit_committed_at(session, repo_id)+ since_ts: int | None = None+ if newest is not None:+ # SQLite drops tzinfo, so a naive read must be interpreted as UTC (the+ # column is stored tz-aware) rather than local time.+ from datetime import UTC++ dt = newest if newest.tzinfo is not None else newest.replace(tzinfo=UTC)+ since_ts = int(dt.timestamp())+ with timed(timings, "persist.commits.capture"):+ # One walk fills both, so they describe the same commit set.+ file_rows: list[dict] = []+ rows = await asyncio.to_thread(+ partial(+ indexer.capture_new_commit_rows,+ since_ts=since_ts,+ file_rows_sink=file_rows,+ )+ )+ if rows:+ await upsert_git_commits_bulk(session, repo_id, rows)+ if file_rows:+ await upsert_git_commit_files_bulk(session, repo_id, file_rows)+ await clear_attribution_if_disabled(session, repo_id)++ # What the new commits did to health is scanned by the caller once this+ # transaction commits (commit_health.refresh_commit_health_after_update):+ # the scan can take minutes and must not hold the write lock.++ with timed(timings, "persist.commits.experience"):+ await reconcile_commit_experience(session, repo_id, indexer)+ # Fills the commit-offset column on indexes written before it existed, so a+ # new capture never needs a re-index to become useful.+ with timed(timings, "persist.commits.offsets"):+ await reconcile_commit_offsets(session, repo_id, indexer)+ with timed(timings, "persist.commits.changes"):+ from repowise.core.changes.store import reconcile_categories, refresh_changes++ await refresh_changes(session, repo_id, repo_path, rebuild=False)+ try:+ await reconcile_categories(session, repo_id)+ except Exception as exc:+ logger.debug("category_reconcile_failed", error=str(exc))++ # Refresh the repo-level whole-history totals so age / commit / contributor+ # counts keep growing between full re-indexes (#730). Cheap git calls, and+ # cheap to run every update since they don't touch the bounded sample —+ # except lifetime churn, which walks the history. Handing the capture what+ # was stored last time lets it add only the range since, and it re-proves+ # that range is safe to add before doing so.+ prior = _churn_prior(await get_repository(session, repo_id))+ with timed(timings, "persist.commits.totals"):+ totals = await asyncio.to_thread(indexer.capture_repo_totals, prior)+ await update_repo_git_totals(+ session,+ repo_id,+ total_commit_count=totals.total_commit_count,+ total_merge_commit_count=totals.total_merge_commit_count,+ first_commit_at=totals.first_commit_at,+ total_contributor_count=totals.total_contributor_count,+ first_commit_author=totals.first_commit_author,+ first_commit_subject=totals.first_commit_subject,+ total_lines_added=totals.total_lines_added,+ total_lines_deleted=totals.total_lines_deleted,+ churn_anchor_sha=totals.churn_anchor_sha,+ )++ with timed(timings, "persist.commits.fix_events"):+ await persist_incremental_fix_events(session, repo_id, indexer)+++def _churn_prior(repo_row: Any) -> Any:+ """The stored totals lifetime churn can resume from, or ``None``.++ Only the four fields the fold reads are carried across, so this never+ becomes a second way to read repo-level git facts. ``None`` for a repo row+ that is missing or has no anchor yet, which makes the capture walk the whole+ history exactly as it always did.+ """+ from repowise.core.ingestion.git_indexer.records import RepoTotals++ if repo_row is None:+ return None+ anchor = getattr(repo_row, "churn_anchor_sha", None)+ if not anchor:+ return None+ return RepoTotals(+ total_commit_count=repo_row.total_commit_count,+ total_lines_added=repo_row.total_lines_added,+ total_lines_deleted=repo_row.total_lines_deleted,+ churn_anchor_sha=anchor,+ )+++async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any) -> None:+ """Re-tally author experience across the whole commit table and re-score.++ ``build_commit_rows`` can only count the commits it is handed. On a full+ index that is the entire window, so the number lands right; on an update it+ is just the commits newer than the last one persisted, so every author's+ count restarts at zero and an established author's new commits look like a+ first-timer's. That is not only a cosmetic badge: ``author_experience`` is a+ change-risk feature, so the stored ``change_risk_score`` inherits the error+ and the review queue ranks on it.++ Rather than seed the batch tally, this re-derives experience over the full+ persisted history after the append. The batch-local pass then has no lasting+ say, so there is no second code path to keep correct, and rows written by+ earlier (wrong) updates are repaired on the next one instead of waiting for+ a re-index.++ Two things have to happen together. Unreachable commits are dropped first:+ an update run on a feature branch persists that branch's shas, and once it+ is squash-merged they survive as orphans that no full index would produce+ and inflate every author's count. Then each surviving commit is re-scored+ from its stored features, because a corrected experience that leaves the old+ score in place would just move the inconsistency somewhere less visible.++ Bounded by the commit count and git-free apart from one ``rev-list``, and+ failure-isolated like the rest of the git-phase refreshes.+ """+ from repowise.core.persistence.crud import (+ delete_commit_health_by_sha,+ delete_git_commit_files_by_sha,+ delete_git_commits_by_sha,+ get_commit_experience_inputs,+ upsert_git_commits_bulk,+ )++ try:+ stored = await get_commit_experience_inputs(session, repo_id)+ if not stored:+ return++ reachable = await asyncio.to_thread(indexer.list_reachable_shas)+ if reachable is not None:+ orphans = [r["sha"] for r in stored if r["sha"] not in reachable]+ if orphans:+ await delete_git_commits_by_sha(session, repo_id, orphans)+ # Per-commit rows leave with their commit; nothing cascades them.+ await delete_git_commit_files_by_sha(session, repo_id, orphans)+ await delete_commit_health_by_sha(session, repo_id, orphans)+ stored = [r for r in stored if r["sha"] in reachable]+ logger.info("commit_orphans_pruned", repo_id=repo_id, count=len(orphans))++ updates = _recompute_commit_experience(stored)+ if updates:+ await upsert_git_commits_bulk(session, repo_id, updates)+ logger.info("commit_experience_reconciled", repo_id=repo_id, count=len(updates))+ except Exception as exc:+ logger.debug("commit_experience_reconcile_failed", error=str(exc))+++async def reconcile_commit_offsets(session: Any, repo_id: str, indexer: Any) -> None:+ """Backfill ``committed_offset_minutes`` on commits indexed before it existed.++ The offset is captured on the commit walk, so a full re-index gets it for+ free — but an update only writes rows for *new* commits, which would leave a+ repo indexed earlier with author-local hours on recent commits and UTC on+ everything older. A punch card mixing the two is worse than one that is+ honestly all-UTC, so the gap is closed here rather than waiting for a+ re-index nobody should have to run for a new column.++ One ``git log`` and one bulk update, both skipped entirely once the column+ is filled — the common case is a single cheap SELECT that returns nothing.+ Failure-isolated like the other update-time reconciles; an unfilled offset+ just means those rows keep falling back to UTC.+ """+ from repowise.core.persistence.crud import (+ get_commits_missing_offset,+ upsert_git_commits_bulk,+ )++ try:+ pending = await get_commits_missing_offset(session, repo_id)+ if not pending:+ return++ offsets = await asyncio.to_thread(indexer.capture_commit_offsets, pending)+ if not offsets:+ return++ await upsert_git_commits_bulk(+ session,+ repo_id,+ [{"sha": sha, "committed_offset_minutes": minutes} for sha, minutes in offsets.items()],+ )+ logger.info("commit_offsets_backfilled", repo_id=repo_id, count=len(offsets))+ except Exception as exc:+ logger.debug("commit_offset_reconcile_failed", error=str(exc))+++def _committed_ts(committed_at: Any) -> float:+ """``committed_at`` as a sortable epoch, or 0 when the row has no date.++ SQLite drops tzinfo, so a naive read has to be reinterpreted as UTC — the+ column is stored tz-aware. Doing that first also keeps ``timestamp()`` off+ the platform's local-time conversion, which fails outright on Windows for+ pre-epoch dates.+ """+ if committed_at is None:+ return 0.0+ from datetime import UTC++ if committed_at.tzinfo is None:+ committed_at = committed_at.replace(tzinfo=UTC)+ return committed_at.timestamp()+++def _recompute_commit_experience(stored: list[dict]) -> list[dict]:+ """Rows whose experience or risk moved, as partial upserts keyed by sha.++ Pure, so the ordering and re-scoring can be tested without a database.+ Emits only changed rows: on a settled index that is a handful, which keeps a+ whole-table read from turning into a whole-table write every update.+ """+ from repowise.core.analysis.change_risk import change_features_from_stored, score_change+ from repowise.core.ingestion.git_indexer.commit_rows import author_experience_by_sha++ exp_by_sha = author_experience_by_sha(+ [+ {+ "sha": r["sha"],+ "author_name": r["author_name"] or "",+ "author_email": r["author_email"] or "",+ # committed_at is the only ordering key the table stores; rows+ # without one sort oldest, which is where an unknown date least+ # disturbs everyone else's running count.+ "ts": _committed_ts(r["committed_at"]),+ }+ for r in stored+ ]+ )++ updates: list[dict] = []+ for r in stored:+ exp = exp_by_sha.get(r["sha"], 0)+ risk = score_change(+ change_features_from_stored(+ la=r["lines_added"],+ ld=r["lines_deleted"],+ nf=r["files_changed"],+ nd=r["dirs_changed"],+ ns=r["subsystems_changed"],+ entropy=r["entropy"],+ exp=exp,+ is_fix=r["is_fix"],+ author=r["author_name"],+ subject=r["subject"],+ ref=r["sha"],+ )+ )+ unchanged = (+ r["author_experience"] == exp+ and r["change_risk_level"] == risk.level+ and r["change_risk_score"] is not None+ and abs(r["change_risk_score"] - risk.score) < 1e-9+ )+ if unchanged:+ continue+ updates.append(+ {+ "sha": r["sha"],+ "author_experience": exp,+ "change_risk_score": risk.score,+ "change_risk_level": risk.level,+ }+ )+ return updates+++async def persist_incremental_fix_events(session: Any, repo_id: str, indexer: Any) -> None:+ """Trace + upsert ``fix_events`` for fix commits this index has not seen.++ Two halves, and both are needed for an update to converge on what a fresh+ index would produce: append the fix commits missing from the table, then drop+ the ones that have aged out of the trailing defect window. Without the prune+ the stored set only ever grows past the window's trailing edge; without the+ append it goes stale. Failure-isolated, like every other git-phase refresh.+ """+ from repowise.core.persistence.crud import (+ get_fix_event_shas,+ prune_fix_events_before,+ prune_fix_events_for_missing_paths,+ upsert_fix_events_bulk,+ )++ try:+ known = await get_fix_event_shas(session, repo_id)+ rows, oldest_ts, tracked = await asyncio.to_thread(+ indexer.capture_new_fix_events, known_shas=known+ )+ except Exception as exc:+ logger.debug("incremental_fix_events_failed", error=str(exc))+ return++ if rows:+ await upsert_fix_events_bulk(session, repo_id, rows)+ # A zero cutoff means the walk or the trace failed; pruning then would drop+ # rows nothing replaced.+ if oldest_ts:+ from datetime import UTC, datetime++ await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))+ if tracked:+ await prune_fix_events_for_missing_paths(session, repo_id, tracked)++ # Recompute over the whole stored window, not just the rows this update+ # appended: decay ages every file's mass whether or not the file changed.+ try:+ from repowise.core.pipeline.fix_rollups import apply_fix_rollups++ await apply_fix_rollups(session, repo_id)+ except Exception as exc:+ logger.debug("fix_rollups_failed", error=str(exc))diff --git a/packages/core/src/repowise/core/pipeline/incremental/external_systems.py b/packages/core/src/repowise/core/pipeline/incremental/external_systems.pynew file mode 100644index 000000000..52fae90fb--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/external_systems.py@@ -0,0 +1,72 @@+"""External-systems refresh when a dependency manifest changed."""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++from ._common import LogFn, _noop_log+++async def refresh_external_systems(+ session: Any,+ repo_id: str,+ repo_path: Any,+ file_diffs: list,+ *,+ log: LogFn | None = None,+) -> bool:+ """Re-extract + reconcile external systems (C4 L1) when a manifest changed.++ The incremental path historically never refreshed the ``external_systems``+ table, so the C4 architecture panel served the init-time dependency list+ until the next full re-index. Extraction is a bounded repo walk (no LLM, no+ network), so it is gated on an actual dependency-manifest change in this+ update's diff — the common no-manifest update pays nothing.++ When a manifest did change, the *whole* repo is re-extracted: it's cheap,+ and only a complete set supports a clean reconcile that also drops deps+ removed from a manifest. The table is then replaced (removed deps pruned)+ and ``external:{name}`` graph nodes re-linked so a brand-new dependency's+ node isn't left with a NULL FK.++ Ceiling: re-extraction walks the repo (depth ≤ 4) rather than parsing only+ the changed manifests — fine because it runs only on a manifest change and+ a partial parse can't see cross-manifest removals. Returns ``True`` when a+ refresh actually ran.+ """+ log = log or _noop_log+ from repowise.core.ingestion.external_systems import is_manifest_path++ if not any(is_manifest_path(fd.path) for fd in file_diffs or []):+ return False++ from repowise.core.ingestion.external_systems import extract_external_systems++ records = await asyncio.to_thread(extract_external_systems, Path(repo_path))+ systems = [+ {+ "name": r.name,+ "display_name": r.display_name,+ "ecosystem": r.ecosystem,+ "category": r.category,+ "io_kind": r.io_kind,+ "version": r.version,+ "declared_in": r.declared_in,+ "is_dev_dep": r.is_dev_dep,+ }+ for r in records+ ]++ from repowise.core.persistence.crud import (+ build_external_system_link_map,+ link_graph_nodes_to_external_systems,+ replace_external_systems,+ )++ id_map = await replace_external_systems(session, repo_id, systems)+ name_to_id = build_external_system_link_map(systems, id_map)+ await link_graph_nodes_to_external_systems(session, repo_id, name_to_id)+ log(f"External systems refreshed: [cyan]{len(systems)}[/cyan] deps")+ return Truediff --git a/packages/core/src/repowise/core/pipeline/incremental/graph.py b/packages/core/src/repowise/core/pipeline/incremental/graph.pynew file mode 100644index 000000000..d97d61913--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/graph.py@@ -0,0 +1,428 @@+"""Rebuild the repo graph and re-index git metadata for the changed files."""++from __future__ import annotations++from pathlib import Path+from typing import Any++from repowise.core.pipeline.phase_timing import PhaseTimings, timed++from ._common import LogFn, _noop_log, logger+++def build_filtered_changed_paths(file_diffs: list, exclude_patterns: list[str]) -> list[str]:+ """Extract paths from file_diffs, filtering out excluded patterns."""+ paths = [fd.path for fd in file_diffs]+ if not exclude_patterns:+ return paths+ import pathspec++ spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)+ return [p for p in paths if not spec.match_file(p)]+++def _record_structural_episodes(repo_path: Any, traverser: Any) -> None:+ """Best-effort structural episodes from the walk, without the formatter check."""+ try:+ from repowise.core.precedent.structural import record_structural_episodes++ record_structural_episodes(repo_path, traverser, allow_formatter_check=False)+ except Exception:+ pass+++def _parse_misses(+ cached_hits: dict[int, Any],+ to_parse: list,+ parse_cache: Any,+ timings: PhaseTimings | None,+) -> dict[int, Any]:+ """Parse the parse-cache misses and merge them over the cached hits by index."""+ from repowise.core.ingestion import ASTParser+ from repowise.core.pipeline.phases.ingestion import _cache_parsed++ parser: Any = None # constructed lazily — every-file-cached updates skip query compilation+ merged: dict[int, Any] = dict(cached_hits)+ with timed(timings, "rebuild.parse"):+ for idx, (fi, source), content_hash in to_parse:+ try:+ if parser is None:+ parser = ASTParser()+ parsed = parser.parse_file(fi, source)+ except Exception:+ continue+ merged[idx] = parsed+ if content_hash:+ _cache_parsed(parse_cache, parsed, content_hash)+ return merged+++def _add_parsed_files(+ graph_builder: Any,+ fi_and_bytes: list,+ merged: dict[int, Any],+ collect_sources: bool,+) -> tuple[list, dict[str, bytes], int]:+ """Add every parsed file to the graph, in read order.++ Returns ``(parsed_files, source_map, unparsed)``, where ``unparsed`` counts+ the read files that have no parse result.+ """+ parsed_files: list = []+ source_map: dict[str, bytes] = {}+ unparsed = 0+ for idx, (fi, source) in enumerate(fi_and_bytes):+ parsed = merged.get(idx)+ if parsed is None:+ unparsed += 1+ continue+ parsed_files.append(parsed)+ if collect_sources:+ source_map[fi.path] = source+ graph_builder.add_file(parsed)+ return parsed_files, source_map, unparsed+++def _add_synthetic_edges(+ repo_path: Any,+ graph_builder: Any,+ file_infos: list,+ source_map: dict[str, bytes],+ log: LogFn,+ timings: PhaseTimings | None,+) -> None:+ """Add the framework-aware and dynamic-hint edges to a built graph."""+ # Add framework-aware synthetic edges (conftest, Django, FastAPI, Flask).+ # Best-effort, but not silent: the update path has to report the failure the+ # init path reports, or an index degrades differently depending on how it+ # was built and nothing says which.+ try:+ from repowise.core.generation.editor_files.tech_stack import detect_tech_stack++ with timed(timings, "rebuild.framework"):+ tech_items = detect_tech_stack(repo_path)+ fw_count = graph_builder.add_framework_edges([item.name for item in tech_items])+ if fw_count:+ log(f"Framework edges added: [cyan]{fw_count}[/cyan]")+ except Exception as fw_exc:+ logger.warning("framework_edges_failed", error=str(fw_exc))+ log(+ f"[yellow]Framework edge detection skipped: {fw_exc}; framework-invoked "+ "symbols will have no callers in the graph and may read as dead.[/yellow]"+ )++ # Add dynamic-hint edges, mirroring the init pipeline's ingestion phase.+ # Without this the update-built graph was missing every dynamic edge the+ # init graph had: metrics computed on update diverged from init's, and+ # the first post-init update could never hit the centrality cache.+ try:+ from repowise.core.ingestion.dynamic_hints import HintRegistry++ with timed(timings, "rebuild.dynamic_hints"):+ dynamic_edges = HintRegistry().extract_all(+ Path(repo_path),+ dotnet_index=graph_builder.dotnet_index,+ file_paths=[fi.path for fi in file_infos],+ source_map=source_map or None,+ )+ graph_builder.add_dynamic_edges(dynamic_edges)+ if dynamic_edges:+ log(f"Dynamic hint edges added: [cyan]{len(dynamic_edges)}[/cyan]")++ except Exception as exc:+ logger.warning("dynamic_hints_extraction_failed", error=str(exc))+ log(+ f"[yellow]Dynamic hint extraction failed: {exc}. Dynamic edges"+ "will be missing from this update.[/yellow]"+ )+++def build_repo_graph(+ repo_path: Any,+ exclude_patterns: list[str],+ *,+ collect_sources: bool = False,+ include_submodules: bool = False,+ include_nested_repos: bool = False,+ log: LogFn | None = None,+ timings: PhaseTimings | None = None,+ read_only: bool = False,+) -> tuple[list, dict[str, bytes], Any, Any, int]:+ """Traverse + parse the repo and build the graph (+ framework-aware edges).++ Shared by the incremental rebuild path (:func:`rebuild_graph_and_git`),+ the config-triggered re-score path and the commands that analyze the+ working tree live, so all of them build the same graph from the same+ parser and the same synthetic edge steps.++ ``read_only`` is for those live commands: the parse cache is read but+ never written, and no structural episodes or centrality cache are kept.++ Files that fail to read/parse are skipped and reported as a count rather than+ swallowed silently. ``source_map`` is populated only when ``collect_sources``+ is set; every path that persists the graph sets it, since the framework-edge+pass reads the sources.++ ``timings`` is the run's shared :class:`PhaseTimings` table; each step+ below records into it under a ``rebuild.*`` name. ``None`` records nothing.++ Returns ``(parsed_files, source_map, graph_builder, repo_structure,+ file_count)``.+ """+ import os+ from concurrent.futures import ThreadPoolExecutor++ from repowise.core.ingestion import FileTraverser, GraphBuilder++ log = log or _noop_log++ traverser = FileTraverser(+ repo_path,+ extra_exclude_patterns=exclude_patterns or None,+ include_submodules=include_submodules,+ include_nested_repos=include_nested_repos,+ )+ # Parallel stat + header sniffing, mirroring the init ingestion phase.+ # A serial traverse() pays per-file I/O latency sequentially; on a cold+ # OS file cache that was ~50s of every PowerToys-scale update. Passing+ # the file_infos into get_repo_structure also avoids its re-walk.+ with timed(timings, "rebuild.traverse"):+ all_paths = list(traverser._walk())+ io_workers = min(32, max(4, (os.cpu_count() or 4) * 2))+ with ThreadPoolExecutor(max_workers=io_workers) as io_pool:+ maybe_infos = list(io_pool.map(traverser._build_file_info, all_paths))+ file_infos = [fi for fi in maybe_infos if fi is not None]+ repo_structure = traverser.get_repo_structure(file_infos)++ # Structural episodes, minus the formatter check: this path is the hot one+ # (every update, plus the config-triggered re-score), so it derives only+ # what the walk has already paid for and never spawns a subprocess.+ if not read_only:+ _record_structural_episodes(repo_path, traverser)++ # Thread-pool source reads + content-hash parse cache split, shared with+ # the init parse phase: only changed files need a tree-sitter parse.+ # Cache failures degrade to all-miss (full parse), as before.+ from repowise.core.pipeline.phases.ingestion import (+ _read_sources,+ _split_cached,+ )+ from repowise.core.workspace.update import get_head_commit++ with timed(timings, "rebuild.read"):+ fi_and_bytes = _read_sources(file_infos, None)+ parse_cache, cached_hits, to_parse = _split_cached(Path(repo_path), fi_and_bytes, None)+ if read_only:+ parse_cache = None # hits above still count; misses are not stored++ graph_builder = GraphBuilder(+ repo_path,+ exclude_patterns=exclude_patterns,+ centrality_cache_dir=None if read_only else Path(repo_path) / ".repowise",+ head_commit=get_head_commit(Path(repo_path)),+ include_submodules=include_submodules,+ include_nested_repos=include_nested_repos,+ )+ graph_builder.console_scripts = traverser.console_script_names+ # Carry the walk's skip record to the dead-code analyzer. This report is+ # persisted repo-wide, so an update that could not see the skipped source+ # files would re-derive and write back the verdicts init had clamped.+ graph_builder.traversal_stats = traverser.stats+ # Reconciliation authority is the successful traversal, not the successful+ # parse set. A transient read/parser failure must not make an existing+ # in-scope file look deleted and prune its persisted rows.+ graph_builder.traversed_file_paths = {+ file_info.path for file_info in file_infos+ }++ # Parse the misses in process and serially: on the update path they are+ # change-sized. (Ceiling: a wiped/stale cache re-parses everything on one+ # core; routing large miss counts through init's process pool would lift+ # it, at the cost of Windows spawn overhead on every routine update.)+ merged = _parse_misses(cached_hits, to_parse, parse_cache, timings)++ skipped = len(file_infos) - len(fi_and_bytes) # unreadable files+ # Opened here and closed after build(): graph construction is the add_file+ # loop plus the resolver, and the tsconfig wiring sits between them.+ if timings is not None:+ timings.start("rebuild.graph")+ parsed_files, source_map, unparsed = _add_parsed_files(+ graph_builder, fi_and_bytes, merged, collect_sources+ )+ skipped += unparsed++ # TS/JS path aliases (``@/components/...``) resolve only when the+ # tsconfig resolver is attached before build(); without it the alias+ # targets read as external nodes and every aliased file looks+ # unreachable to the dead-code analyzer (#648 — this rebuild path was+ # missed when the CLI commands were wired).+ from repowise.core.ingestion import wire_tsconfig_resolver++ wire_tsconfig_resolver(+ graph_builder,+ repo_path,+ include_submodules=include_submodules,+ include_nested_repos=include_nested_repos,+ )+ graph_builder.set_source_map(source_map)+ graph_builder.set_pytest_roots(traverser.pytest_roots)+ graph_builder.build()+ if timings is not None:+ timings.stop("rebuild.graph")+ if parse_cache is not None:+ with timed(timings, "rebuild.cache_save"):+ parse_cache.save()++ if skipped:+ log(f"[yellow]Skipped {skipped} file(s) that failed to parse.[/yellow]")++ _add_synthetic_edges(repo_path, graph_builder, file_infos, source_map, log, timings)++ return parsed_files, source_map, graph_builder, repo_structure, len(file_infos)+++async def rebuild_graph_and_git(+ repo_path: Any,+ file_diffs: list,+ cfg: dict,+ exclude_patterns: list[str],+ *,+ git_tier: str | None = None,+ include_submodules: bool = False,+ include_nested_repos: bool = False,+ idle_decay_sink: dict[str, dict] | None = None,+ force_full_git: bool = False,+ git_summary_sink: list[Any] | None = None,+ log: LogFn | None = None,+ timings: PhaseTimings | None = None,+) -> tuple[list, dict[str, bytes], Any, Any, int, dict[str, dict]]:+ """Re-traverse + parse the repo, rebuild the graph (+ framework edges), and+ re-index git metadata for the changed files.++ ``timings`` records the whole step as ``rebuild`` plus one ``rebuild.*``+ row per sub-step, so a slow update names the stage that made it slow.++ ``idle_decay_sink``, when provided, is filled with a decay-only partial+ metadata row for every idle (unchanged) file whose time-decayed history+ fields the anchor advance moved (issue #728). These rows are for the git+ persist step only — they are deliberately kept out of the returned+ ``git_meta_map`` so the partial health analysis (whose repo-wide aggregates+ read every entry) is unaffected.++ ``git_tier`` is the persisted ``state.json:git_tier`` value: a fast-mode+ (ESSENTIAL) repo must not pay per-file blame on every update for signals+ its index never had. Unknown/missing values fall back to FULL, matching+ the historical behavior for legacy state files.++ ``include_submodules`` / ``include_nested_repos`` are likewise read from+ state.json: a repo indexed with ``init --include-submodules`` must not+ silently drop its submodule files on every incremental update. Missing+ keys fall back to False (legacy behavior).++ ``force_full_git`` is reserved for changes to Git-history/traversal+ configuration. Those settings invalidate every per-file row, not merely+ files in the commit diff. The optional sink carries the resulting summary+ to persistence so per-commit/fix-event rows can be replaced from the same+ walk.++ Returns ``(parsed_files, source_map, graph_builder, repo_structure,+ file_count, git_meta_map)``.+ """+ log = log or _noop_log+ if timings is not None:+ timings.start("rebuild")++ # Full re-ingest for graph (needed for cascade analysis)+ parsed_files, source_map, graph_builder, repo_structure, file_count = build_repo_graph(+ repo_path,+ exclude_patterns,+ collect_sources=True,+ include_submodules=include_submodules,+ include_nested_repos=include_nested_repos,+ log=log,+ timings=timings,+ )++ # Re-index git metadata for changed files+ git_meta_map: dict[str, dict] = {}+ if timings is not None:+ timings.start("rebuild.git")+ try:+ from repowise.core.ingestion.git_indexer import GitIndexer+ from repowise.core.ingestion.git_indexer.tiers import GitIndexTier+ from repowise.core.pipeline.phases.git import label_co_change_structure++ try:+ tier = GitIndexTier(git_tier) if git_tier else GitIndexTier.FULL+ except ValueError:+ tier = GitIndexTier.FULL+ _commit_limit = cfg.get("commit_limit")+ _follow_renames = cfg.get("follow_renames", False)+ git_indexer = GitIndexer(+ repo_path,+ commit_limit=_commit_limit,+ follow_renames=_follow_renames,+ exclude_patterns=exclude_patterns or None,+ tier=tier,+ )+ if force_full_git:+ summary, updated_meta = await git_indexer.index_repo(repo_path.name, on_warning=log)+ if git_summary_sink is not None:+ git_summary_sink.append(summary)+ git_meta_map = {m["file_path"]: m for m in updated_meta}+ label_co_change_structure(graph_builder, git_meta_map)+ graph_builder.update_co_change_edges(git_meta_map)+ else:+ changed_paths = build_filtered_changed_paths(file_diffs, exclude_patterns)+ # The full tracked-file set lets the indexer re-run the repo-wide+ # co-change walk so partners aren't wiped to "[]" for changed files.+ # The sink captures that walk's FULL per-file partner map: the graph+ # was just rebuilt from scratch, so co_changes edges must be re-added+ # for every file (not only the changed ones) or the update graph+ # diverges from the init graph and the centrality cache can't hit.+ co_change_full: dict[str, list[dict]] = {}+ updated_meta = await git_indexer.index_changed_files(+ changed_paths,+ all_files=set(source_map.keys()),+ co_change_sink=co_change_full,+ idle_decay_sink=idle_decay_sink,+ on_warning=log,+ timings=timings,+ )+ git_meta_map = {m["file_path"]: m for m in updated_meta}+ label_co_change_structure(graph_builder, git_meta_map)+ if idle_decay_sink:+ # Idle rows carry the same column and are persisted on their own+ # path, having been serialized before the graph existed.+ label_co_change_structure(graph_builder, idle_decay_sink)+ if co_change_full:+ graph_builder.update_co_change_edges(+ {+ fp: {"co_change_partners_json": partners}+ for fp, partners in co_change_full.items()+ }+ )+ else:+ graph_builder.update_co_change_edges(git_meta_map)+ except Exception as exc:+ log(f"[yellow]Git re-index skipped: {exc}[/yellow]")+ if force_full_git:+ raise+ finally:+ if timings is not None:+ timings.stop("rebuild.git")++ # Pre-compute centrality/community metrics with the init path's fan-out+ # parallelism. Without this, persist_graph_nodes computes the same+ # metrics lazily one-by-one. Runs after the co-change edge refresh so+ # the cached subgraphs reflect the final structure. Best-effort: every+ # metric still falls back to lazy computation.+ try:+ with timed(timings, "rebuild.metrics"):+ await graph_builder.compute_metrics_parallel()+ except Exception as exc:+ log(f"[yellow]Metric pre-computation skipped: {exc}[/yellow]")++ if timings is not None:+ timings.stop("rebuild")+ return parsed_files, source_map, graph_builder, repo_structure, file_count, git_meta_mapdiff --git a/packages/core/src/repowise/core/pipeline/incremental/health.py b/packages/core/src/repowise/core/pipeline/incremental/health.pynew file mode 100644index 000000000..8d92b1fe8--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/health.py@@ -0,0 +1,336 @@+"""Partial health persistence and the history refresh of unchanged files."""++from __future__ import annotations++from typing import Any++from ._common import logger+++async def refresh_unchanged_history(+ session: Any, repo_id: str, repo_path: Any, *, skip_paths: set[str]+) -> int:+ """Re-score the git-derived markers on files this run did not walk.++ The update refreshes git metadata for the whole repository, so a file the+ change set never touched can still have moved in every way history+ measures — new co-change partners, a fix that landed elsewhere in the same+ commit, an owner who left. Only those markers are re-evaluated; each file+ keeps the structural findings its last parse produced, so nothing here+ needs the source.++ Returns the number of files rewritten. Best-effort: the update is not worth+ failing over a refresh.+ """+ from repowise.core.analysis.health.config import HealthConfig+ from repowise.core.analysis.health.history_refresh import (+ REFRESHABLE_MARKERS,+ active_contributors,+ git_meta_rows_to_map,+ refresh_history,+ )+ from repowise.core.persistence.crud import (+ get_all_git_metadata,+ get_file_language_map,+ get_health_findings,+ get_health_metrics,+ upsert_health_findings,+ upsert_health_metrics,+ )+ from repowise.core.pipeline.persist import _analyzed_commit++ stored = {+ m.file_path: m+ for m in await get_health_metrics(session, repo_id)+ if m.file_path not in skip_paths+ }+ if not stored:+ return 0+ git_meta = git_meta_rows_to_map((await get_all_git_metadata(session, repo_id)).values())+ if not git_meta:+ return 0++ findings_by_path: dict[str, list[Any]] = {}+ for finding in await get_health_findings(session, repo_id, include_withheld=True):+ findings_by_path.setdefault(finding.file_path, []).append(finding)++ cfg = HealthConfig.load(repo_path)+ refreshed = refresh_history(+ metrics=list(stored.values()),+ findings_by_path=findings_by_path,+ git_meta_by_path=git_meta,+ languages=await get_file_language_map(session, repo_id),+ repo_active_contributors_90d=active_contributors(git_meta),+ severity_overrides=cfg.severity_overrides or None,+ )+ if not refreshed:+ return 0++ # The two writes are scoped separately on purpose. A metric row is cheap to+ # rewrite and carries no identity, but rewriting findings deletes and+ # re-inserts them, which means new ids and a reset ``created_at`` — so that+ # only happens for a file whose history findings actually changed, not for+ # every file whose stored split was merely never recorded.+ commit = await _analyzed_commit(session, repo_id)+ metric_writes = [+ _refreshed_metric(r, stored[r.file_path], commit)+ for r in refreshed+ if _numbers_moved(r, stored[r.file_path])+ ]+ finding_writes = [+ r for r in refreshed if _history_findings_moved(r, findings_by_path.get(r.file_path, []))+ ]+ if not metric_writes and not finding_writes:+ return 0++ # One savepoint over both: a file whose findings were rewritten but whose+ # score was not would report a deduction its own findings cannot account+ # for, and the caller logs this step and carries on to commit the rest.+ async with session.begin_nested():+ if finding_writes:+ await upsert_health_findings(+ session,+ repo_id,+ [f for r in finding_writes for f in r.findings],+ file_paths=[r.file_path for r in finding_writes],+ )+ if metric_writes:+ await upsert_health_metrics(session, repo_id, metric_writes)+ logger.debug(+ "health_history_refreshed",+ repo_id=repo_id,+ metric_rows=len(metric_writes),+ finding_rows=len(finding_writes),+ markers=len(REFRESHABLE_MARKERS),+ )+ return len(finding_writes)+++def _numbers_moved(refreshed: Any, stored: Any) -> bool:+ """Whether the stored row's numbers differ from the re-scored ones.++ Includes a row whose split was never recorded, so the first update after+ the split ships backfills it without touching any finding.+ """+ return (+ _differs(refreshed.score, stored.score, 2)+ or _differs(refreshed.structure_deduction, stored.structure_deduction, 3)+ or _differs(refreshed.history_deduction, stored.history_deduction, 3)+ )+++def _differs(new: float | None, old: float | None, places: int) -> bool:+ """``None`` is a value here: a file that is no longer scored has moved."""+ if new is None or old is None:+ return (new is None) != (old is None)+ return round(new, places) != round(float(old), places)+++def _history_findings_moved(refreshed: Any, stored_findings: list[Any]) -> bool:+ """Whether the git-derived findings themselves changed.++ Compared on what a reader sees — which markers fired, where, and how+ severely — so a file keeps its finding ids and their ages across an update+ that re-derived the same history.+ """++ def key(findings: Any) -> set:+ return {+ (+ getattr(f, "biomarker_type", ""),+ str(getattr(f, "severity", "")),+ getattr(f, "function_name", None),+ round(float(getattr(f, "health_impact", 0.0) or 0.0), 3),+ )+ for f in findings+ }++ return key(refreshed.findings) != key(stored_findings)+++def _refreshed_metric(refreshed: Any, stored: Any, commit: str | None) -> dict:+ """The stored metric row with the rescored numbers written over it.++ A dict rather than a dataclass so the fields this pass cannot know — the+ complexity and coverage columns, which need a parse — keep their stored+ values instead of being reset to a default.++ ``commit`` is the one the row was rescored against: its history is read at+ it, and the file is unchanged since its last parse. Keeping the old stamp+ made the newest row name a commit 100 behind, which the health basis+ reads. Set here, not as the writer's default, so an unreadable HEAD+ clears the stamp: "not recorded" is honest and the old commit is not.+ """+ # A file health never walked carries no complexity figures either, which+ # also clears the ones a store written before that rule kept.+ walked = refreshed.score is not None+ return {+ "file_path": refreshed.file_path,+ "analyzed_commit": commit,+ "score": refreshed.score,+ "max_ccn": stored.max_ccn if walked else None,+ "max_nesting": stored.max_nesting if walked else None,+ "nloc": stored.nloc,+ "duplication_pct": stored.duplication_pct,+ "has_test_file": stored.has_test_file,+ "line_coverage_pct": stored.line_coverage_pct,+ "branch_coverage_pct": stored.branch_coverage_pct,+ "module": stored.module,+ "defect_score": refreshed.defect_score,+ "maintainability_score": refreshed.maintainability_score,+ "performance_score": refreshed.performance_score,+ "structure_deduction": refreshed.structure_deduction,+ "history_deduction": refreshed.history_deduction,+ "is_test": stored.is_test,+ "code_origin": getattr(stored, "code_origin", None),+ }+++async def persist_partial_health(+ session: Any, repo_id: str, report: Any, repo_path: Any = None+) -> None:+ """Upsert health findings + metrics for the changed-files subset.++ Unlike ``persist_pipeline_result`` (which delete-then-inserts the+ whole repo), this writer only touches rows whose ``file_path`` is in+ the partial report — so unchanged files keep their existing findings+ and metrics across an incremental ``repowise update``.+ """+ from repowise.core.persistence.crud import (+ PayoffContext,+ finalize_performance_opportunities,+ finalize_refactoring_opportunities,+ upsert_health_findings,+ upsert_health_metrics,+ upsert_refactoring_suggestions,+ write_function_facts,+ )+ from repowise.core.pipeline.persist import _analyzed_commit, path_liveness++ changed_paths = sorted(+ set(getattr(report, "authoritative_paths", None) or ())+ or {m.file_path for m in report.metrics or []}+ )+ performance_paths = sorted(+ set(getattr(report, "performance_authoritative_paths", None) or ()) - set(changed_paths)+ )+ # Nothing analysed: a deletion-only update runs no health analysis, so it+ # has no role map to restamp stored roles with. Roles, like performance+ # findings, refresh on the next run that analyses any file.+ if not changed_paths and not performance_paths:+ return+ analyzed_commit = await _analyzed_commit(session, repo_id)+ # One savepoint over the findings and everything derived from them. This+ # writer's caller logs a failed step and carries on to commit the rest of+ # the run, so without the savepoint a rebuild that failed halfway would+ # leave the queue describing findings that were never stored.+ async with session.begin_nested():+ if changed_paths:+ await upsert_health_metrics(+ session,+ repo_id,+ report.metrics or [],+ analyzed_commit=analyzed_commit,+ )+ await upsert_health_findings(+ session, repo_id, list(report.findings or []), file_paths=changed_paths+ )+ if performance_paths:+ await upsert_health_findings(+ session,+ repo_id,+ list(report.findings or []),+ file_paths=performance_paths,+ dimension="performance",+ )+ # Refactoring suggestions for the changed files only (unchanged files+ # keep theirs). Scoped reconciliation across the full changed-file set,+ # so a file that became clean has its plans resolved rather than left+ # standing, and a plan that survived the edit keeps its id.+ if changed_paths:+ await upsert_refactoring_suggestions(+ session,+ repo_id,+ [+ suggestion+ for suggestion in (getattr(report, "refactoring_suggestions", None) or [])+ if suggestion.refactoring_type != "performance_fix"+ ],+ file_paths=changed_paths,+ # Before the facts below replace the stored ones: those are the+ # measures a resolved plan was detected against.+ payoff=PayoffContext(+ fact_rows=getattr(report, "function_facts", None),+ is_live=path_liveness(repo_path),+ commit=analyzed_commit,+ ),+ )+ # Facts for the files this run walked; roles and nearest tests for every+ # stored row, written only where they moved. No rows means no graph to+ # key them on: the stored ones stay. Before the finalizers, which read+ # each plan's nearest tests off these rows.+ fact_rows = getattr(report, "function_facts", None)+ if fact_rows is not None:+ await write_function_facts(+ session,+ repo_id,+ fact_rows,+ file_paths={*changed_paths, *performance_paths},+ roles=getattr(report, "execution_roles", None),+ tests=getattr(report, "function_tests", None),+ )+ # A partial run sees a subset of the findings, so the plans and the+ # queue it would derive are a subset too. Both are rebuilt here instead,+ # from the merged stored rows, by the same writer the full path uses.+ # That is what makes the two paths agree, and it retires the file-scoped+ # plan bookkeeping that used to try to reach a shared intervention from+ # its callers.+ await finalize_performance_opportunities(+ session,+ repo_id,+ analyzed_commit=analyzed_commit,+ plan_policy=getattr(report, "performance_plan_policy", None),+ execution_roles=getattr(report, "execution_roles", None),+ )+ # Repository-wide, like the queue above and for the same reason: an+ # opportunity folds a file's plans, and a file this run did not touch+ # can still lose one when a cross-file plan elsewhere resolves.+ await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)+ # Per-function blame rollup for the changed files (keeps git_function_blame+ # current between full indexes; FULL git tier only — empty otherwise).+ fn_blame_rows = getattr(report, "function_blame_rows", None)+ if fn_blame_rows:+ from repowise.core.persistence.crud import upsert_git_function_blame_bulk++ await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)+ # Only a full index rewrites the whole population, so rows an older version+ # scored for prose or configuration go here rather than lingering in the+ # average, and rows written before ``is_test`` existed get it from their+ # path. Both before the refresh, which should not re-score a row that is+ # about to be deleted.+ from repowise.core.persistence.crud import (+ backfill_is_test,+ clear_unanalysed_scores,+ prune_unscored_health_rows,+ )++ await prune_unscored_health_rows(session, repo_id)+ await clear_unanalysed_scores(session, repo_id)+ await backfill_is_test(session, repo_id)+ # Then the files this run did not walk, whose git-derived markers the fresh+ # metadata may have moved. Before the snapshot, or the trend would describe+ # the store as it stood one update ago.+ if repo_path is not None:+ try:+ await refresh_unchanged_history(+ session, repo_id, repo_path, skip_paths=set(changed_paths)+ )+ except Exception as exc:+ # Never fails the run: the next update re-derives the whole thing+ # from the stored git metadata, so nothing is stranded behind.+ logger.debug("health_history_refresh_skipped", repo_id=repo_id, error=str(exc))+ # The store now holds the merged repository, so the snapshot describes the+ # whole of it, not this run's changed files.+ from repowise.core.pipeline.persist import snapshot_health_from_store++ await snapshot_health_from_store(session, repo_id)diff --git a/packages/core/src/repowise/core/pipeline/incremental/knowledge_graph.py b/packages/core/src/repowise/core/pipeline/incremental/knowledge_graph.pynew file mode 100644index 000000000..64e9fe18f--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/knowledge_graph.py@@ -0,0 +1,140 @@+"""Knowledge-graph refresh for an incremental run."""++from __future__ import annotations++from pathlib import Path+from typing import Any++from ._common import LogFn, _noop_log+++async def refresh_knowledge_graph(+ repo_path: Any,+ parsed_files: list,+ graph_builder: Any,+ repo_structure: Any,+ git_meta_map: dict,+ dead_code_report: Any,+ *,+ prior_fingerprint: str | None,+ log: LogFn | None = None,+) -> Any | None:+ """Rebuild the KG skeleton + curation when the graph shape changed.++ The knowledge graph (layers, tour, entry points, curated node meta) was+ historically rebuilt only by the full init pipeline, so every incremental+ ``repowise update`` carried the init-time KG forward verbatim and agents+ read a stale orientation snapshot (#669). This reruns the deterministic+ skeleton + curation passes against the freshly rebuilt graph, then carries+ forward the prior artifact's LLM-enriched layer names and node summaries+ by stable id — so index-only updates stay LLM-free without regressing+ enrichment. LLM re-enrichment stays with the caller (docs mode only).++ Returns the refreshed result, or ``None`` when the graph fingerprint is+ unchanged (the persisted artifact is already current) or the rebuild+ failed (keep the prior artifact rather than export a broken one).+ """+ log = log or _noop_log+ try:+ from repowise.core.analysis.knowledge_graph import (+ KnowledgeGraphResult,+ build_knowledge_graph_skeleton,+ compute_kg_fingerprint,+ should_skip_kg_rebuild,+ )++ kg_json_path = Path(repo_path) / ".repowise" / "knowledge-graph.json"+ new_fingerprint = compute_kg_fingerprint(graph_builder)+ if should_skip_kg_rebuild(prior_fingerprint, new_fingerprint, kg_json_path):+ return None++ tech_stack: list[dict] = []+ try:+ from repowise.core.generation.editor_files.tech_stack import detect_tech_stack++ tech_stack = [+ {"name": t.name, "version": t.version, "category": t.category}+ for t in detect_tech_stack(repo_path)+ ]+ except Exception:+ pass # tech stack is contextual metadata, not structural++ prior_kg = KnowledgeGraphResult.from_file(kg_json_path)++ kg = build_knowledge_graph_skeleton(+ parsed_files=parsed_files,+ graph_builder=graph_builder,+ repo_structure=repo_structure,+ tech_stack=tech_stack,+ external_systems=[],+ git_meta_map=git_meta_map,+ dead_code_report=dead_code_report,+ repo_path=Path(repo_path),+ )+ kg.fingerprint = new_fingerprint++ from repowise.core.analysis.kg_curation import (+ apply_summary_floor,+ curate_knowledge_graph,+ curation_enabled,+ )++ kg = curate_knowledge_graph(+ kg,+ parsed_files=parsed_files,+ graph_builder=graph_builder,+ repo_structure=repo_structure,+ community_info=graph_builder.community_info(),+ git_meta_map=git_meta_map,+ enabled=curation_enabled(),+ # Floor after the prior-artifact carry-forward below so carried+ # page-derived summaries win over the deterministic floor.+ defer_summary_floor=True,+ )++ if prior_kg is not None:+ _carry_forward_kg_enrichment(kg, prior_kg)++ # Summaries degrade to empty on failure, same as the init-path seam.+ import contextlib++ with contextlib.suppress(Exception):+ apply_summary_floor(kg, parsed_files)++ log(+ f"Knowledge graph refreshed: [cyan]{len(kg.layers)}[/cyan] layers, "+ f"[cyan]{len(kg.tour)}[/cyan] tour steps"+ )+ return kg+ except Exception as exc:+ log(f"[yellow]Knowledge-graph refresh skipped: {exc}[/yellow]")+ return None+++def _carry_forward_kg_enrichment(kg: Any, prior_kg: Any) -> None:+ """Adopt the prior artifact's LLM-enriched prose onto the rebuilt KG.++ Matching is by stable id, and only fields the deterministic passes left+ empty are filled — structural changes always win over stale prose. Layer+ descriptions exist only after LLM enrichment (curation names layers but+ leaves descriptions empty), so a non-empty prior description is the+ signal that the prior name/description pair is the enriched one.+ """+ prior_layers = {layer.get("id"): layer for layer in prior_kg.layers or []}+ for layer in kg.layers or []:+ prior = prior_layers.get(layer.get("id"))+ if prior and prior.get("description") and not layer.get("description"):+ layer["name"] = prior.get("name") or layer.get("name")+ layer["description"] = prior["description"]++ prior_summaries = {n.get("id"): n["summary"] for n in prior_kg.nodes or [] if n.get("summary")}+ for node in kg.nodes or []:+ if not node.get("summary"):+ prior_summary = prior_summaries.get(node.get("id"))+ if prior_summary:+ node["summary"] = prior_summary++ # With curation disabled the skeleton carries no tour and only the LLM+ # path builds one — keep the prior tour rather than exporting none.+ if not kg.tour and prior_kg.tour:+ kg.tour = prior_kg.tourdiff --git a/packages/core/src/repowise/core/pipeline/incremental/loaders.py b/packages/core/src/repowise/core/pipeline/incremental/loaders.pynew file mode 100644index 000000000..ca560fe21--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/loaders.py@@ -0,0 +1,233 @@+"""Reads of the stored index that the incremental analysis scores against."""++from __future__ import annotations++from pathlib import Path+from typing import Any++from ._common import LogFn, _noop_log+++async def load_stored_git_meta(+ repo_path: Any, *, log: LogFn | None = None+) -> dict[str, dict] | None:+ """Read the persisted per-file git fields the dead-code analyzer scores on.++ Returns ``None`` when the store could not be read, and a mapping (possibly+ an empty one) when it could. The caller has to tell those apart: an empty+ mapping is a repository whose ``git_metadata`` genuinely holds nothing,+ which scores exactly the way a full index would score it, whereas a failed+ read means this run knows less than a full index does and must not+ overwrite what a full index wrote.++ Not every indexed file has a row even on a healthy repository — ``git+ metadata`` covers what ``index_repo`` produced, which excludes skipped+ paths — so a *missing file* is not evidence of a failure and a coverage+ count cannot stand in for one.+ """+ log = log or _noop_log+ # Never create the store as a side effect of reading it. A repo whose+ # wiki.db was deleted to force a rebuild would otherwise be handed an+ # empty one here, and an empty database reads as "indexed" downstream.+ # Same guard, and the same reason, as the head-commit stamper.+ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():+ log("[yellow]No store to read git metadata from; dead-code scope narrowed[/yellow]")+ return None+ try:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_dead_code_git_fields,+ get_session,+ )+ from repowise.core.persistence.crud import get_repository_by_path+ from repowise.core.persistence.database import resolve_db_url++ engine = create_engine(resolve_db_url(repo_path))+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ # The persist path resolves the repository with an upsert,+ # so a miss here means this run would be writing against a+ # row that does not exist yet. Unknown, not empty.+ log(+ f"[yellow]No stored repository for {repo_path}; "+ "dead-code scope narrowed[/yellow]"+ )+ return None+ return await get_dead_code_git_fields(session, repo.id)+ finally:+ await engine.dispose()+ except Exception as exc:+ log(f"[yellow]Stored git metadata unavailable for dead-code scoring: {exc}[/yellow]")+ return None+++async def load_stored_performance_callers(+ repo_path: Any,+ changed_paths: set[str],+ *,+ log: LogFn | None = None,+) -> set[str] | None:+ """Load callers whose persisted performance paths touched changed files.++ The current graph cannot retain an edge to a deleted or renamed symbol.+ One bounded store read supplies that old-side reverse evidence so partial+ analysis can remove stale caller findings. ``None`` means the store was+ unavailable and therefore must not widen authoritative persistence scope.+ """+ log = log or _noop_log+ if not changed_paths:+ return set()+ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():+ return None+ try:+ import json++ from sqlalchemy import select++ from repowise.core.persistence import create_engine, get_session+ from repowise.core.persistence.crud import get_repository_by_path+ from repowise.core.persistence.database import (+ create_session_factory,+ resolve_db_url,+ )+ from repowise.core.persistence.models import HealthFinding++ engine = create_engine(resolve_db_url(repo_path))+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return None+ rows = (+ await session.execute(+ select(HealthFinding.file_path, HealthFinding.details_json).where(+ HealthFinding.repository_id == repo.id,+ HealthFinding.status == "open",+ HealthFinding.dimension == "performance",+ )+ )+ ).all()+ finally:+ await engine.dispose()+ callers: set[str] = set()+ for file_path, details_json in rows:+ try:+ path = json.loads(details_json or "{}").get("path", ())+ except (TypeError, ValueError, AttributeError):+ continue+ if any(+ isinstance(node, str) and node.split("::", 1)[0] in changed_paths for node in path+ ):+ callers.add(file_path)+ return callers+ except Exception as exc:+ log(f"[yellow]Stored performance callers unavailable: {exc}[/yellow]")+ return None+++async def load_stored_function_mod_p80(repo_path: Any, *, log: LogFn | None = None) -> int | None:+ """Load the repo-wide p80 of per-function modification counts.++ Computed from the persisted ``git_function_blame`` rollup, which a FULL+ index writes for every modified function. The incremental health pass+ reuses this value so the Function Hotspot gate is scored against the+ full repo rather than the churn-heavy changed-files subset (issue+ #1484) — a hotspot verdict then no longer flips when a full ``init``+ is later replaced by an incremental ``update``.++ Returns ``None`` when the store is unreadable, the repository row is+ missing, or no blame rollup has been persisted (ESSENTIAL tier, or a+ repo that has never been fully indexed) — callers fall back to the+ walked-set computation in that case.+ """+ log = log or _noop_log+ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():+ return None+ try:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_git_function_mod_counts,+ get_repository_by_path,+ )+ from repowise.core.persistence.database import resolve_db_url++ engine = create_engine(resolve_db_url(repo_path))+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return None+ # What the last full index measured over every walked function.+ stored = getattr(repo, "function_mod_p80", None)+ if stored:+ return int(stored)+ counts = await get_git_function_mod_counts(session, repo.id)+ finally:+ await engine.dispose()+ if not counts:+ return None+ # Fallback for a store whose last full index predates the column above.+ # The rollup is keyed by ``{path}::{name}``, so a file's same-named+ # functions collapse to one row and this percentile is taken over a+ # population missing those samples. Closer than the changed-files+ # subset, still not the number a full index computes.+ from repowise.core.analysis.health.engine import _percentile_p80++ return _percentile_p80(counts)+ except Exception as exc:+ log(f"[yellow]Stored function-mod percentile unavailable: {exc}[/yellow]")+ return None+++async def load_stored_coverage_map(repo_path: Any, *, log: LogFn | None = None) -> dict[str, dict]:+ """Load the persisted coverage map for health scoring on an incremental run.++ The incremental health pass re-scores changed files only, but if it builds+ its ``HealthAnalyzer`` without a ``coverage_map`` every re-analyzed file is+ scored as if no coverage had ever been ingested — and the partial-health+ writer then overwrites the stored ``line_coverage_pct`` with ``None`` for+ exactly the files that just changed, eroding coverage one file per update+ (issue #1739).++ Returns ``{path: coverage-dict}`` by reloading the persisted ``CoverageFile``+ rows, mirroring ``_coverage_for_rescore`` in the CLI update path. Empty dict+ when no coverage is stored, the store is unreadable, or the repository row+ is missing — the analyzer then scores without coverage, matching the+ established safe default.+ """+ log = log or _noop_log++ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():+ return {}+ try:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_repository_by_path,+ load_coverage_map,+ )+ from repowise.core.persistence.database import resolve_db_url++ engine = create_engine(resolve_db_url(repo_path))+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return {}+ coverage_map = await load_coverage_map(session, repo.id)+ finally:+ await engine.dispose()+ return coverage_map+ except Exception as exc:+ log(f"[yellow]Stored coverage unavailable: {exc}[/yellow]")+ return {}diff --git a/packages/core/src/repowise/core/pipeline/incremental/persist_index.py b/packages/core/src/repowise/core/pipeline/incremental/persist_index.pynew file mode 100644index 000000000..9433f4011--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/persist_index.py@@ -0,0 +1,497 @@+"""The incremental index writer: every DB step of an update, in order."""++from __future__ import annotations++from pathlib import Path+from typing import Any++from repowise.core.pipeline.phase_timing import PhaseTimings, timed++from ._common import LogFn, _noop_log+from .commits import persist_incremental_commits+from .external_systems import refresh_external_systems+from .health import persist_partial_health+from .prune import prune_deleted_files+++async def persist_incremental_index(+ repo_path: Any,+ graph_builder: Any,+ git_meta_map: dict,+ dead_code_report: Any,+ partial_health_report: Any,+ changed_paths: list[str],+ *,+ doc_drift_report: Any | None = None,+ current_graph_file_paths: set[str] | None = None,+ file_diffs: list[Any] | None = None,+ knowledge_graph_result: Any | None = None,+ parsed_files: list[Any] | None = None,+ source_map: dict[str, Any] | None = None,+ git_decay_map: dict | None = None,+ full_git_summary: Any | None = None,+ history_window_changed: bool = False,+ reconcile_full_scope: bool = False,+ full_generation_page_ids: set[str] | None = None,+ vector_store: Any | None = None,+ log: LogFn | None = None,+ degraded: list[str] | None = None,+ failed_steps: list[str] | None = None,+ timings: PhaseTimings | None = None,+) -> None:+ """Persist an incremental index refresh (graph + symbols + git + dead-code + health).++ Upsert-only: unchanged files keep their existing rows, unlike+ ``persist_pipeline_result``'s delete-then-insert. State-file updates stay+ with the caller — this writes the DB only.++ ``degraded`` (when supplied) collects a one-line entry for every+ best-effort step that failed, so the caller can render an honest+ completion report instead of silently claiming success.++ ``failed_steps`` (when supplied) collects the names of the failed steps+ whose input was *this commit range* rather than the whole repo. Those are+ the only failures a later run cannot heal on its own: their data is scoped+ to a range the sync pointer is about to move past, so the caller records+ them as a repair marker and re-covers the range next update.++ The test for membership is "would widening the next run's diff base repair+ this, and would nothing else". Steps that re-derive the whole repo every+ run are deliberately absent (graph nodes, the sweeps, the page tree,+ related pages, the knowledge graph, the deleted-file prune): they heal+ themselves on the next update, and marking them would let a permanently+ broken one pin the repair window open. So is the commit capture, which+ looks range-scoped and is not: it bounds its walk by the newest+ ``committed_at`` already in the table, so a run it skipped is re-walked by+ the next one whatever the diff base says.++ ``timings`` records the whole write as ``persist`` and each step as a+ ``persist.*`` row. A step that did not run records nothing, so an absent+ row means skipped rather than free.+ """+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )+ from repowise.core.persistence.database import resolve_db_url++ log = log or _noop_log++ def _skip(step: str, exc: Exception, *, range_scoped: bool = False) -> None:+ log(f"[yellow]{step} skipped: {exc}[/yellow]")+ if degraded is not None:+ degraded.append(f"{step}: {exc}")+ if range_scoped and failed_steps is not None:+ failed_steps.append(step)++ url = resolve_db_url(repo_path)+ engine = create_engine(url)+ # Filled by the tombstone step; read after the session closes, so it has to+ # survive a step that was skipped.+ tombstoned_page_ids: list[str] = []+ # Same contract, for rows of a page that has been retired outright.+ swept_page_ids: list[str] = []+ if timings is not None:+ timings.start("persist")+ try:+ with timed(timings, "persist.open"):+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ with timed(timings, "persist.open"):+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path), stamp_head=True+ )+ repo_id = repo.id++ if reconcile_full_scope:+ try:+ from repowise.core.pipeline.persist import (+ reconcile_full_index_scope,+ )++ current_graph_paths = set(+ getattr(+ graph_builder,+ "traversed_file_paths",+ {pf.file_info.path for pf in parsed_files or []},+ )+ )+ current_git_paths = set(git_meta_map)+ with timed(timings, "persist.scope_reconcile"):+ tombstoned_page_ids = await reconcile_full_index_scope(+ session,+ repo_id,+ current_graph_paths,+ current_git_paths,+ )+ except Exception as exc:+ _skip("Config scope reconciliation", exc)++ if full_generation_page_ids is not None:+ try:+ from repowise.core.pipeline.persist import (+ tombstone_pages_outside_generation,+ )++ tombstoned_page_ids += await tombstone_pages_outside_generation(+ session, repo_id, full_generation_page_ids+ )+ except Exception as exc:+ _skip("Generation scope reconciliation", exc)++ # Delete rows of pages retired since this index was built. This+ # path never regenerates a repo-wide page, so nothing else here+ # would ever visit one to notice it should be gone, and for a user+ # whose updates all come from the post-commit hook this is the only+ # place a retirement can land.+ try:+ from repowise.core.pipeline.persist import (+ sweep_absent_cycle_pages,+ sweep_absent_symbol_spotlights,+ sweep_retired_pages,+ )++ with timed(timings, "persist.sweeps"):+ swept_page_ids = await sweep_retired_pages(session, repo_id)+ # Same reasoning as the retirement sweep above: this path+ # never regenerates a cycle page, so asking the rebuilt+ # graph whether the cycle still exists is the only way a+ # fixed cycle's page can ever be retired for a user who+ # only runs `update`. Spotlights of removed symbols too.+ swept_page_ids += await sweep_absent_cycle_pages(+ session, repo_id, graph_builder+ )+ swept_page_ids += await sweep_absent_symbol_spotlights(+ session, repo_id, graph_builder+ )+ except Exception as exc:+ _skip("Retired page sweep", exc)++ # Tombstone pages for deleted/renamed files FIRST — a fresh page+ # for a file that no longer exists misleads every retrieval+ # consumer until the next full regeneration.+ if file_diffs:+ try:+ from repowise.core.pipeline.persist import (+ mark_tombstone_pages,+ tombstone_candidates,+ )++ with timed(timings, "persist.tombstones"):+ tombstoned_page_ids += await mark_tombstone_pages(+ session, repo_id, tombstone_candidates(file_diffs)+ )+ except Exception as exc:+ _skip("Tombstone marking", exc, range_scoped=True)++ # Placement depends on the whole page set, which on an incremental+ # run lives in the store rather than in the pages just generated.+ try:+ from repowise.core.pipeline.page_tree_sync import rebuild_page_tree++ with timed(timings, "persist.page_tree"):+ await rebuild_page_tree(session, repo_id)+ except Exception as exc:+ _skip("Page tree rebuild", exc)++ if git_meta_map or git_decay_map or full_git_summary is not None:+ try:+ with timed(timings, "persist.git"):+ from repowise.core.pipeline.persist import persist_git_refresh++ await persist_git_refresh(+ session,+ repo_id,+ git_meta_map,+ git_decay_map,+ full_git_summary,+ keep_commit_health=not history_window_changed,+ )+ except Exception as exc:+ _skip("Git persist", exc, range_scoped=True)++ try:+ with timed(timings, "persist.commits"):+ if full_git_summary is None:+ await persist_incremental_commits(+ session, repo_id, repo_path, timings=timings+ )+ except Exception as exc:+ _skip("Commit capture", exc)++ if dead_code_report is not None:+ try:+ from repowise.core.persistence.crud import (+ replace_dead_code_findings,+ )++ # The report is repo-wide, and dead code is a cross-file+ # property, so a change-scoped write would drop every+ # verdict the change flipped outside the change set. The+ # scope is the set of files whose confidence was scored on+ # real git metadata; the rest keep what they had.+ with timed(timings, "persist.dead_code"):+ await replace_dead_code_findings(+ session,+ repo_id,+ dead_code_report.findings,+ scope=dead_code_report.authoritative_paths,+ )+ except Exception as exc:+ _skip("Dead-code persist", exc, range_scoped=True)++ if doc_drift_report is not None:+ try:+ from repowise.core.persistence.crud import (+ replace_doc_drift_guarded,+ )++ with timed(timings, "persist.doc_drift"):+ await replace_doc_drift_guarded(+ session, repo_id, doc_drift_report+ )+ except Exception as exc:+ # Not range_scoped: the pass re-derives every document each+ # run, so a skipped write heals itself on the next update.+ _skip("Doc-drift persist", exc)++ # Re-persist graph_nodes so symbol-level PageRank /+ # betweenness / community ids stay in sync with the+ # current graph build. Without this, ``repowise update``+ # leaves stale per-symbol metrics from the original init+ # and the UI shows "Not indexed in graph" for every+ # symbol on existing repos. Before health, whose plan+ # annotations read each symbol's ``public_api`` from here; a+ # failed write leaves them reading the last run's flags.+ try:+ from repowise.core.pipeline.persist import persist_graph_nodes++ with timed(timings, "persist.graph_nodes"):+ await persist_graph_nodes(session, repo_id, graph_builder, timings=timings)+ except Exception as exc:+ _skip("Graph nodes persist", exc)++ if partial_health_report is not None:+ try:+ with timed(timings, "persist.health"):+ await persist_partial_health(+ session, repo_id, partial_health_report, repo_path+ )+ except Exception as exc:+ _skip("Health persist", exc, range_scoped=True)++ # Refresh wiki_symbols for the changed files. Historically the+ # incremental path re-parsed but never persisted symbols, so their+ # start/end bounds fossilized at the last full index and the+ # get_answer hydrator served drifted signatures. Scoped to the+ # changed set for cost.+ try:+ from repowise.core.pipeline.persist import persist_incremental_symbols++ with timed(timings, "persist.symbols"):+ await persist_incremental_symbols(session, repo_id, parsed_files, changed_paths)+ except Exception as exc:+ _skip("Symbol persist", exc, range_scoped=True)++ try:+ from repowise.core.pipeline.persist import persist_incremental_security_findings++ with timed(timings, "persist.security"):+ await persist_incremental_security_findings(+ session, repo_id, parsed_files, source_map, changed_paths+ )+ except Exception as exc:+ _skip("Security persist", exc, range_scoped=True)++ # Refresh graph_edges for the changed files. The full-init path was+ # historically the only writer of edges, so adjacency froze at the+ # last full index: new imports/calls stayed invisible and dropped+ # ones lingered as false paths. Phase E flow-path traversal reads+ # adjacency straight from this table, so it decayed on every update.+ try:+ from repowise.core.pipeline.persist import persist_incremental_edges++ with timed(timings, "persist.edges"):+ await persist_incremental_edges(+ session, repo_id, graph_builder, parsed_files, changed_paths+ )+ except Exception as exc:+ _skip("Graph edges persist", exc, range_scoped=True)++ # Refresh related-pages metadata across the whole wiki. LLM-free,+ # so even index-only updates heal pages generated before the+ # feature shipped (or drifted by new imports) in one run.+ try:+ from repowise.core.generation.related_pages import file_import_edges+ from repowise.core.persistence.crud import backfill_related_pages++ with timed(timings, "persist.related_pages"):+ changed_rel = await backfill_related_pages(+ session,+ repo_id,+ import_edges=file_import_edges(graph_builder),+ git_meta_map=git_meta_map,+ pagerank=graph_builder.pagerank(),+ )+ if changed_rel:+ log(f"Related pages refreshed on {changed_rel} pages")+ except Exception as exc:+ _skip("Related-pages backfill", exc)++ if knowledge_graph_result is not None:+ try:+ from repowise.core.pipeline.persist import persist_kg++ with timed(timings, "persist.kg"):+ await persist_kg(knowledge_graph_result, session, repo_id)+ except Exception as exc:+ _skip("Knowledge-graph persist", exc)++ # Refresh external systems (C4 L1) when a dependency manifest+ # changed — otherwise the architecture panel serves the init-time+ # dep list forever. Gated + no LLM (see refresh_external_systems).+ if file_diffs:+ try:+ with timed(timings, "persist.external_systems"):+ await refresh_external_systems(+ session, repo_id, repo_path, file_diffs, log=log+ )+ except Exception as exc:+ _skip("External systems refresh", exc, range_scoped=True)++ # One-shot drain of proposals from the removed code_comment+ # harvest (#751). Runs on the index-only path too, because the+ # post-commit hook's updates never reach the full decision+ # persist. Confirmed/dismissed rows are kept.+ try:+ from repowise.core.persistence.crud import (+ purge_proposed_decisions_by_source,+ )++ await purge_proposed_decisions_by_source(session, repo_id, "code_comment")+ # A history-window change re-mines these; a walk that only+ # refreshes rows under new rules does not, so it keeps them.+ if full_git_summary is not None and history_window_changed:+ await purge_proposed_decisions_by_source(+ session, repo_id, "git_archaeology"+ )+ except Exception as exc:+ _skip("Decision purge", exc)++ # Last in the session on purpose: everything above upserts, and the+ # git step indexes the changed *paths*, deleted ones included, so+ # the prune has to have the final say on what the store claims.+ await prune_deleted_files(+ session,+ repo_id,+ repo_path,+ graph_builder,+ (+ current_graph_file_paths+ if current_graph_file_paths is not None+ else {pf.file_info.path for pf in parsed_files or []}+ ),+ health_report=partial_health_report,+ skip=_skip,+ log=log,+ degraded=degraded,+ timings=timings,+ )+ # The transaction commits as the block exits.+ if timings is not None:+ timings.start("persist.commit")+ if timings is not None:+ timings.stop("persist.commit")++ # Every update, not only those with git changes: a backlog an earlier+ # budget left drains here, and an empty window costs one query.+ from repowise.core.pipeline.commit_health import refresh_commit_health_after_update++ with timed(timings, "persist.commit_health"):+ await refresh_commit_health_after_update(sf, repo_id, str(repo_path))++ # After the session closes: on SQLite the full-text index shares the+ # database file, so writing to it while the session holds a write lock+ # raises "database is locked".+ #+ # A tombstone can never be an answer — hydration drops it — but+ # retrieval fetches a fixed number of rows before that check runs, so+ # every tombstone left in the index costs a real candidate its slot.+ #+ # A swept page's FTS row is worse than a tombstone: search hydrates+ # title and snippet from the FTS copy itself, so an orphan answers in+ # full while the page it names 404s.+ from repowise.core.pipeline.cleanup_debt import (+ clear_cleanup_debt,+ load_cleanup_debt,+ record_cleanup_debt,+ )++ cleanup_debt = load_cleanup_debt(Path(repo_path))+ fts_cleanup_ids = (+ set(tombstoned_page_ids) | set(swept_page_ids) | cleanup_debt["fts"]+ )+ if fts_cleanup_ids:+ try:+ from repowise.core.persistence.search import FullTextSearch++ fts = FullTextSearch(engine)+ with timed(timings, "persist.fts"):+ await fts.ensure_index()+ await fts.delete_many(sorted(fts_cleanup_ids))+ clear_cleanup_debt(Path(repo_path), "fts", fts_cleanup_ids)+ except Exception as exc:+ # Range-scoped for the tombstone half: mark_tombstone_pages+ # re-marks and re-returns pages that are already tombstones, so+ # a widened re-run regenerates these ids and retries the delete.+ # The swept half is not repairable this way, because the sweeps+ # deleted those rows and a later run finds nothing to sweep.+ # Tagging still recovers strictly more than not tagging.+ record_cleanup_debt(Path(repo_path), "fts", fts_cleanup_ids)+ _skip("Tombstone full-text removal", exc, range_scoped=True)++ vector_cleanup_ids = set(tombstoned_page_ids) | cleanup_debt["vectors"]+ if vector_cleanup_ids and vector_store is None:+ lance_dir = Path(repo_path) / ".repowise" / "lancedb"+ if lance_dir.exists():+ try:+ from repowise.core.persistence.vector_store import LanceDBVectorStore+ from repowise.core.providers.embedding.base import MockEmbedder++ # Delete-only access never embeds or checks dimensions.+ vector_store = LanceDBVectorStore(str(lance_dir), embedder=MockEmbedder())+ except Exception as exc:+ record_cleanup_debt(+ Path(repo_path), "vectors", vector_cleanup_ids+ )+ _skip("Tombstone vector-store open", exc, range_scoped=True)+ else:+ # No store means there are no vector rows left to clean.+ clear_cleanup_debt(Path(repo_path), "vectors", vector_cleanup_ids)++ if vector_cleanup_ids and vector_store is not None:+ try:+ with timed(timings, "persist.vectors"):+ await vector_store.delete_many(sorted(vector_cleanup_ids))+ clear_cleanup_debt(Path(repo_path), "vectors", vector_cleanup_ids)+ except Exception as exc:+ record_cleanup_debt(Path(repo_path), "vectors", vector_cleanup_ids)+ _skip("Tombstone vector removal", exc)++ # Ceiling: retired non-file pages' *vector* embeddings survive this path.+ # There is no store here to delete them from, and building one would+ # pull the lancedb import onto the post-commit hook, which+ # ``deterministic.py`` avoids on purpose — and with the default mock+ # embedder this path never wrote a page embedding in the first place.+ # LanceDB hydrates a hit from its own columns, so a residual embedding+ # can still surface in semantic search until the next docs-mode update+ # (which does delete it) or a reindex.+ finally:+ await engine.dispose()+ if timings is not None:+ timings.stop("persist")diff --git a/packages/core/src/repowise/core/pipeline/incremental/prune.py b/packages/core/src/repowise/core/pipeline/incremental/prune.pynew file mode 100644index 000000000..07d9bb68f--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/incremental/prune.py@@ -0,0 +1,83 @@+"""Deleted-file prune shared by every update writer."""++from __future__ import annotations++from collections.abc import Callable, Iterable+from typing import Any++from repowise.core.pipeline.phase_timing import PhaseTimings, timed++from ._common import LogFn+++async def prune_deleted_files(+ session: Any,+ repo_id: str,+ repo_path: Any,+ graph_builder: Any,+ live_paths: Iterable[str],+ *,+ health_report: Any,+ skip: Callable[[str, Exception], None],+ log: LogFn,+ degraded: list[str] | None,+ timings: PhaseTimings | None,+) -> None:+ """Drop file-scoped rows for deleted files, then rebuild the queues built from them.++ Shared by every update writer. Liveness is asked of disk and git, never of+ this run's parse (see prune_deleted_file_rows).++ Call it last in the session: the steps before it upsert, and the git step+ indexes deleted paths too, so an earlier prune would be undone.++ The graph's file nodes join *live_paths* because resolver passes mint+ file-shaped nodes that name no file (`external:`, `framework:`, Spring SPI+ sources); they fail every liveness test, and only changed files' edges are+ rebuilt afterwards. A graph that cannot be read skips the prune.+ """+ pruned = 0+ try:+ from repowise.core.pipeline.persist import prune_deleted_file_rows++ live_hint = set(live_paths) | {+ node+ for node, data in graph_builder.graph().nodes(data=True)+ if data.get("node_type", "file") == "file"+ }+ with timed(timings, "persist.prune"):+ pruned, refusals = await prune_deleted_file_rows(+ session, repo_id, repo_path, live_hint=live_hint+ )+ if pruned:+ log(f"Pruned rows for [cyan]{pruned}[/cyan] deleted file(s)")+ for refusal in refusals:+ log(f"[yellow]{refusal}[/yellow]")+ if degraded is not None:+ degraded.append(refusal)+ except Exception as exc:+ skip("Deleted-file prune", exc)++ # The performance and refactoring queues are materialized from the health+ # findings the prune just deleted; without this they keep serving a cause+ # whose evidence is gone, on a file the store no longer claims exists.+ if not pruned:+ return+ try:+ from repowise.core.persistence.crud import (+ finalize_performance_opportunities,+ finalize_refactoring_opportunities,+ )+ from repowise.core.pipeline.persist import _analyzed_commit++ analyzed_commit = await _analyzed_commit(session, repo_id)+ await finalize_performance_opportunities(+ session,+ repo_id,+ analyzed_commit=analyzed_commit,+ plan_policy=getattr(health_report, "performance_plan_policy", None),+ execution_roles=getattr(health_report, "execution_roles", None),+ )+ await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)+ except Exception as exc:+ skip("Queue rebuild after prune", exc)diff --git a/tests/unit/_persist_step_recorders.py b/tests/unit/_persist_step_recorders.pyindex 1380bd949..0bd5056fe 100644--- a/tests/unit/_persist_step_recorders.py+++ b/tests/unit/_persist_step_recorders.py@@ -90,6 +90,7 @@ def install_shared_steps(rec: StepRecorder, *, prune_ret: tuple[int, list[str]]import repowise.core.persistence.search as searchimport repowise.core.pipeline.commit_health as commit_healthimport repowise.core.pipeline.incremental as incremental+ import repowise.core.pipeline.incremental.persist_index as persist_indeximport repowise.core.pipeline.page_tree_sync as page_tree_syncimport repowise.core.pipeline.persist as persistfrom repowise.core.persistence import crud@@ -103,11 +104,14 @@ def install_shared_steps(rec: StepRecorder, *, prune_ret: tuple[int, list[str]]rec.patch(persist, "mark_tombstone_pages", ret=[TOMBSTONED])rec.patch(page_tree_sync, "rebuild_page_tree")rec.patch(persist, "persist_git_refresh")+ # The package for the CLI, which imports it at call time; the writer for core.rec.patch(incremental, "persist_incremental_commits")+ rec.patch(persist_index, "persist_incremental_commits")rec.patch(crud, "replace_dead_code_findings")rec.patch(crud, "replace_doc_drift_guarded")rec.patch(persist, "persist_graph_nodes")rec.patch(incremental, "persist_partial_health")+ rec.patch(persist_index, "persist_partial_health")rec.patch(persist, "persist_incremental_symbols")rec.patch(persist, "persist_incremental_security_findings")rec.patch(persist, "persist_incremental_edges")@@ -115,6 +119,7 @@ def install_shared_steps(rec: StepRecorder, *, prune_ret: tuple[int, list[str]]rec.patch(crud, "backfill_related_pages", ret=0)rec.patch(persist, "persist_kg")rec.patch(incremental, "refresh_external_systems")+ rec.patch(persist_index, "refresh_external_systems")rec.patch(crud, "purge_proposed_decisions_by_source")rec.patch(persist, "prune_deleted_file_rows", ret=prune_ret)rec.patch(persist, "_analyzed_commit", ret="abc123")diff --git a/tests/unit/cli/test_update_working_tree.py b/tests/unit/cli/test_update_working_tree.pyindex 78f34e9c2..7b0989ace 100644--- a/tests/unit/cli/test_update_working_tree.py+++ b/tests/unit/cli/test_update_working_tree.py@@ -205,6 +205,7 @@ def test_working_tree_only_update_skips_history_phases_until_the_commit() -> None:from repowise.cli.helpers import load_state, save_statefrom repowise.core.pipeline import incremental as core_incremental+ from repowise.core.pipeline.incremental import persist_indexrepo = _make_git_repo(tmp_path)_index_full(repo)@@ -214,14 +215,16 @@ def test_working_tree_only_update_skips_history_phases_until_the_commit(analysis = _spy(monkeypatch, update_command_mod, "_run_partial_analysis")drift = _spy(monkeypatch, update_command_mod, "_run_doc_drift_partial")+ # The CLI path imports it from the package; the core writer holds its own reference.commits = _spy(monkeypatch, core_incremental, "persist_incremental_commits")+ commits_core = _spy(monkeypatch, persist_index, "persist_incremental_commits")(repo / "a.py").write_text(_EDITED_A)(repo / "b.py").write_text(_EDITED_B)result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace", "--working-tree"])assert result.exit_code == 0, result.output- assert (analysis, drift, commits) == ([], [], [])+ assert (analysis, drift, commits + commits_core) == ([], [], [])history_phases = {"persist.commits", "persist.health", "analysis.health", "rescore"}assert not history_phases & _phase_rows(repo)view = asyncio.run(_store_view(repo))@@ -235,7 +238,7 @@ def test_working_tree_only_update_skips_history_phases_until_the_commit(result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])assert result.exit_code == 0, result.output- assert analysis and drift and commits+ assert analysis and drift and commits + commits_core# Each label is real: the commit's update records every one of them.assert history_phases <= _phase_rows(repo)assert load_state(repo)["last_sync_commit"] == _git(repo, "rev-parse", "HEAD")diff --git a/tests/unit/health/test_module_attribution.py b/tests/unit/health/test_module_attribution.pyindex dfc258ccb..baee1d7dc 100644--- a/tests/unit/health/test_module_attribution.py+++ b/tests/unit/health/test_module_attribution.py@@ -228,7 +228,7 @@ def test_every_analyzer_call_site_supplies_a_repo_root():import repowise.cli.commands.health_cmd.command as health_cmdimport repowise.cli.commands.update_cmd.persistence as rescore- import repowise.core.pipeline.incremental as incremental+ import repowise.core.pipeline.incremental.analysis as incrementalimport repowise.core.pipeline.phases.analysis as full_indexfor module in (full_index, incremental, rescore, health_cmd):diff --git a/tests/unit/persistence/test_commit_health_after_update.py b/tests/unit/persistence/test_commit_health_after_update.pyindex 1c26d1e96..b56f2ff48 100644--- a/tests/unit/persistence/test_commit_health_after_update.py+++ b/tests/unit/persistence/test_commit_health_after_update.py@@ -15,7 +15,7 @@ from pathlib import Pathimport pytestimport repowise.core.analysis.change_health.commit_scan as scan_mod-import repowise.core.pipeline.incremental as incremental_mod+import repowise.core.pipeline.incremental.persist_index as incremental_modfrom repowise.core.analysis.change_health.commit_scan import (CommitHealthScan,current_fingerprint,diff --git a/tests/unit/persistence/test_page_tree_wiring.py b/tests/unit/persistence/test_page_tree_wiring.pyindex 4f2ed6727..623e429f6 100644--- a/tests/unit/persistence/test_page_tree_wiring.py+++ b/tests/unit/persistence/test_page_tree_wiring.py@@ -23,7 +23,7 @@ import pytest_PERSIST_PATHS = [("repowise.core.pipeline.persist", "the full index"),- ("repowise.core.pipeline.incremental", "the incremental index"),+ ("repowise.core.pipeline.incremental.persist_index", "the incremental index"),("repowise.core.pipeline.scoped_generation", "a scoped regeneration"),("repowise.cli.commands.update_cmd.persistence", "the docs update"),("repowise.cli.commands.upgrade_flow", "the fast-to-full upgrade"),diff --git a/tests/unit/pipeline/test_git_partial_clone_warning.py b/tests/unit/pipeline/test_git_partial_clone_warning.pyindex 4053c76a8..e53b5024b 100644--- a/tests/unit/pipeline/test_git_partial_clone_warning.py+++ b/tests/unit/pipeline/test_git_partial_clone_warning.py@@ -51,7 +51,7 @@ async def test_partial_clone_warning_reaches_incremental_log(tmp_path) -> None:with (patch(- "repowise.core.pipeline.incremental.build_repo_graph",+ "repowise.core.pipeline.incremental.graph.build_repo_graph",return_value=([], {}, graph_builder, MagicMock(), 0),),patch("repowise.core.ingestion.git_indexer.GitIndexer") as indexer_type,diff --git a/tests/unit/pipeline/test_incremental_failure_isolation.py b/tests/unit/pipeline/test_incremental_failure_isolation.pyindex d67ee82d8..a022d7f8b 100644--- a/tests/unit/pipeline/test_incremental_failure_isolation.py+++ b/tests/unit/pipeline/test_incremental_failure_isolation.py@@ -131,7 +131,7 @@ def test_the_range_scoped_set_is_exactly_these_steps():import refrom pathlib import Path- import repowise.core.pipeline.incremental as mod+ import repowise.core.pipeline.incremental.persist_index as modsource = Path(mod.__file__).read_text(encoding="utf-8")tagged = set(re.findall(r'_skip\(\s*"([^"]+)",\s*exc,\s*range_scoped=True', source))diff --git a/tests/unit/precedent/test_git_episodes.py b/tests/unit/precedent/test_git_episodes.pyindex 09727a10e..cfd806773 100644--- a/tests/unit/precedent/test_git_episodes.py+++ b/tests/unit/precedent/test_git_episodes.py@@ -327,7 +327,7 @@ def test_only_the_indexing_paths_opt_in() -> None:}assert found == {"repowise/core/pipeline/phases/git.py",- "repowise/core/pipeline/incremental.py",+ "repowise/core/pipeline/incremental/commits.py",}