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
fix(health): find import cycles over runtime edges and make break_cycle advisory (#3259)
Raghav Chamadiya8f81e82c33fb
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 3a629f8ea..2283bd1c1 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -261,8 +261,9 @@ edge, so those cases are missed.Each low-scoring file can carry deterministic refactoring plans (Extract Method,Split File, Break Cycle, Performance Fix and others) with evidence, gain, effort and-blast radius. `repowise health --refactoring-targets` prints the stored queue. See-[REFACTORING.md](REFACTORING.md).+blast radius. `repowise health --refactoring-targets` prints the stored queue.+Break Cycle is advisory: it is shown beside a file's steps, never as one, and+never in Fix first. See [REFACTORING.md](REFACTORING.md).## Trends, coverage and badgesdiff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex f4968e499..bb9d7ce97 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -23,7 +23,7 @@ is a separate, on-request step that does use an LLM| **Extract Method** | A line span to lift out of a long or complex function, with the helper's parameters and return value. || **Extract Helper** | Every occurrence of a duplicated block and where the shared helper belongs. || **Move Method** | A method that uses another class more than its own, and the class it belongs in. |-| **Break Cycle** | The smallest set of import edges to invert to break a dependency cycle. |+| **Break Cycle** | The smallest set of import edges to invert to break a runtime dependency cycle. Advisory: see below. || **Split File** | The files an oversized module splits into, which symbols go where, and the import edits in each dependent. || **Performance Fix** | One shared change for a performance problem, with the affected call sites and caller-to-sink paths. |@@ -79,6 +79,21 @@ earlier step moves a symbol to another file, the later step carries`relocated_by`: its stored location is where the symbol was before, so find itagain before applying.+Break Cycle is advisory. Its plan names edges to cut, not which symbols cross+them or how to move them, so an opportunity carries it as `evidence` rather than+as a numbered step: it never leads, and never reaches Fix first. The plan itself+stays in the plan list. Cycles are found over runtime imports only: an import+under `if TYPE_CHECKING:` or a TypeScript `import type` / `typeof import()` is+type-only, and an import inside a function body is deferred (it runs on first+call, the usual way to break a cycle on purpose). Neither closes a cycle. Only a+plain `TYPE_CHECKING` or `module.TYPE_CHECKING` condition counts; a negated or+aliased flag is read as a runtime import.++Every plan is counted once: the rollup's `plans_total` is the steps, plus+`evidence_total`, plus `unattached_plans_total` (plans in no opportunity, such as+a file whose only plan is a cycle). The plan list's `structural_total` leaves+Break Cycle out, matching the opportunities; `by_type` still counts it.+Names are never invented. A suggested helper or file name is `null` when nothingin the code anchors one.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 0ed342fd4..1ba73301e 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1105,7 +1105,7 @@ Compute per-file code-health scores from 51 deterministic detectors (McCabe comp| `--module <prefix>` | Restrict the report to files whose path starts with this prefix || `--scope` | `all` (default) or `production`. Which files every figure describes. Tests score higher than production code, so narrowing lowers the number without a defect being found. || `--counts` | `everything` (default) or `code_shape`. `code_shape` drops the git-derived half of the deduction, which rises as a file is worked on — the reading that answers whether the code itself is improving. |-| `--refactoring-targets` | Print the refactoring queue the index stored: one opportunity per file with its structured, graph-aware plans (Extract Class / Helper / Method, Move Method, Break Cycle, Split File) as ordered steps, in the same order MCP and the web UI serve. Reads the index, so it needs `repowise init` first. See [REFACTORING.md](../layers/REFACTORING.md) |+| `--refactoring-targets` | Print the refactoring queue the index stored: one opportunity per file with its structured, graph-aware plans (Extract Class / Helper / Method, Move Method, Split File) as ordered steps and Break Cycle as advisory evidence, in the same order MCP and the web UI serve. Reads the index, so it needs `repowise init` first. See [REFACTORING.md](../layers/REFACTORING.md) || `--recompute` | With `--refactoring-targets`: analyze the working tree in-process instead of reading the index. Slow on a large repo; the only option outside an indexed one. `--scope` and `--counts` apply only here. || `--generate-code <selector>` | Generate an actual refactoring patch for one target. The only `health` flag that calls an LLM; needs a configured provider. || `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) |diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.pyindex 79870bc46..e01a1d2a9 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py@@ -82,11 +82,11 @@ def _render_refactoring_targets(# contract speak. The type-grouped dump this replaced made type the# organizing principle, so a file needing a split and two extractions# appeared three times in three sections.+ from repowise.core.analysis.health.refactoring.opportunity import claimed_plan_ids+opportunities, _leads = _compose(findings, suggestions)plan_by_id = _plans_by_public_id(suggestions, ranked_plans)- claimed = {s.plan_id for o in opportunities for s in o.steps} | {- e.plan_id for o in opportunities for e in o.evidence- }+ claimed = claimed_plan_ids(opportunities)unattached = [row for pid, row in plan_by_id.items() if pid not in claimed]rows = [_opportunity_row(o) for o in opportunities]@@ -537,17 +537,17 @@ def _render_opportunities_md(opportunities: list[dict], plan_by_id: dict) -> Nondef _render_unattached_console(plans: list[dict]) -> None:"""Plans no opportunity claims.- A file whose only plans are demoted clones publishes no opportunity, so- without this the CLI would print a smaller number than the analyzer found- and call it the total. They are listed as observations, under their own- heading, rather than folded back in as work.+ A file whose only plans are demoted clones or advisory cycles publishes no+ opportunity, so without this the CLI would print a smaller number than the+ analyzer found and call it the total. They are listed as observations,+ under their own heading, rather than folded back in as work."""if not plans:returnconsole.print(f"\n[bold]Unattached observations ({len(plans)})[/bold]")console.print(- "[dim]Real duplication, not ranked work: no file's opportunity is built "- "on them.[/dim]"+ "[dim]Duplication and import cycles, not ranked work: no file's "+ "opportunity is built on them.[/dim]")for p in plans:console.print(f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']})[/dim]")@@ -560,7 +560,8 @@ def _render_unattached_md(plans: list[dict]) -> None:returnclick.echo("\n## Unattached observations\n")click.echo(- "Real duplication, not ranked work: no file's opportunity is built on them.\n"+ "Duplication and import cycles, not ranked work: no file's opportunity is "+ "built on them.\n")for p in plans:click.echo(f"- **{p['target_symbol']}** ({p['file_path']})")diff --git a/packages/core/alembic/versions/0098_graph_edge_deferred.py b/packages/core/alembic/versions/0098_graph_edge_deferred.pynew file mode 100644index 000000000..a33262d15--- /dev/null+++ b/packages/core/alembic/versions/0098_graph_edge_deferred.py@@ -0,0 +1,42 @@+"""Persist ``graph_edges.deferred`` so lazy-import cycles stay suppressed.++An import inside a function body runs on first call, not at module load, which+is how code breaks an import cycle on purpose. Cycle detection drops these+edges, and a graph rehydrated from SQL must keep the mark.++Local SQLite stores get the column from ``init_db``'s additive reconciler; this+migration covers managed Postgres.++Revision ID: 0098+Revises: 0097+Create Date: 2026-10-10+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0098"+down_revision: str | None = "0097"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "graph_edges",+ sa.Column(+ "deferred",+ sa.Boolean(),+ nullable=False,+ server_default=sa.text("false"),+ ),+ )+++def downgrade() -> None:+ op.drop_column("graph_edges", "deferred")diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.pyindex 99397409c..1633a92f3 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py@@ -15,7 +15,7 @@ from __future__ import annotationsfrom typing import Any-from ....ingestion.cohesion import is_cohesion_edge+from ....ingestion.cohesion import cannot_close_cyclefrom ....ingestion.models import FILE_DEPENDENCY_EDGE_TYPES# File->file edge types that constitute a structural dependency cycle.@@ -39,27 +39,19 @@ from ....ingestion.models import FILE_DEPENDENCY_EDGE_TYPES# ``imports`` and ``type_use`` edges to express that two files are one# compilation unit (Go package siblings, C# partial fragments, a C++# header/impl pair). Those are not dependencies and must not close a cycle, so-# both definitions additionally reject ``is_cohesion_edge``. See+# both definitions additionally reject ``cannot_close_cycle``, which also drops+# type-only and deferred imports and ``dynamic_uses`` hints. See# repowise.core.ingestion.cohesion._CYCLE_EDGE_TYPES = FILE_DEPENDENCY_EDGE_TYPESdef _is_cycle_edge(data: Any) -> bool:- """True if *data* is a file-level edge that can legitimately close a cycle.-- ``dynamic_uses`` is excluded on top of the allowlist: the hint extractors- that emit it (.NET among others) link every file declaring a type of a- given short name, so two unrelated classes that happen to share a name- across projects form a false two-file cycle (#2886). ``framework``,- ``dynamic_imports`` and ``dynamic_url_route`` are not excluded — they were- not the edge type the measured false positives came from.+ """True if *data* is a file-level edge that can close a runtime cycle.++ ``framework``, ``dynamic_imports`` and ``dynamic_url_route`` stay in: they+ were not the edge types the measured false positives came from."""- return (- data.get("edge_type") in _CYCLE_EDGE_TYPES- and data.get("edge_type") != "dynamic_uses"- and not is_cohesion_edge(data)- and not data.get("type_only")- )+ return data.get("edge_type") in _CYCLE_EDGE_TYPES and not cannot_close_cycle(data)def build_file_scc_index(graph: Any) -> dict[str, tuple[str, ...]]:diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.pyindex 3336eb01c..1e99d40bc 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py@@ -27,6 +27,12 @@ across files *and* co-changed. The rest still appears, attached to the file'sopportunity as the supporting evidence it always was, never as an instruction.Nothing is deleted: the plans remain plans, addressable by id.+**A cycle is advisory, not a step.** A ``break_cycle`` plan says which edge to+cut but not which symbols cross it or how to move them, and on audited repos+none of the cycles it named were worth cutting. It rides along as evidence the+same way, so it is never a numbered step, never leads, and never reaches Fix+first; the plan stays in the plan inventory.+**A finding is recovered once.** A step names the findings its own targetanswers: the source biomarker's findings whose span it covers, and for anamed finding only the one on the same symbol. Two steps answering one@@ -46,6 +52,7 @@ from dataclasses import dataclassfrom typing import Anyfrom ...finding_registry import excluded_types+from ..refactoring_summary import ADVISORY_TYPESfrom ..rows import fieldfrom .extract_helper import ACTIVE_CO_CHANGEfrom .identity import REFACTORING_MODEL_VERSION, assign_public_ids, stable_id@@ -72,6 +79,7 @@ _OPPORTUNITY_PREFIX = "refop"# Owned by the performance layer end to end - see the module docstring.EXCLUDED_TYPES = frozenset({"performance_fix"})+# Execution order. Lower runs first. Structural steps relocate symbols, so they# precede the local extractions that would otherwise be re-grouped by them;# within the structural block the widest change goes first, so a later step@@ -234,6 +242,8 @@ def is_standalone_clone(suggestion: RefactoringSuggestion) -> bool:def _is_step(suggestion: RefactoringSuggestion) -> bool:+ if suggestion.refactoring_type in ADVISORY_TYPES:+ return Falseif suggestion.refactoring_type == "extract_helper":return is_standalone_clone(suggestion)return True@@ -545,6 +555,16 @@ def compose_opportunities(return composed+def claimed_plan_ids(opportunities: Iterable[RefactoringOpportunity]) -> set[str]:+ """Plan ids an opportunity carries, as a step or as evidence. A plan outside+ this set is unattached: still a plan, in no file's work."""+ return {+ item.plan_id+ for opportunity in opportunities+ for item in (*opportunity.steps, *opportunity.evidence)+ }++def opportunity_status(opportunity: RefactoringOpportunity, plan_status: Mapping[str, str]) -> str:@@ -581,11 +601,13 @@ def roll_up_status(step_states: Iterable[str]) -> str:__all__ = [+ "ADVISORY_TYPES","EXCLUDED_TYPES","STEP_ORDER","OpportunityEvidence","OpportunityStep","RefactoringOpportunity",+ "claimed_plan_ids","compose_opportunities","is_standalone_clone","opportunity_kernel",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring_summary.py b/packages/core/src/repowise/core/analysis/health/refactoring_summary.pyindex f41490ea9..27c0e05c9 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring_summary.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring_summary.py@@ -11,8 +11,14 @@ from typing import Anyfrom repowise.core.analysis.health.rows import field-#: The types the board groups under its "Structural" lens.-STRUCTURAL_TYPES = frozenset({"split_file", "break_cycle", "extract_class", "move_method"})+#: Plans an opportunity carries as evidence, never as a step: a cycle names+#: edges to cut but not which symbols cross them.+ADVISORY_TYPES = frozenset({"break_cycle"})++#: The types the board groups under its "Structural" lens. Advisory types are+#: left out so the plan chips agree with the opportunities, where they never+#: lead; ``by_type`` still counts them.+STRUCTURAL_TYPES = frozenset({"split_file", "extract_class", "move_method"})#: A plan recovers health at or above this ``impact_delta``.HEALTH_RECOVERY_MIN = 0.1@@ -50,6 +56,7 @@ def summarize_plans(plans: Iterable[Any]) -> dict[str, Any]:__all__ = [+ "ADVISORY_TYPES","HEALTH_RECOVERY_MIN","NEGLIGIBLE_HEALTH_BELOW","STRUCTURAL_TYPES",diff --git a/packages/core/src/repowise/core/ingestion/cohesion.py b/packages/core/src/repowise/core/ingestion/cohesion.pyindex 32b85c918..20efb63c2 100644--- a/packages/core/src/repowise/core/ingestion/cohesion.py+++ b/packages/core/src/repowise/core/ingestion/cohesion.py@@ -106,3 +106,20 @@ def withdraw_declaration_hint(data: dict[str, Any]) -> None:def is_cohesion_edge(data: Any) -> bool:"""True if *data* — a graph edge's attribute dict — is a cohesion edge."""return data.get("hint_source") in COHESION_HINTS+++def cannot_close_cycle(data: Any) -> bool:+ """True if *data* is an edge no runtime import cycle can run through.++ The one predicate both cycle definitions share (``cycle_subgraph`` and+ ``refactoring.graph_signals``): cohesion edges, type-only imports, deferred+ (function-local) imports, and ``dynamic_uses`` hints, which match a type by+ short name rather than resolve a dependency (#2886). The edges stay in the+ graph for reachability and centrality.+ """+ return (+ is_cohesion_edge(data)+ or bool(data.get("type_only"))+ or bool(data.get("deferred"))+ or data.get("edge_type") == "dynamic_uses"+ )diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.pyindex 65fbe88eb..4b8d78c34 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py@@ -133,6 +133,8 @@ def expand_bare_relative_imports(imports: list[Import]) -> list[Import]:is_relative=True,resolved_file=None,bindings=[binding],+ type_only=imp.type_only,+ deferred=imp.deferred,))return outdiff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.pyindex c07ad6471..ee3a2113c 100644--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py@@ -20,7 +20,7 @@ from typing import Anyimport networkx as nximport structlog-from ..cohesion import is_cohesion_edge+from ..cohesion import cannot_close_cyclefrom ..models import SYMBOL_USE_EDGE_TYPES, TEMPORAL_EDGE_TYPESlog = structlog.get_logger(__name__)@@ -131,8 +131,8 @@ class MetricsMixin:return subdef cycle_subgraph(self) -> nx.DiGraph:- """Return :meth:`file_subgraph` minus cohesion, type-only and ``dynamic_uses`` edges,- for cycle detection.+ """Return :meth:`file_subgraph` minus the edges no runtime cycle runs+ through (:func:`~repowise.core.ingestion.cohesion.cannot_close_cycle`).A cohesion edge records that two files are one compilation unit — Gopackage siblings, JVM same-package classes, C# partial fragments, a C++@@ -143,10 +143,12 @@ class MetricsMixin:A ``dynamic_uses`` edge is a hint match, not a resolved dependency — the.NET extractor among others links every file declaring a type of a givenshort name, so two unrelated same-named classes in different projects- form a false two-file cycle (#2886). Excluded here and in- ``refactoring.graph_signals._is_cycle_edge``, which must agree: this- method feeds the wiki SCC pages and the repo-overview cycle list, that- one feeds ``break_cycle`` plans.+ form a false two-file cycle (#2886). Type-only and deferred+ (function-local) imports never run at module load, so they cannot make+ one either. The predicate is shared with+ ``refactoring.graph_signals._is_cycle_edge``: this method feeds the wiki+ SCC pages and the repo-overview cycle list, that one feeds+ ``break_cycle`` plans.Kept separate from :meth:`file_subgraph` deliberately: PageRank,betweenness and the degree kernels must keep seeing cohesion edges,@@ -160,11 +162,7 @@ class MetricsMixin:"""return self._file_edge_view("_cycle_subgraph_cache",- lambda base, u, v, d: (- is_cohesion_edge(d)- or d.get("type_only") is True- or d.get("edge_type") == "dynamic_uses"- ),+ lambda base, u, v, d: cannot_close_cycle(d),)def centrality_subgraph(self) -> nx.DiGraph:diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.pyindex 09360d775..ae956fa19 100644--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py@@ -125,6 +125,8 @@ class RehydrateMixin:edge_attrs["supplied_props"] = frozenset(supplied_props)if edge.get("type_only"):edge_attrs["type_only"] = True+ if edge.get("deferred"):+ edge_attrs["deferred"] = Truegraph.add_edge(source, target, **edge_attrs)edge_count += 1diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.pyindex 6ac47fbbc..6839a64e2 100644--- a/packages/core/src/repowise/core/ingestion/graph/builder.py+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py@@ -21,7 +21,7 @@ from ..cohesion import (withdraw_declaration_hint,)from ..languages.python_modules import dotted_module_for-from ..models import ParsedFile+from ..models import Import, ParsedFile, combine_load_kindsfrom ..resolvers import ResolverContext, resolve_importfrom ..resolvers.go import read_go_module_path, read_go_modulesfrom ..symbol_identity import has_overload_identity@@ -36,6 +36,19 @@ from ._stem import build_stem_maplog = structlog.get_logger(__name__)+def _merge_load_kind(data: dict[str, Any], imp: Import) -> None:+ """Fold one more import into an edge's ``type_only`` / ``deferred`` marks,+ by :func:`~repowise.core.ingestion.models.combine_load_kinds` (one+ load-time import makes the edge a runtime one). ``deferred`` is stored+ only when true."""+ edge = (bool(data.get("type_only")), bool(data.get("deferred")))+ data["type_only"], deferred = combine_load_kinds(edge, (imp.type_only, imp.deferred))+ if deferred:+ data["deferred"] = True+ else:+ data.pop("deferred", None)++class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, RehydrateMixin):"""Build a dependency graph from a collection of ParsedFile objects.@@ -491,16 +504,15 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehydself._graph[path][target]["imported_names"] = mergedif not imp.is_module_declaration:withdraw_declaration_hint(self._graph[path][target])- self._graph[path][target]["type_only"] = (- bool(self._graph[path][target].get("type_only", False))- and imp.type_only- )+ _merge_load_kind(self._graph[path][target], imp)else:edge_attrs: dict[str, Any] = {"edge_type": "imports","imported_names": list(imp.imported_names),"type_only": imp.type_only,}+ if imp.deferred:+ edge_attrs["deferred"] = True# ``external:`` targets are excluded before the# directory test, not after: an external node id has no# directory, and a single-segment one such asdiff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 3f7a03a7a..8c44cab61 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -268,6 +268,8 @@ class Import:# Rust ``mod child;``: declares the child module, uses nothing from it.is_module_declaration: bool = Falsetype_only: bool = False # True when the statement is purely type-level (e.g. TypeScript import type)+ # Inside a function or lambda body: runs on first call, not at module load.+ deferred: bool = False@propertydef local_names(self) -> list[str]:@@ -638,6 +640,22 @@ def is_dynamic_edge(edge_type: str | None) -> bool:return edge_type is not None and edge_type.startswith("dynamic_")+def combine_load_kinds(+ first: tuple[bool, bool], second: tuple[bool, bool]+) -> tuple[bool, bool]:+ """``(type_only, deferred)`` for two imports of one target folded together.++ Each side is runtime ``R`` (neither flag), type-only ``T`` or deferred+ ``D``; the result is the one that runs earliest::++ T + T -> T T + D -> D D + T -> D+ D + D -> D D + R -> R R + D -> R T + R -> R+ """+ type_only = first[0] and second[0]+ deferred = not type_only and any(first) and any(second)+ return type_only, deferred++@dataclassclass TypeReference:"""A non-import type reference extracted from a source file.diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex b80e6ea99..99fc634c3 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -85,6 +85,7 @@ from .models import (ParsedFile,Symbol,TypeReference,+ combine_load_kinds,compute_content_hash,)from .parser_helpers import (@@ -120,6 +121,7 @@ from .parser_helpers import (_run_query,_rust_shadowed_by_type_param,_ts_nested_object_method_owner,+ import_load_kind,)from .python_local_refs import extract_python_local_refsfrom .python_overload import is_python_overload as _is_python_overload@@ -1201,12 +1203,7 @@ def _generic_import(or module_text.startswith("./")or module_text.startswith(("self::", "super::", "crate::")))- type_only = False- if language in _TS_JS_LANGUAGES:- from .extractors.bindings.ts_js import is_type_only_ts_js_import-- type_only = is_type_only_ts_js_import(stmt_node, src)-+ # ``type_only`` / ``deferred`` are set by the caller from ``import_load_kind``.return Import(raw_statement=raw,module_path=module_text,@@ -1216,7 +1213,6 @@ def _generic_import(bindings=bindings,is_reexport=_is_reexport_import(stmt_node, raw, language),is_module_declaration=is_module_declaration,- type_only=type_only,)@@ -1894,6 +1890,9 @@ class ASTParser:language = file_info.languageimports: list[Import] = []seen_raws: set[str] = set()+ # Statement key -> the Imports it produced, so a repeat folds its load+ # kind into them rather than adding a duplicate.+ seen_imports: dict[str, list[Import]] = {}seen_pascal_units: set[str] = set()seen_elixir_modules: set[str] = set()@@ -1935,17 +1934,25 @@ class ASTParser:# each one binds.if language in _TS_JS_LANGUAGES and _is_dynamic_esm_import(stmt_node):dedup_key = f"{raw}|at={stmt_node.start_byte}"- if dedup_key in seen_raws:+ kind = import_load_kind(stmt_node, language, src)+ if dedup_key in seen_imports:+ # A lazy copy must not hide a load-time twin: runtime wins.+ for imp in seen_imports[dedup_key]:+ imp.type_only, imp.deferred = combine_load_kinds(+ (imp.type_only, imp.deferred), kind+ )continue- seen_raws.add(dedup_key)+ seen_imports[dedup_key] = []module_text = _node_text(module_nodes[0], src).strip().strip("\"'` ")if not module_text:continue- imports.extend(- _statement_imports(stmt_node, module_nodes[0], module_text, raw, language, src)- )+ found = _statement_imports(stmt_node, module_nodes[0], module_text, raw, language, src)+ for imp in found:+ imp.type_only, imp.deferred = kind+ seen_imports[dedup_key] = found+ imports.extend(found)if language == "python":imports = expand_bare_relative_imports(imports)diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex 9f67bfd4a..0cb7ea35c 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -13,6 +13,7 @@ import structlogfrom tree_sitter import Nodefrom .extractors import node_text+from .extractors.bindings.ts_js import is_type_only_ts_js_importfrom .lang_helpers.elixir import (_elixir_call_is_definitional,_elixir_is_template_definition,@@ -81,6 +82,7 @@ __all__ = ["_rust_head_type_identifier","_rust_shadowed_by_type_param","_ts_nested_object_method_owner",+ "import_load_kind","prepare_objectivec_source","prepare_pascal_source",]@@ -169,6 +171,90 @@ def _has_callable_ancestor(return False+# Scopes whose body runs when called, not when the module loads. Its own set,+# not ``symbol_node_types``: a TS ``lexical_declaration`` is a symbol kind, yet+# ``const m = await import("./m")`` at the top level still runs at load.+_TS_JS_FUNCTION_SCOPES = frozenset(+ {+ "function_declaration",+ "generator_function_declaration",+ "function_expression",+ "generator_function",+ "function",+ "arrow_function",+ "method_definition",+ }+)+_LOAD_DEFERRING_SCOPES: dict[str, frozenset[str]] = {+ "python": frozenset({"function_definition", "lambda"}),+ **dict.fromkeys(("typescript", "javascript", "svelte", "vue"), _TS_JS_FUNCTION_SCOPES),+}+# Statements that can be ``import type`` / ``export type``; only these are+# asked, since a ``require`` assignment may bind a variable named ``type``.+_TS_TYPE_STATEMENTS = frozenset({"import_statement", "export_statement"})+# ``typeof import("./m")`` and its kin: erased before anything runs.+_TS_TYPE_POSITIONS = frozenset(+ {"type_query", "type_annotation", "type_alias_declaration", "interface_declaration"}+)+++def _is_type_checking_flag(condition: Node | None, src: str) -> bool:+ """``TYPE_CHECKING`` or ``<module>.TYPE_CHECKING``, matched on the node.++ Ceiling: anything else is runtime, so ``not``/``and``/``or``, parentheses+ and an alias (``from typing import TYPE_CHECKING as TC``) are missed on+ the safe side: the import stays a runtime edge.+ """+ if condition is None:+ return False+ if condition.type == "attribute":+ condition = condition.child_by_field_name("attribute")+ return (+ condition is not None+ and condition.type == "identifier"+ and node_text(condition, src) == "TYPE_CHECKING"+ )+++def _is_type_checking_branch(node: Node, child: Node, src: str) -> bool:+ """``child`` is the body of ``if``/``elif TYPE_CHECKING:``, not an ``else``."""+ if node.type not in ("if_statement", "elif_clause"):+ return False+ if child != node.child_by_field_name("consequence"):+ return False+ return _is_type_checking_flag(node.child_by_field_name("condition"), src)+++def import_load_kind(stmt_node: Node, language: str, src: str) -> tuple[bool, bool]:+ """``(type_only, deferred)`` for an import, from the statement and where it sits.++ Type-only: ``import type`` / ``export type`` (TS), under ``if+ TYPE_CHECKING:`` (Python), or in a type position such as ``typeof+ import()`` (TS), so it never runs. Deferred: inside a function or lambda+ body, so it runs on first call rather than at module load, the usual way to+ break an import cycle on purpose. Type-only wins when both hold. Reads the+ statement and its ancestor chain only.+ """+ scopes = _LOAD_DEFERRING_SCOPES.get(language)+ if scopes is None:+ return False, False+ if stmt_node.type in _TS_TYPE_STATEMENTS and is_type_only_ts_js_import(stmt_node, src):+ return True, False+ deferred = False+ child, node = stmt_node, stmt_node.parent+ while node is not None:+ if node.type in scopes:+ deferred = True+ elif (+ _is_type_checking_branch(node, child, src)+ if language == "python"+ else node.type in _TS_TYPE_POSITIONS+ ):+ return True, False+ child, node = node, node.parent+ return False, deferred++def _qualified_cpp_parent(name_node: Node, src: str) -> str | None:"""Return the parent class for a C/C++ ``Class::method`` definition.diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.pyindex e328140d3..c44b187af 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py@@ -221,7 +221,13 @@ def _summary_payload(opportunities: list[OpportunityModel],statuses: dict[str, str],lead_details: dict[str, Any] | None,+ plan_ids: set[str],) -> dict[str, Any]:+ """The rollup. ``plans_total`` is the plan inventory behind it, split into+ steps, evidence and plans in no opportunity, so the plan and opportunity+ counts reconcile."""+ from ....analysis.health.refactoring.opportunity import claimed_plan_ids+by_type: dict[str, int] = {}by_effort: dict[str, int] = {}by_confidence: dict[str, int] = {}@@ -248,6 +254,9 @@ def _summary_payload("steps_total": mechanical + judgment,"mechanical_steps_total": mechanical,"judgment_steps_total": judgment,+ "plans_total": len(plan_ids),+ "evidence_total": sum(len(item.evidence) for item in opportunities),+ "unattached_plans_total": len(plan_ids - claimed_plan_ids(opportunities)),"by_lead_type": by_type,"by_effort": by_effort,"by_confidence": by_confidence,@@ -423,6 +432,7 @@ async def finalize_refactoring_opportunities(opportunities,statuses=statuses,lead_details=lead_details,+ plan_ids={row.public_id for row in live_plans if row.public_id},analyzed_commit=analyzed_commit,)return sum(1 for state in statuses.values() if state != "resolved")@@ -511,12 +521,13 @@ async def _write_summary(*,statuses: dict[str, str],lead_details: dict[str, Any] | None,+ plan_ids: set[str],analyzed_commit: str | None,) -> None:from ....analysis.health.refactoring.identity import REFACTORING_MODEL_VERSIONpayload = json.dumps(- _summary_payload(opportunities, statuses, lead_details), separators=(",", ":")+ _summary_payload(opportunities, statuses, lead_details, plan_ids), separators=(",", ":"))row = await session.get(RefactoringSummary, repository_id)if row is None:diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex f37a67476..af21e47ae 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -96,6 +96,9 @@ def _update_graph_edge(existing: GraphEdge, edge_data: dict) -> None:type_only = edge_data.get("type_only")if type_only is not None:existing.type_only = bool(type_only)+ deferred = edge_data.get("deferred")+ if deferred is not None:+ existing.deferred = bool(deferred)confidence = edge_data.get("confidence")if confidence is not None:# Keep the max on collision, mirroring the in-memory resolver@@ -123,6 +126,7 @@ def _edge_values(repository_id: str, e: dict) -> dict:"resolution_origin": e.get("resolution_origin"),"call_lines_json": e.get("call_lines_json", "[]"),"type_only": bool(e.get("type_only", False)),+ "deferred": bool(e.get("deferred", False)),}@@ -534,6 +538,7 @@ async def get_all_graph_edges("resolution_origin": row.resolution_origin,"call_lines": call_lines,"type_only": bool(row.type_only),+ "deferred": bool(row.deferred),})return edgesdiff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 9b8e0fde5..9907f557d 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -414,6 +414,12 @@ class GraphEdge(Base):type_only: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=false())+ # True when every import along the edge sits in a function body (a lazy+ # import), so it runs on first call, not at module load. Skipped by cycle+ # detection and persisted for the same reason as ``type_only``.+ deferred: Mapped[bool] = mapped_column(+ Boolean, nullable=False, default=False, server_default=false()+ )created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex b81481419..5b082d123 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -657,22 +657,26 @@ def _changed_file_edges(for u, v, data in graph.edges(data=True):if owner.get(u) not in reconcile:continue- edges.append(- {- "source_node_id": u,- "target_node_id": v,- "imported_names_json": json.dumps(data.get("imported_names", [])),- "edge_type": data.get("edge_type", "imports"),- "confidence": data.get("confidence", 1.0),- "hint_source": data.get("hint_source"),- "resolution_origin": data.get("resolution_origin"),- "call_lines_json": json.dumps(data.get("call_lines", [])),- "type_only": bool(data.get("type_only", False)),- }- )+ edges.append(_edge_row(u, v, data))return sorted(reconcile), edges+def _edge_row(source: str, target: str, data: dict) -> dict:+ """One ``graph_edges`` payload from an in-memory edge; both writers use it."""+ return {+ "source_node_id": source,+ "target_node_id": target,+ "imported_names_json": json.dumps(data.get("imported_names", [])),+ "edge_type": data.get("edge_type", "imports"),+ "confidence": data.get("confidence", 1.0),+ "hint_source": data.get("hint_source"),+ "resolution_origin": data.get("resolution_origin"),+ "call_lines_json": json.dumps(data.get("call_lines", [])),+ "type_only": bool(data.get("type_only", False)),+ "deferred": bool(data.get("deferred", False)),+ }++async def _edges_predate_cohesion(session: Any, repo_id: str, graph_builder: Any) -> bool:"""True when ``graph_edges`` was written before edge cohesion was recorded.@@ -1606,21 +1610,7 @@ async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:# ---- Graph edges ---------------------------------------------------------graph = result.graph_builder.graph()- edges = []- for u, v, data in graph.edges(data=True):- edges.append(- {- "source_node_id": u,- "target_node_id": v,- "imported_names_json": json.dumps(data.get("imported_names", [])),- "edge_type": data.get("edge_type", "imports"),- "confidence": data.get("confidence", 1.0),- "hint_source": data.get("hint_source"),- "resolution_origin": data.get("resolution_origin"),- "call_lines_json": json.dumps(data.get("call_lines", [])),- "type_only": bool(data.get("type_only", False)),- }- )+ edges = [_edge_row(u, v, data) for u, v, data in graph.edges(data=True)]if edges:await batch_upsert_graph_edges(session, repo_id, edges)diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.tsindex e5a1a7d05..bf20899aa 100644--- a/packages/types/src/refactoring.ts+++ b/packages/types/src/refactoring.ts@@ -344,6 +344,12 @@ export interface RefactoringRollupAvailable {steps_total: number;mechanical_steps_total: number;judgment_steps_total: number;+ /** The plan inventory: steps + evidence + unattached. Absent on older indexes. */+ plans_total?: number;+ /** Plans carried as evidence (demoted clones, advisory cycles), not steps. */+ evidence_total?: number;+ /** Plans no opportunity carries; listed only in the plan inventory. */+ unattached_plans_total?: number;by_lead_type: Record<string, number>;by_effort: Record<string, number>;by_confidence: Record<string, number>;diff --git a/tests/unit/cli/test_refactoring_targets_render.py b/tests/unit/cli/test_refactoring_targets_render.pyindex b48f604d7..997e1d3a7 100644--- a/tests/unit/cli/test_refactoring_targets_render.py+++ b/tests/unit/cli/test_refactoring_targets_render.py@@ -78,9 +78,12 @@ def test_markdown_renders_both_plans_as_opportunity_steps(capsys):assert "## Break Cycle plans" not in text# Every step says which kind of change it is, and keeps its own detail.assert "move_method **C.envious**" in text and "`T (t.py)`" in text- assert "break_cycle **cycle[2]: b.py->a.py**" in text- assert "invert b.py -> a.py" in textassert "judgment" in text+ # A cycle is advisory: never a numbered step, still listed with its cut.+ assert "break_cycle **cycle[2]: b.py->a.py**" not in text+ assert "## Unattached observations" in text+ assert "- **cycle[2]: b.py->a.py** (a.py)" in text+ assert "invert b.py -> a.py" in textdef test_markdown_states_the_unknown_primary_problem_rather_than_denying_it(capsys):@@ -95,7 +98,9 @@ def test_json_carries_the_opportunities_beside_the_plans(capsys):_render_refactoring_targets([], [], [_move_method(), _break_cycle()], fmt="json")out = json.loads(capsys.readouterr().out)opportunities = out["refactoring_opportunities"]- assert {o["file_path"] for o in opportunities} == {"a.py", "c.py"}+ # The cycle-only file publishes no opportunity; its plan stays listed.+ assert {o["file_path"] for o in opportunities} == {"c.py"}+ assert "break_cycle" in {p["refactoring_type"] for p in out["refactoring_plans"]}assert all(o["opportunity_id"].startswith("refop") for o in opportunities)# The step ids are the plan ids, so the CLI and the server address one thing.step_ids = [s["plan_id"] for o in opportunities for s in o["steps"]]diff --git a/tests/unit/health/test_refactoring_opportunity.py b/tests/unit/health/test_refactoring_opportunity.pyindex 9c1634c1a..497cee75b 100644--- a/tests/unit/health/test_refactoring_opportunity.py+++ b/tests/unit/health/test_refactoring_opportunity.py@@ -138,6 +138,59 @@ def test_a_high_signal_clone_is_a_step_not_evidence() -> None:assert opportunity.evidence == ()+def cycle(**kwargs) -> RefactoringSuggestion:+ return plan(+ "break_cycle",+ "cycle[2]: svc/api.py->svc/orders.py",+ plan={"cut_edges": [{"from": "svc/api.py", "to": "svc/orders.py"}]},+ evidence={"cycle_size": 2},+ impact_delta=0.0,+ source_biomarker="",+ **kwargs,+ )+++def test_a_cycle_is_evidence_never_a_step_or_the_lead() -> None:+ """Break Cycle is advisory: it rides on the file's work, never leads it,+ so Fix first and the default scope, which read steps, never see it."""+ opportunity = compose_opportunities([cycle(), plan("extract_method")])[0]+ assert [step.refactoring_type for step in opportunity.steps] == ["extract_method"]+ assert opportunity.lead_refactoring_type == "extract_method"+ assert [item.refactoring_type for item in opportunity.evidence] == ["break_cycle"]+++def test_a_file_with_only_a_cycle_publishes_nothing() -> None:+ assert compose_opportunities([cycle()]) == []++[email protected]("dry_violation_shown")+def test_plan_inventory_is_steps_plus_evidence_plus_unattached() -> None:+ """The rollup's plan counts reconcile with the opportunities they fold into."""+ from repowise.core.analysis.health.refactoring.identity import assign_public_ids+ from repowise.core.analysis.health.refactoring.opportunity import claimed_plan_ids+ from repowise.core.persistence.crud.analysis.refactoring_opportunities import (+ _summary_payload,+ )++ rows = [+ plan("extract_method"),+ cycle(),+ clone(intra=True, co_change=0),+ cycle(file_path="svc/only_cycle.py"),+ ]+ opportunities = compose_opportunities(rows)+ plan_ids = set(assign_public_ids(rows))+ summary = _summary_payload(opportunities, {}, None, plan_ids)+ steps = sum(item.step_count for item in opportunities)+ assert summary["evidence_total"] == 2 # the cycle and the clone in orders.py+ assert summary["unattached_plans_total"] == 1 # the cycle-only file+ assert summary["plans_total"] == 4+ assert summary["plans_total"] == (+ steps + summary["evidence_total"] + summary["unattached_plans_total"]+ )+ assert len(plan_ids - claimed_plan_ids(opportunities)) == 1++# --------------------------------------------------------------------------# ordering# --------------------------------------------------------------------------diff --git a/tests/unit/ingestion/test_import_load_kind.py b/tests/unit/ingestion/test_import_load_kind.pynew file mode 100644index 000000000..90d48c90d--- /dev/null+++ b/tests/unit/ingestion/test_import_load_kind.py@@ -0,0 +1,232 @@+"""Imports that never run at module load do not close an import cycle.++Python ``if TYPE_CHECKING:`` imports and TS ``typeof import()`` are type-only;+an import inside a function body is deferred. Both stay in the graph for+reachability and leave cycle detection, so a deliberate lazy-import pair is+not a ``break_cycle`` plan while a real runtime cycle still is.+"""++from __future__ import annotations++from datetime import datetime++import pytest++from repowise.core.analysis.health.refactoring import (+ RefactoringContext,+ build_file_scc_index,+ detect_refactorings,+)+from repowise.core.ingestion.graph import GraphBuilder+from repowise.core.ingestion.models import FileInfo, Import, combine_load_kinds+from repowise.core.ingestion.parser import ASTParser+++def _info(path: str) -> FileInfo:+ language = "python" if path.endswith(".py") else "typescript"+ return FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language=language,+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _kinds(path: str, source: str) -> dict[str, tuple[bool, bool]]:+ parsed = ASTParser().parse_file(_info(path), source.encode("utf-8"))+ return {imp.module_path: (imp.type_only, imp.deferred) for imp in parsed.imports}+++def _builder(files: dict[str, str]) -> GraphBuilder:+ parser = ASTParser()+ builder = GraphBuilder()+ for path, source in files.items():+ builder.add_file(parser.parse_file(_info(path), source.encode("utf-8")))+ builder.build()+ return builder+++def _cycles(builder: GraphBuilder) -> list:+ graph = builder.graph()+ out = []+ for path in sorted(n for n, d in graph.nodes(data=True) if d.get("node_type") == "file"):+ ctx = RefactoringContext(+ file_path=path,+ language="python",+ nloc=50,+ graph=graph,+ file_scc=build_file_scc_index(graph).get(path),+ )+ out += [s for s in detect_refactorings(ctx) if s.refactoring_type == "break_cycle"]+ return out+++PY_SOURCE = """\+from typing import TYPE_CHECKING+import typing+if TYPE_CHECKING:+ from .context import Ctx+else:+ from .other import Other+if typing.TYPE_CHECKING:+ from .types import T+def handler():+ from .command import claim+ if TYPE_CHECKING:+ from .hinted import H+class Box:+ from .attrs import field+ def method(self):+ from .lazy import thing+if not TYPE_CHECKING:+ from .negated import N+if not typing.TYPE_CHECKING:+ from .negated_attr import NA+if sys.version_info > (3, 11):+ pass+elif TYPE_CHECKING:+ from .elif_branch import E+from typing import TYPE_CHECKING as TC+if TC:+ from .aliased import A+"""+++ ("module", "expected"),+ [+ (".context", (True, False)), # if TYPE_CHECKING:+ (".other", (False, False)), # its else branch runs+ (".types", (True, False)), # typing.TYPE_CHECKING+ (".command", (False, True)), # function-local+ (".hinted", (True, False)), # type-only wins inside a function+ (".attrs", (False, False)), # a class body runs at load+ (".lazy", (False, True)), # method body+ (".negated", (False, False)), # `if not TYPE_CHECKING:` runs+ (".negated_attr", (False, False)),+ (".elif_branch", (True, False)),+ # Ceiling: an alias is not recognised, so the import stays runtime.+ (".aliased", (False, False)),+ ],+)+def test_python_import_load_kind(module: str, expected: tuple[bool, bool]) -> None:+ assert _kinds("pkg/a.py", PY_SOURCE)[module] == expected+++TS_SOURCE = """\+export type Probe = typeof import("./probe.js").probe;+const load = makeLoader(() => import("./runtime.js"));+async function f() { const r = require("./req.js"); }+const top = await import("./top.js");+"""+++ ("module", "expected"),+ [+ ("./probe.js", (True, False)), # typeof import(): a type position+ ("./runtime.js", (False, True)), # lazy loader+ ("./req.js", (False, True)), # require in a function+ ("./top.js", (False, False)), # top-level await runs at load+ ],+)+def test_ts_import_load_kind(module: str, expected: tuple[bool, bool]) -> None:+ assert _kinds("src/a.ts", TS_SOURCE)[module] == expected+++ ("source", "expected"),+ [+ # A lazy copy first must not hide the load-time twin: runtime wins.+ ("def f():\n from .b import x\n\nfrom .b import x\n", (False, False)),+ ("from .b import x\n\ndef f():\n from .b import x\n", (False, False)),+ ("if TYPE_CHECKING:\n from .b import x\ndef f():\n from .b import x\n", (False, True)),+ ],+)+def test_a_repeated_statement_is_one_import_with_the_earliest_kind(+ source: str, expected: tuple[bool, bool]+) -> None:+ parsed = ASTParser().parse_file(_info("pkg/a.py"), source.encode("utf-8"))+ same = [imp for imp in parsed.imports if imp.module_path == ".b"]+ assert len(same) == 1 # non-graph consumers see no duplicate+ assert (same[0].type_only, same[0].deferred) == expected+++R, T, D = (False, False), (True, False), (False, True)+++ ("first", "second", "expected"),+ [(T, T, T), (T, D, D), (D, T, D), (D, D, D), (D, R, R), (R, D, R), (T, R, R), (R, T, R)],+)+def test_combine_load_kinds(first, second, expected) -> None:+ assert combine_load_kinds(first, second) == expected+++ ("first", "second", "expected"),+ [(T, T, T), (T, D, D), (D, T, D), (D, R, R), (R, D, R)],+)+def test_an_edge_folds_its_imports_load_kinds(first, second, expected) -> None:+ from repowise.core.ingestion.graph.builder import _merge_load_kind++ data: dict = {"type_only": first[0], **({"deferred": True} if first[1] else {})}+ imp = Import("x", "b", [], True, None, type_only=second[0], deferred=second[1])+ _merge_load_kind(data, imp)+ assert (data["type_only"], bool(data.get("deferred"))) == expected+ assert data.get("deferred", True) is True # stored only when true+++def test_type_checking_and_lazy_import_pair_is_no_cycle() -> None:+ """The resolvers/context.py <-> ruby_rails.py shape: one side imports under+ TYPE_CHECKING, the other inside a function."""+ builder = _builder(+ {+ "pkg/context.py": "def resolve():\n from .rails import go\n return go()\n",+ "pkg/rails.py": (+ "from typing import TYPE_CHECKING\n"+ "if TYPE_CHECKING:\n from .context import Ctx\n"+ "def go():\n return 1\n"+ ),+ }+ )+ graph = builder.graph()+ # The edges stay for reachability, marked.+ assert graph["pkg/context.py"]["pkg/rails.py"]["deferred"] is True+ assert graph["pkg/rails.py"]["pkg/context.py"]["type_only"] is True+ cycle_view = builder.cycle_subgraph()+ assert not cycle_view.has_edge("pkg/context.py", "pkg/rails.py")+ assert not cycle_view.has_edge("pkg/rails.py", "pkg/context.py")+ assert build_file_scc_index(graph) == {}+ assert _cycles(builder) == []+++def test_a_runtime_cycle_is_still_a_plan() -> None:+ builder = _builder(+ {+ "pkg/a.py": "from .b import y\nx = 1\n",+ "pkg/b.py": "from .a import x\ny = 2\n",+ }+ )+ plans = _cycles(builder)+ assert len(plans) == 1+ assert set(plans[0].plan["cycle"]) == {"pkg/a.py", "pkg/b.py"}+++def test_one_load_time_import_makes_the_edge_runtime() -> None:+ builder = _builder(+ {+ "pkg/a.py": "def f():\n from .b import y\nfrom .b import z\n",+ "pkg/b.py": "def g():\n from .a import f\ny = z = 1\n",+ }+ )+ graph = builder.graph()+ assert not graph["pkg/a.py"]["pkg/b.py"].get("deferred")+ assert graph["pkg/b.py"]["pkg/a.py"]["deferred"] is True+ assert build_file_scc_index(graph) == {}diff --git a/tests/unit/persistence/test_graph_edge_type_only.py b/tests/unit/persistence/test_graph_edge_type_only.pyindex c01b15e63..159a417aa 100644--- a/tests/unit/persistence/test_graph_edge_type_only.py+++ b/tests/unit/persistence/test_graph_edge_type_only.py@@ -53,3 +53,56 @@ async def test_graph_edge_type_only_round_trips_through_database(async_session)assert rehydrated.graph()["b.ts"]["a.ts"]["type_only"] is Trueassert rehydrated.cycle_subgraph().number_of_edges() == 0assert build_file_scc_index(rehydrated.graph()) == {}+++async def test_graph_edge_deferred_round_trips_through_database(async_session) -> None:+ """A function-local import's mark survives rehydration, so an update does+ not bring back the lazy-import cycle the full index suppressed."""+ repo = await insert_repo(async_session)+ nodes = [+ {"node_id": "a.py", "node_type": "file", "language": "python"},+ {"node_id": "b.py", "node_type": "file", "language": "python"},+ ]+ edges = [+ {"source_node_id": "a.py", "target_node_id": "b.py", "edge_type": "imports"},+ {+ "source_node_id": "b.py",+ "target_node_id": "a.py",+ "edge_type": "imports",+ "deferred": True,+ },+ ]+ await batch_upsert_graph_nodes(async_session, repo.id, nodes)+ await batch_upsert_graph_edges(async_session, repo.id, edges)+ await async_session.commit()++ loaded = {+ (e["source_node_id"], e["target_node_id"]): e+ for e in await get_all_graph_edges(async_session, repo.id)+ }+ assert loaded[("b.py", "a.py")]["deferred"] is True+ assert loaded[("a.py", "b.py")]["deferred"] is False++ rehydrated = GraphBuilder.from_persisted(+ await get_all_graph_nodes(async_session, repo.id), list(loaded.values())+ )+ assert rehydrated.graph()["b.py"]["a.py"]["deferred"] is True+ assert build_file_scc_index(rehydrated.graph()) == {}+++def test_incremental_edge_path_carries_the_load_kind() -> None:+ """The incremental writer emits the same row as the full one, marks included."""+ from types import SimpleNamespace++ from repowise.core.pipeline.persist import _changed_file_edges, _edge_row++ builder = GraphBuilder()+ graph = builder.graph()+ graph.add_node("a.py", node_type="file")+ graph.add_node("b.py", node_type="file")+ graph.add_edge("a.py", "b.py", edge_type="imports", type_only=False, deferred=True)+ parsed = [SimpleNamespace(file_info=SimpleNamespace(path="a.py"))]++ _, rows = _changed_file_edges(builder, parsed, ["a.py"])+ assert rows == [_edge_row("a.py", "b.py", graph["a.py"]["b.py"])]+ assert rows[0]["deferred"] is True and rows[0]["type_only"] is Falsediff --git a/tests/unit/server/test_refactoring_summary_golden.py b/tests/unit/server/test_refactoring_summary_golden.pyindex cdc559697..6ade35417 100644--- a/tests/unit/server/test_refactoring_summary_golden.py+++ b/tests/unit/server/test_refactoring_summary_golden.py@@ -44,7 +44,7 @@ def test_summary_counts_and_threshold_edges() -> None:{"type": "split_file", "count": 1},],"files_total": 5,- "structural_total": 4,+ "structural_total": 3, # break_cycle is advisory: counted in by_type only"performance_total": 1,"small_effort_total": 3,"health_recovery_total": 6,@@ -68,9 +68,9 @@ def test_summary_of_nothing() -> None:def test_structural_lens() -> None:+ # break_cycle is advisory: evidence on an opportunity, never a structural lead.assert set(refactoring._STRUCTURAL_TYPES) == {"split_file",- "break_cycle","extract_class","move_method",}