Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(pipeline): lift phases out of the update and persist functions this week grew (#3553)

Raghav Chamadiyaf8c7f067ffa4
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index c126716c9..386472b43 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -414,6 +414,95 @@ def resolve_repair_base(
return from_commit, None
+def _rescore_stale_findings(
+ repo_path: Any,
+ graph_builder: Any,
+ state: dict,
+ *,
+ head_ts: float | None,
+ parsed_files: list | None,
+ exclude_patterns: list[str] | None,
+ force_full_rescore: bool,
+ timings: PhaseTimings | None,
+) -> tuple[Any, Any, Any]:
+ """Re-score health and rescan security repo-wide when they are stale.
+
+ Returns the ``last_full_rescore_at``, ``health_analyzer_version`` and
+ ``security_scanner_version`` stamps the new state should carry.
+ """
+ # Periodic idle-file health re-score (#728): git_metadata is now fresh in the
+ # DB, so re-score every file's findings against the decayed inputs. Gated to
+ # ~weekly since only the findings (not their cheap git inputs) lag here.
+ # ``force_full_rescore`` is the config-changed caller: a config edit
+ # invalidates every persisted score, and the partial health update above
+ # only reached the changed files.
+ last_full_rescore_at = state.get("last_full_rescore_at")
+ health_analyzer_version = state.get("health_analyzer_version")
+ rescored = False
+ if force_full_rescore or full_rescore_due(state, head_ts):
+ with timed(timings, "rescore"):
+ rescored = run_decay_health_rescore(
+ repo_path, graph_builder, parsed_files or [], exclude_patterns or []
+ )
+ if rescored:
+ # Only the time gate reads this, and it treats a non-numeric value as
+ # "never re-scored", so leave a real stamp alone rather than writing
+ # None over it when git gave us no timestamp.
+ if head_ts is not None:
+ last_full_rescore_at = head_ts
+ health_analyzer_version = HEALTH_ANALYZER_VERSION
+ if force_full_rescore and not rescored:
+ raise RuntimeError(
+ "Configuration-triggered health re-score failed; the previous "
+ "fingerprint was retained so the next update retries."
+ )
+
+ # Same drift check for the security scanner (#3072): a version bump means
+ # every unchanged file's stored findings may be stale, since the normal
+ # persist above only rescanned the changed files.
+ security_scanner_version = state.get("security_scanner_version")
+ if security_scanner_changed(state):
+ with timed(timings, "security_rescan"):
+ if run_full_security_rescan(repo_path, exclude_patterns or []):
+ security_scanner_version = SECURITY_SCANNER_VERSION
+ return last_full_rescore_at, health_analyzer_version, security_scanner_version
+
+
+def _stamp_git_history(
+ new_state: dict, full_git_summary: Any | None, failed_steps: list[str]
+) -> None:
+ """Record git history coverage and version when this run walked full history."""
+ if full_git_summary is None:
+ return
+ coverage = getattr(full_git_summary, "history_coverage", None)
+ if coverage is not None:
+ new_state["git_history_coverage"] = coverage.to_dict()
+ else:
+ new_state.pop("git_history_coverage", None)
+ # Every row was rewritten under the current rules, unless they never
+ # reached the store; then the next update walks again.
+ if "Git persist" not in failed_steps:
+ new_state[GIT_HISTORY_VERSION_KEY] = GIT_HISTORY_VERSION
+
+
+def _stamp_scope(repo_path: Any, new_state: dict, failed_steps: list[str]) -> None:
+ """Stamp the index scope, counting this run's failed steps as unavailable."""
+ from repowise.core.index_scope import resolve_index_scope, stamp_index_scope
+
+ scope = resolve_index_scope(new_state, load_config(repo_path))
+ unavailable = set(scope["analysis"]["unavailable"])
+ unavailable.update(str(step) for step in failed_steps)
+ stamp_index_scope(
+ new_state,
+ load_config(repo_path),
+ git_history_coverage=new_state.get("git_history_coverage"),
+ analysis={
+ "unavailable": sorted(unavailable),
+ "skipped": scope["analysis"]["skipped"],
+ },
+ )
+
+
def _persist_index_only_update(
repo_path: Any,
graph_builder: Any,
@@ -504,41 +593,18 @@ def _persist_index_only_update(
from .command import _current_renderer_fingerprint
- # Periodic idle-file health re-score (#728): git_metadata is now fresh in the
- # DB, so re-score every file's findings against the decayed inputs. Gated to
- # ~weekly since only the findings (not their cheap git inputs) lag here.
- # ``force_full_rescore`` is the config-changed caller: a config edit
- # invalidates every persisted score, and the partial health update above
- # only reached the changed files.
- last_full_rescore_at = state.get("last_full_rescore_at")
- health_analyzer_version = state.get("health_analyzer_version")
- rescored = False
- if force_full_rescore or full_rescore_due(state, head_ts):
- with timed(timings, "rescore"):
- rescored = run_decay_health_rescore(
- repo_path, graph_builder, parsed_files or [], exclude_patterns or []
- )
- if rescored:
- # Only the time gate reads this, and it treats a non-numeric value as
- # "never re-scored", so leave a real stamp alone rather than writing
- # None over it when git gave us no timestamp.
- if head_ts is not None:
- last_full_rescore_at = head_ts
- health_analyzer_version = HEALTH_ANALYZER_VERSION
- if force_full_rescore and not rescored:
- raise RuntimeError(
- "Configuration-triggered health re-score failed; the previous "
- "fingerprint was retained so the next update retries."
+ last_full_rescore_at, health_analyzer_version, security_scanner_version = (
+ _rescore_stale_findings(
+ repo_path,
+ graph_builder,
+ state,
+ head_ts=head_ts,
+ parsed_files=parsed_files,
+ exclude_patterns=exclude_patterns,
+ force_full_rescore=force_full_rescore,
+ timings=timings,
)
-
- # Same drift check for the security scanner (#3072): a version bump means
- # every unchanged file's stored findings may be stale, since the normal
- # persist above only rescanned the changed files.
- security_scanner_version = state.get("security_scanner_version")
- if security_scanner_changed(state):
- with timed(timings, "security_rescan"):
- if run_full_security_rescan(repo_path, exclude_patterns or []):
- security_scanner_version = SECURITY_SCANNER_VERSION
+ )
new_state = {
**state,
"last_sync_commit": head,
@@ -559,16 +625,7 @@ def _persist_index_only_update(
# here is exactly the cost the mode exists to avoid.
"renderer_fingerprint": _current_renderer_fingerprint(repo_path),
}
- if full_git_summary is not None:
- coverage = getattr(full_git_summary, "history_coverage", None)
- if coverage is not None:
- new_state["git_history_coverage"] = coverage.to_dict()
- else:
- new_state.pop("git_history_coverage", None)
- # Every row was rewritten under the current rules, unless they never
- # reached the store; then the next update walks again.
- if "Git persist" not in failed_steps:
- new_state[GIT_HISTORY_VERSION_KEY] = GIT_HISTORY_VERSION
+ _stamp_git_history(new_state, full_git_summary, failed_steps)
# Before save_state, and reading ``state`` (the pre-update dict) for the old
# pointer: this is what keeps a degraded run recoverable now that the
# pointer below advances to head regardless.
@@ -591,20 +648,7 @@ def _persist_index_only_update(
if timings is not None:
timings.stop("run")
new_state["phase_timings"] = timings.totals
- from repowise.core.index_scope import resolve_index_scope, stamp_index_scope
-
- scope = resolve_index_scope(new_state, load_config(repo_path))
- unavailable = set(scope["analysis"]["unavailable"])
- unavailable.update(str(step) for step in failed_steps)
- stamp_index_scope(
- new_state,
- load_config(repo_path),
- git_history_coverage=new_state.get("git_history_coverage"),
- analysis={
- "unavailable": sorted(unavailable),
- "skipped": scope["analysis"]["skipped"],
- },
- )
+ _stamp_scope(repo_path, new_state, failed_steps)
save_state(repo_path, new_state)
elapsed = time.monotonic() - start
from .reporting import show_index_only_completion
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 242c89f6e..4bb392a4a 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -50,6 +50,122 @@ def build_filtered_changed_paths(file_diffs: list, exclude_patterns: list[str])
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],
@@ -85,7 +201,7 @@ pass reads the sources.
import os
from concurrent.futures import ThreadPoolExecutor
- from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+ from repowise.core.ingestion import FileTraverser, GraphBuilder
log = log or _noop_log
@@ -111,18 +227,12 @@ pass reads the sources.
# (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:
- try:
- from repowise.core.precedent.structural import record_structural_episodes
-
- record_structural_episodes(repo_path, traverser, allow_formatter_check=False)
- except Exception:
- pass
+ _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 (
- _cache_parsed,
_read_sources,
_split_cached,
)
@@ -134,9 +244,6 @@ pass reads the sources.
if read_only:
parse_cache = None # hits above still count; misses are not stored
- parser: Any = None # constructed lazily — every-file-cached updates skip query compilation
- parsed_files: list = []
- source_map: dict[str, bytes] = {}
graph_builder = GraphBuilder(
repo_path,
exclude_patterns=exclude_patterns,
@@ -161,33 +268,17 @@ pass reads the sources.
# 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: 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)
+ 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")
- for idx, (fi, source) in enumerate(fi_and_bytes):
- parsed = merged.get(idx)
- if parsed is None:
- skipped += 1
- continue
- parsed_files.append(parsed)
- if collect_sources:
- source_map[fi.path] = source
- graph_builder.add_file(parsed)
+ 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
@@ -214,49 +305,7 @@ pass reads the sources.
if skipped:
log(f"[yellow]Skipped {skipped} file(s) that failed to parse.[/yellow]")
- # 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]"
- )
+ _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)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 95db66b09..788a6854b 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -433,6 +433,55 @@ def _betweenness_commits(graph_builder: Any) -> dict[str, str | None]:
return {"file": None, "symbol": None}
+def _stamp_betweenness_commit(
+ node_dict: dict[str, Any],
+ node_type: str,
+ bc: dict[str, float],
+ sym_bc: dict[str, float],
+ bt_commits: dict[str, str | None],
+) -> None:
+ """Set ``betweenness_commit`` on a graph-node row when its scoring is known."""
+ node_id = node_dict["node_id"]
+ # Scored → its commit; in no scoring → NULL, the unscored marker;
+ # provenance unknown → key omitted, so the stored stamp survives.
+ if node_id in bc:
+ kind, scored = "file", True
+ elif node_id in sym_bc:
+ kind, scored = "symbol", True
+ else:
+ kind, scored = ("file" if node_type == "file" else "symbol"), False
+ if bt_commits[kind] is not None:
+ node_dict["betweenness_commit"] = bt_commits[kind] if scored else None
+
+
+def _community_meta(
+ node_id: str,
+ node_type: str,
+ cd: dict[str, Any],
+ sc: dict[str, Any],
+ ci: dict[Any, Any],
+ ep_scores: dict[str, float],
+) -> dict[str, Any]:
+ """The ``community_meta_json`` payload of one graph node."""
+ community_meta: dict[str, Any] = {}
+ if node_type == "file":
+ cid = cd.get(node_id, 0)
+ comm_info = ci.get(cid)
+ if comm_info:
+ community_meta = {
+ "label": comm_info.label,
+ "cohesion": comm_info.cohesion,
+ "conductance": comm_info.conductance,
+ }
+ elif node_type == "symbol":
+ sym_cid = sc.get(node_id)
+ if sym_cid is not None:
+ community_meta = {"symbol_community_id": sym_cid}
+ if node_id in ep_scores:
+ community_meta["entry_point_score"] = ep_scores[node_id]
+ return community_meta
+
+
async def persist_graph_nodes(
session: Any,
repo_id: str,
@@ -500,33 +549,9 @@ async def persist_graph_nodes(
"community_id": stored_community_id(cd, node_id),
}
- # Scored → its commit; in no scoring → NULL, the unscored marker;
- # provenance unknown → key omitted, so the stored stamp survives.
- if node_id in bc:
- kind, scored = "file", True
- elif node_id in sym_bc:
- kind, scored = "symbol", True
- else:
- kind, scored = ("file" if node_type == "file" else "symbol"), False
- if bt_commits[kind] is not None:
- node_dict["betweenness_commit"] = bt_commits[kind] if scored else None
-
- community_meta: dict[str, Any] = {}
- if node_type == "file":
- cid = cd.get(node_id, 0)
- comm_info = ci.get(cid)
- if comm_info:
- community_meta = {
- "label": comm_info.label,
- "cohesion": comm_info.cohesion,
- "conductance": comm_info.conductance,
- }
- elif node_type == "symbol":
- sym_cid = sc.get(node_id)
- if sym_cid is not None:
- community_meta = {"symbol_community_id": sym_cid}
- if node_id in ep_scores:
- community_meta["entry_point_score"] = ep_scores[node_id]
+ _stamp_betweenness_commit(node_dict, node_type, bc, sym_bc, bt_commits)
+
+ community_meta = _community_meta(node_id, node_type, cd, sc, ci, ep_scores)
node_dict["community_meta_json"] = json.dumps(community_meta)
if node_type == "symbol":
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 3fc48941e..5c7b95ab9 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -148,6 +148,133 @@ _DIFF_SIZE_LABELS = {
}
+async def _score_change(
+ repo_path: Any,
+ revspec: str | None,
+ extensions: list[str] | None,
+ exclude_patterns: list[str] | None,
+ baseline: int,
+) -> tuple[Any, dict | None]:
+ """Score the live change: ``(result, None)``, or ``(None, error reply)``."""
+ try:
+ result = await asyncio.to_thread(
+ score_live_change,
+ repo_path,
+ revspec,
+ extensions=tuple(extensions or ()),
+ exclude_patterns=tuple(exclude_patterns or ()),
+ baseline=baseline,
+ )
+ except ValueError as exc:
+ return None, {"error": str(exc)}
+ except subprocess.CalledProcessError as exc:
+ detail = (exc.stderr or "").strip() or str(exc)
+ return None, {"error": f"Could not read change {revspec or 'HEAD'!r}: {detail}"}
+ except subprocess.TimeoutExpired:
+ return None, {"error": f"git timed out reading change {revspec or 'HEAD'!r}."}
+ return result, None
+
+
+async def _attach_change_blocks(
+ ctx: Any,
+ payload: dict,
+ result: Any,
+ revspec: str | None,
+ extensions: list[str] | None,
+ changed_read: tuple[Any, Any],
+ collector: OmissionCollector,
+) -> None:
+ """Attach the tests, patch coverage, prior fixes and cross-repo blocks, in that order."""
+ changed, changed_error = changed_read
+ payload["impacted_tests"] = await _impacted_tests_block(
+ ctx,
+ changed,
+ changed_error,
+ collector,
+ revspec=revspec,
+ working_tree=result.working_tree,
+ )
+ patch_changed, patch_error, patch_label, patch_revspec = await _push_change(
+ str(ctx.path),
+ revspec,
+ result.working_tree,
+ normalize_extensions(tuple(extensions or ())),
+ result.riskignore_excludes + result.request_excludes,
+ (changed, changed_error),
+ )
+ patch = await _patch_coverage_block(
+ ctx, patch_changed, patch_error, patch_revspec, result, collector, label=patch_label
+ )
+ if patch is not None:
+ payload["patch_coverage"] = patch
+ prior_fixes = await _prior_fixes_block(ctx, changed)
+ if prior_fixes is not None:
+ # One fix record, not two. The blocks answered the same question
+ # with different arithmetic (decayed pressure vs raw count) and a
+ # reader had to work out which was which.
+ payload.setdefault("fix_history", {})["overlap"] = prior_fixes
+ alias = getattr(ctx, "alias", "")
+ # The join needs an open index per consumer repo, so it runs once for
+ # the whole change and the block distributes its rows.
+ impact = await cross_repo_tests(alias, sorted(changed))
+ cross_repo = _cross_repo_block(alias, sorted(changed), impact, collector)
+ if cross_repo is not None:
+ payload["cross_repo"] = cross_repo
+
+
+def _include_blocks(include: list[str] | None, ignored: list[dict]) -> set[str]:
+ """The valid ``include`` blocks; unknown ones are recorded in ``ignored``."""
+ return {
+ block
+ for block in (include or [])
+ if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)
+ }
+
+
+async def _attach_branch_blocks(
+ ctx: Any,
+ payload: dict,
+ changed: Any,
+ collector: OmissionCollector,
+ revspec: str | None,
+ finding_id: str | None,
+) -> Any:
+ """Attach ``branch_overlap`` and return the independent-changes block, or None."""
+ # A drill-down returns one finding and nothing else, so neither block
+ # would reach the caller; both are pure cost on that path.
+ if finding_id is not None:
+ return None
+ overlap = await _branch_overlap_block(ctx, changed, collector)
+ if overlap is not None:
+ payload["branch_overlap"] = overlap
+ return await _independent_changes_block(ctx, changed, collector, revspec)
+
+
+def _shape_payload(result: Any, include_set: set[str], revspec: str | None) -> tuple[dict, dict]:
+ """The score's payload trimmed to what the request asked for.
+
+ Returns ``(payload, diagnostics)``; ``diagnostics`` holds the fields moved
+ out of the payload when the caller did not ask for them.
+ """
+ payload = change_risk_payload(result, scales="scales" in include_set)
+ if payload.get("review_priority") in _DIFF_SIZE_LABELS:
+ payload["classification"] = _DIFF_SIZE_LABELS[payload["review_priority"]]
+ if "diagnostics" not in include_set:
+ diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}
+ payload["fix_history"].pop("density", None)
+ else:
+ diagnostics = {}
+ # Fields that only repeat the request or say nothing: an empty exclude list,
+ # a working-tree flag after an explicit revspec, a false ``is_fix``.
+ if not payload["exclude_patterns"]:
+ del payload["exclude_patterns"]
+ if revspec is not None:
+ del payload["working_tree"]
+ if not payload["is_fix"]:
+ del payload["is_fix"]
+ return payload, diagnostics
+
+
@mcp.tool(
surface_order=60,
artifact_type="change_risk",
@@ -199,44 +326,12 @@ async def get_change_risk(
return _unsupported_repo_all("get_change_risk")
ctx = await _resolve_repo_context(repo)
started = time.perf_counter()
- try:
- result = await asyncio.to_thread(
- score_live_change,
- ctx.path,
- revspec,
- extensions=tuple(extensions or ()),
- exclude_patterns=tuple(exclude_patterns or ()),
- baseline=baseline,
- )
- except ValueError as exc:
- return {"error": str(exc)}
- except subprocess.CalledProcessError as exc:
- detail = (exc.stderr or "").strip() or str(exc)
- return {"error": f"Could not read change {revspec or 'HEAD'!r}: {detail}"}
- except subprocess.TimeoutExpired:
- return {"error": f"git timed out reading change {revspec or 'HEAD'!r}."}
+ result, error = await _score_change(ctx.path, revspec, extensions, exclude_patterns, baseline)
+ if error is not None:
+ return error
ignored: list[dict] = []
- include_set = {
- block
- for block in (include or [])
- if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)
- }
- payload = change_risk_payload(result, scales="scales" in include_set)
- if payload.get("review_priority") in _DIFF_SIZE_LABELS:
- payload["classification"] = _DIFF_SIZE_LABELS[payload["review_priority"]]
- if "diagnostics" not in include_set:
- diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}
- payload["fix_history"].pop("density", None)
- else:
- diagnostics = {}
- # Fields that only repeat the request or say nothing: an empty exclude list,
- # a working-tree flag after an explicit revspec, a false ``is_fix``.
- if not payload["exclude_patterns"]:
- del payload["exclude_patterns"]
- if revspec is not None:
- del payload["working_tree"]
- if not payload["is_fix"]:
- del payload["is_fix"]
+ include_set = _include_blocks(include, ignored)
+ payload, diagnostics = _shape_payload(result, include_set, revspec)
if result.features.nf == 0:
return await _nothing_to_score(ctx, payload["ref"], started)
# Changed lines over the SAME file universe the score counted (its
@@ -267,48 +362,12 @@ async def get_change_risk(
)
)
try:
- payload["impacted_tests"] = await _impacted_tests_block(
- ctx,
- changed,
- changed_error,
- collector,
- revspec=revspec,
- working_tree=result.working_tree,
- )
- patch_changed, patch_error, patch_label, patch_revspec = await _push_change(
- str(ctx.path),
- revspec,
- result.working_tree,
- normalize_extensions(tuple(extensions or ())),
- result.riskignore_excludes + result.request_excludes,
- (changed, changed_error),
+ await _attach_change_blocks(
+ ctx, payload, result, revspec, extensions, (changed, changed_error), collector
)
- patch = await _patch_coverage_block(
- ctx, patch_changed, patch_error, patch_revspec, result, collector, label=patch_label
+ independent = await _attach_branch_blocks(
+ ctx, payload, changed, collector, revspec, finding_id
)
- if patch is not None:
- payload["patch_coverage"] = patch
- prior_fixes = await _prior_fixes_block(ctx, changed)
- if prior_fixes is not None:
- # One fix record, not two. The blocks answered the same question
- # with different arithmetic (decayed pressure vs raw count) and a
- # reader had to work out which was which.
- payload.setdefault("fix_history", {})["overlap"] = prior_fixes
- alias = getattr(ctx, "alias", "")
- # The join needs an open index per consumer repo, so it runs once for
- # the whole change and the block distributes its rows.
- impact = await cross_repo_tests(alias, sorted(changed))
- cross_repo = _cross_repo_block(alias, sorted(changed), impact, collector)
- if cross_repo is not None:
- payload["cross_repo"] = cross_repo
- # A drill-down returns one finding and nothing else, so neither block
- # would reach the caller; both are pure cost on that path.
- overlap = independent = None
- if finding_id is None:
- overlap = await _branch_overlap_block(ctx, changed, collector)
- if overlap is not None:
- payload["branch_overlap"] = overlap
- independent = await _independent_changes_block(ctx, changed, collector, revspec)
except BaseException:
# Never leave the comparison running for a request that is already over.
delta_task.cancel()