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.

feat(refactoring): warn when a plan changes a symbol a package exports (#3485)

Raghav Chamadiyadef8bac8fb9f
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index c2e6caea7..bb816d2e6 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -115,7 +115,8 @@ Plan detail also lists `risks`, one sentence each, to read before applying the
plan: an accepted decision that governs the file, callers or importers of what
the plan moves, a target nothing reaches (delete it instead), and recent commits
on the same lines, and a test the plan runs that asserts on the function's own
-source text. A governed plan's steps are `judgment`, and its
+source text. When the plan changes a symbol a package exports to its consumers,
+the risk names the file exporting it. A governed plan's steps are `judgment`, and its
`blast_radius.co_change_partners` names the files that usually change with it.
A newly accepted decision shows here after the next index or update.
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 4b339de7b..4649ab97d 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1217,6 +1217,18 @@ async def _persist_full_update_async(
except Exception as exc:
_skip("Doc-drift persist", exc)
+ # Re-persist graph_nodes so symbol-level PageRank / betweenness /
+ # community ids reflect the current build. 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)
+ except Exception as exc:
+ _skip("Graph nodes persist", exc)
+
# Code-health findings + metrics (partial — upsert only).
if partial_health_report is not None:
try:
@@ -1248,16 +1260,6 @@ async def _persist_full_update_async(
except Exception as exc:
_skip("Dead-code persist", exc)
- # Re-persist graph_nodes so symbol-level PageRank / betweenness /
- # community ids reflect the current build.
- 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)
- except Exception as exc:
- _skip("Graph nodes persist", exc)
-
# Refresh wiki_symbols for the changed files (upsert + within-file
# prune). Without this, symbol bounds fossilize at the last full
# index and the get_answer hydrator serves drifted signatures.
@@ -1578,6 +1580,10 @@ async def _rescore_health_from_db(
f"[yellow]{len(report.findings)} findings[/yellow]"
)
+ # Graph nodes first: the plan annotations the writer below stores
+ # read each symbol's ``public_api`` from them.
+ await persist_graph_nodes(session, repo_id, graph_builder)
+
# Same writer the index's analysis phase uses, so a re-score leaves
# the derived queues agreeing with the findings it just replaced
# rather than describing the set it deleted. Read HEAD off disk:
@@ -1615,7 +1621,6 @@ async def _rescore_health_from_db(
ingested_commit_sha=live_head,
provenance=coverage.provenance,
)
- await persist_graph_nodes(session, repo_id, graph_builder)
await _rescore()
diff --git a/packages/core/alembic/versions/0107_graph_node_public_api.py b/packages/core/alembic/versions/0107_graph_node_public_api.py
new file mode 100644
index 000000000..7a81d1e7f
--- /dev/null
+++ b/packages/core/alembic/versions/0107_graph_node_public_api.py
@@ -0,0 +1,30 @@
+"""Add ``graph_nodes.public_api``: the file a package exports a symbol from.
+
+Local SQLite stores get the column from ``init_db``; this migration covers
+managed Postgres. Values appear on the next index.
+
+Revision ID: 0107
+Revises: 0106
+Create Date: 2026-10-11
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0107"
+down_revision: str | None = "0106"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column("graph_nodes", sa.Column("public_api", sa.Text(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("graph_nodes", "public_api")
diff --git a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
index fb1aad46e..3d573650a 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
@@ -45,34 +45,12 @@ from typing import Any
from repowise.core.entry_candidacy import is_reachability_root
from repowise.core.ids import SYMBOL_SEP, file_path_of, is_external
+from ...ingestion.barrels import BARREL_FILENAMES
from .constants import never_flag_path
from .cpp_reachability import build_cpp_package_files, is_cpp_file_reachable, is_cpp_path
from .go_reachability import build_go_package_files, is_go_file_reachable
from .jvm_reachability import build_jvm_package_files, is_jvm_file_reachable
-#: Re-export barrel filenames. A barrel aggregates other modules' symbols and
-#: is reached by importing those names (or, for a package's public entry, via
-#: package.json ``exports``/``main``), so a barrel with no inbound graph edge
-#: is not unreachable.
-#:
-#: Scope note for the analyzer: this rescues a file in the *unreachable-file*
-#: pass only. It is NOT applied in the unused-export pass — a genuine symbol
-#: defined in a barrel that nobody imports should still be flagged.
-BARREL_FILENAMES: frozenset[str] = frozenset(
- {
- "__init__.py",
- "index.ts",
- "index.tsx",
- "index.js",
- "index.jsx",
- "index.mts",
- "index.cts",
- "index.mjs",
- "index.cjs",
- "mod.rs",
- }
-)
-
#: Edge types that record association rather than dependency. A co-change edge
#: says two files were committed together, which is not a path any code can
#: take, so it must not answer "does anything import this".
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
index be9169011..95bfc719f 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
@@ -26,7 +26,7 @@ from ....co_change import parse_partners
from ....persistence.crud.analysis.dead_code import get_dead_code_findings
from ....persistence.crud.authority import governing_decisions_by_file
from ....persistence.crud.git import get_git_metadata_bulk
-from ....persistence.models import GitCommit, GitFunctionBlame, Repository
+from ....persistence.models import GitCommit, GitFunctionBlame, GraphNode, Repository
from ..queue.eligibility import DeadSpan, dead_spans, dead_target
from .extract_helper import ACTIVE_CO_CHANGE
from .models import RefactoringSuggestion
@@ -42,6 +42,8 @@ ACTIVE_EDIT_MIN_COMMITS = 2
_HISTORY_WINDOWS = 2
MAX_CO_CHANGE_PARTNERS = 5
_MAX_DECISION_RISKS = 3
+#: Exported symbols one risk names before counting the rest.
+_MAX_NAMED = 3
#: Kinds that move a symbol out of its file, so its consumers see the change.
_RELOCATING = frozenset({"split_file", "extract_class", "move_method"})
#: The blast-radius key each file-level builder writes its dependents under.
@@ -119,7 +121,9 @@ class AnnotationFacts:
recent from all, which is no signal rather than a quiet target. ``dead``
is the sure dead-code spans by file (:func:`..queue.eligibility.dead_spans`).
``sources_read`` is, per test file the plans run, the ``getsource``
- arguments it passes (:data:`_GETSOURCE`).
+ arguments it passes (:data:`_GETSOURCE`). ``exported`` is, per file, its
+ symbols a package exports and the file exporting each
+ (``graph_nodes.public_api``).
"""
decisions: Mapping[str, list[tuple[str, str]]] = field(default_factory=dict)
@@ -128,6 +132,7 @@ class AnnotationFacts:
recent: Mapping[str, tuple[datetime, str]] | None = None
dead: Mapping[str, list[DeadSpan]] = field(default_factory=dict)
sources_read: Mapping[str, frozenset[str]] = field(default_factory=dict)
+ exported: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
def annotate(
@@ -146,7 +151,7 @@ def annotate(
]
for risk in (
_dead_code_risk(suggestion, facts.dead),
- _public_api_risk(suggestion),
+ _public_api_risk(suggestion, facts.exported),
_active_edit_risk(suggestion, facts),
_source_text_risk(suggestion, tests, facts.sources_read),
):
@@ -171,7 +176,20 @@ def _dead_code_risk(
return PlanRisk("dead_code", f"Nothing reaches {what}; delete it instead of refactoring it.")
-def _public_api_risk(suggestion: RefactoringSuggestion) -> PlanRisk | None:
+def _public_api_risk(
+ suggestion: RefactoringSuggestion, exported: Mapping[str, Mapping[str, str]]
+) -> PlanRisk | None:
+ """One ``public_api`` risk: callers inside the repo of what the plan moves,
+ then the exported symbols it changes, which code outside the repo may call."""
+ texts = [
+ risk.text
+ for risk in (_relocation_risk(suggestion), _exported_risk(suggestion, exported))
+ if risk is not None
+ ]
+ return PlanRisk("public_api", " ".join(texts)) if texts else None
+
+
+def _relocation_risk(suggestion: RefactoringSuggestion) -> PlanRisk | None:
"""Consumers of a symbol the plan moves out of its file, from its own blast radius."""
kind = suggestion.refactoring_type
if kind not in _RELOCATING:
@@ -201,6 +219,32 @@ def _public_api_risk(suggestion: RefactoringSuggestion) -> PlanRisk | None:
return PlanRisk("public_api", text)
+def _exported_risk(
+ suggestion: RefactoringSuggestion, exported: Mapping[str, Mapping[str, str]]
+) -> PlanRisk | None:
+ """The symbols the plan changes that a package exports, at most three named."""
+ # Deferred: recommendations imports this module.
+ from .recommendations import target_symbol_ids
+
+ in_file = exported.get(suggestion.file_path) or {}
+ # Spans with no line bounds: only named symbols match, never by enclosing lines.
+ spans = [(symbol_id, 0, 0) for symbol_id in in_file]
+ hits = target_symbol_ids(suggestion, suggestion.file_path, None, spans)
+ if not hits:
+ return None
+ if len(hits) == 1:
+ text = f"{_dotted(hits[0])} is exported from `{in_file[hits[0]]}`; changing its signature"
+ else:
+ named = ", ".join(f"{_dotted(hit)} (from `{in_file[hit]}`)" for hit in hits[:_MAX_NAMED])
+ more = f" and {len(hits) - _MAX_NAMED} more" if len(hits) > _MAX_NAMED else ""
+ text = f"{named}{more} are exported; changing their signatures"
+ return PlanRisk("public_api", f"{text} breaks consumers outside the repo.")
+
+
+def _dotted(symbol_id: str) -> str:
+ return f"`{symbol_id.split('::', 1)[1].replace('::', '.')}`"
+
+
def _active_edit_risk(suggestion: RefactoringSuggestion, facts: AnnotationFacts) -> PlanRisk | None:
"""Recent commits on the functions the plan's lines sit in. Function blame is
the finest stored grain, so a span inside a long function counts all of it."""
@@ -346,9 +390,30 @@ async def load_annotation_facts(
recent=recent,
dead=dead_spans(dead),
sources_read=_sources_read(Path(root), _test_files(tests)) if root else {},
+ exported=await _exported_symbols(session, repository_id, files),
)
+async def _exported_symbols(
+ session: AsyncSession, repository_id: str, files: Sequence[str]
+) -> dict[str, dict[str, str]]:
+ """Per plan file, its exported symbols and the file exporting each; one
+ query per chunk of files, not per file."""
+ out: dict[str, dict[str, str]] = {}
+ for index in range(0, len(files), _BATCH):
+ rows = await session.execute(
+ select(GraphNode.file_path, GraphNode.node_id, GraphNode.public_api).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.file_path.in_(list(files[index : index + _BATCH])),
+ GraphNode.public_api.is_not(None),
+ GraphNode.public_api != "",
+ )
+ )
+ for path, node_id, root in rows:
+ out.setdefault(path, {})[node_id] = root
+ return out
+
+
def _partners(meta: Any) -> tuple[tuple[str, int], ...]:
"""Files that changed with this one often enough to update together."""
strong = sorted(
diff --git a/packages/core/src/repowise/core/generation/context/public_api.py b/packages/core/src/repowise/core/analysis/public_api.py
similarity index 62%
rename from packages/core/src/repowise/core/generation/context/public_api.py
rename to packages/core/src/repowise/core/analysis/public_api.py
index 77610e79f..785cc6908 100644
--- a/packages/core/src/repowise/core/generation/context/public_api.py
+++ b/packages/core/src/repowise/core/analysis/public_api.py
@@ -1,4 +1,4 @@
-"""The Public API of a page's files, computed from manifests and re-exports.
+"""The Public API of a package, computed from manifests and re-exports.
A package's public surface is what a consumer can import from it: whatever its
manifest names as the start (``package.json`` ``bin``/``main``/``exports["."]``,
@@ -6,16 +6,20 @@ manifest names as the start (``package.json`` ``bin``/``main``/``exports["."]``,
``FileInfo.is_manifest_entry``) declares or re-exports through barrels. It is
read off the parsed imports, never guessed by a model, so a class that nothing
in the repo imports still appears when the package's front door publishes it.
+
+Two readers share it: a wiki page's Public API section, and the per-symbol
+``public_api`` flag the graph carries (:func:`stamp_public_api`).
"""
from __future__ import annotations
from collections.abc import Iterable, Mapping
+from collections.abc import Set as AbstractSet
from pathlib import Path, PurePosixPath
from typing import Any
-from repowise.core.analysis.dead_code.file_reachability import BARREL_FILENAMES
-from repowise.core.ingestion.package_roots import module_for
+from repowise.core.ingestion.barrels import BARREL_FILENAMES
+from repowise.core.ingestion.package_roots import module_for, package_roots_from_paths
from repowise.core.workspace.code_api import dunder_all
# A Rust ``impl`` block is not a name anyone imports.
@@ -187,3 +191,102 @@ def compute_public_api(
first = first_name.setdefault(key, name)
api.append(_entry(name, sym, path, "" if first == name else first))
return api
+
+
+def _is_declared_entry(pf: Any, entries: AbstractSet[str]) -> bool:
+ """Where a manifest says its package starts: a distribution's ``__init__.py``,
+ a ``package.json`` entry or ``exports`` subpath (*entries*). A Python
+ module a console script runs is not one: nothing imports from it."""
+ info = pf.file_info
+ if info.path in entries:
+ return True
+ if not getattr(info, "is_manifest_entry", False):
+ return False
+ return info.language != "python" or PurePosixPath(info.path).name == "__init__.py"
+
+
+def _is_launcher(pf: Any) -> bool:
+ """A Python module a console script runs, which makes its package an application."""
+ info = pf.file_info
+ return (
+ bool(getattr(info, "is_manifest_entry", False))
+ and info.language == "python"
+ and PurePosixPath(info.path).name != "__init__.py"
+ )
+
+
+def _imported_from_other_packages(
+ parsed: Mapping[str, Any], owner: Mapping[str, str | None]
+) -> set[str]:
+ """Files a non-test file of another package imports."""
+ out: set[str] = set()
+ for path, pf in parsed.items():
+ if pf.file_info.is_test:
+ continue
+ for imp in pf.imports:
+ target = imp.resolved_file
+ if target in owner and owner[target] != owner[path]:
+ out.add(target)
+ return out
+
+
+def export_roots(parsed: Mapping[str, Any], entries: AbstractSet[str] = frozenset()) -> list[str]:
+ """The files whose exports reach consumers, never a test file.
+
+ A manifest-declared entry always is. A barrel is when another package in
+ the repository imports through it, or when its package has no consumer
+ here and runs no console script: a library whose consumers live outside.
+ A barrel only its own package reads, in a package other packages consume
+ or in an application, is internal.
+ """
+ packages = package_roots_from_paths(set(parsed))
+ owner = {path: module_for(path, packages) for path in parsed}
+ imported = _imported_from_other_packages(parsed, owner)
+ closed = {owner[path] for path in imported}
+ closed |= {owner[path] for path, pf in parsed.items() if _is_launcher(pf)}
+ roots: list[str] = []
+ for path, pf in sorted(parsed.items()):
+ if pf.file_info.is_test:
+ continue
+ if _is_declared_entry(pf, entries) or (PurePosixPath(path).name in BARREL_FILENAMES and (
+ path in imported or owner[path] not in closed
+ )):
+ roots.append(path)
+ return roots
+
+
+def public_symbols(
+ parsed: Mapping[str, Any], entries: AbstractSet[str] = frozenset()
+) -> dict[str, str]:
+ """``{symbol id: the file that exports it}`` for every symbol consumers can import.
+
+ Exported means a barrel or a package entry publishes it (re-exports and
+ ``__all__`` followed as for :func:`compute_public_api`); a public method
+ of an exported class is exported with it. *entries* are the files a
+ ``package.json`` ``exports`` map names (:func:`export_roots`).
+ """
+ resolver = _Resolver(parsed)
+ out: dict[str, str] = {}
+ for root in export_roots(parsed, entries):
+ for _name, sym, declared_in in resolver.exported(root):
+ if sym is not None and not parsed[declared_in].file_info.is_test:
+ out.setdefault(sym.id, root)
+ for path, pf in parsed.items():
+ for sym in pf.symbols:
+ owner = out.get(f"{path}::{sym.parent_name}") if sym.parent_name else None
+ if owner is not None and sym.visibility == "public":
+ out.setdefault(sym.id, owner)
+ return out
+
+
+def stamp_public_api(graph: Any, parsed: Mapping[str, Any]) -> None:
+ """Set ``public_api`` on every symbol node: the exporting file, or ``""``."""
+ entries = {
+ path for path in parsed if graph.nodes.get(path, {}).get("package_export")
+ }
+ exported = public_symbols(parsed, entries)
+ for pf in parsed.values():
+ for sym in pf.symbols:
+ node = graph.nodes.get(sym.id)
+ if node is not None:
+ node["public_api"] = exported.get(sym.id, "")
diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.py
index 14d6dbad1..4c577dcf9 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -17,9 +17,9 @@ import structlog
from repowise.core.ids import is_external
from repowise.core.ingestion.package_roots import package_roots_from_paths
+from ...analysis.public_api import compute_public_api
from .. import onboarding as _onboarding
from ..concept_tree.grouping import package_file_counts
-from ..context.public_api import compute_public_api
from ..context_assembler import FilePageContext
from ..models import compute_page_id
from .helpers import _is_infra_file, decisions_for_files, rank_decisions
diff --git a/packages/core/src/repowise/core/ingestion/barrels.py b/packages/core/src/repowise/core/ingestion/barrels.py
new file mode 100644
index 000000000..ce3b8e2fa
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/barrels.py
@@ -0,0 +1,29 @@
+"""File names that re-export other modules' symbols (barrels).
+
+A leaf with no imports, so ingestion and analysis can both read it.
+"""
+
+from __future__ import annotations
+
+#: Re-export barrel filenames. A barrel aggregates other modules' symbols and
+#: is reached by importing those names (or, for a package's public entry, via
+#: package.json ``exports``/``main``), so a barrel with no inbound graph edge
+#: is not unreachable.
+#:
+#: Scope note for the analyzer: this rescues a file in the *unreachable-file*
+#: pass only. It is NOT applied in the unused-export pass — a genuine symbol
+#: defined in a barrel that nobody imports should still be flagged.
+BARREL_FILENAMES: frozenset[str] = frozenset(
+ {
+ "__init__.py",
+ "index.ts",
+ "index.tsx",
+ "index.js",
+ "index.jsx",
+ "index.mts",
+ "index.cts",
+ "index.mjs",
+ "index.cjs",
+ "mod.rs",
+ }
+)
diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
index 58b770953..fa6fd76cc 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
@@ -38,6 +38,7 @@ _NODE_ATTR_KEYS = (
"is_entry_point",
"is_reachability_root",
"always_run_reason",
+ "public_api",
"kind",
"name",
"qualified_name",
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 705e9a7dc..394ed0a7b 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -14,6 +14,7 @@ from typing import Any
import networkx as nx
import structlog
+from ...analysis.public_api import stamp_public_api
from ..cohesion import (
MODULE_DECLARATION_HINT,
SAME_PACKAGE_HINT,
@@ -649,6 +650,12 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# Post-pass: needs heritage resolved and reads only the graph.
self._resolve_override_dispatch(progress=progress)
+ # Which symbols a package exports, read off the imports just resolved.
+ try:
+ stamp_public_api(self._graph, self._parsed_files)
+ except Exception as exc: # a reader bug must not fail the index
+ log.warning("public_api_stamp_failed", error=str(exc))
+
self._built = True
# Keep the resolver-built DotNetProjectIndex reachable after the
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index 785f44904..5d76fa825 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -411,6 +411,12 @@ def _warmup_typescript(ctx: ResolverContext) -> None:
if graph is None:
return
parsed = getattr(ctx, "parsed_files", None) or {}
+ # Every file a ``package.json`` publishes, subpaths included, for the
+ # per-symbol public API flag (``analysis.public_api``).
+ for path in index.exports_entry_paths | index.manifest_entry_paths:
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["package_export"] = True
for path in index.manifest_entry_paths:
_stamp_entry(graph, parsed, path)
pf = parsed.get(path)
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index af21e47ae..29f8a2262 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -61,6 +61,7 @@ _NODE_FIELDS = (
"is_entry_point",
"is_reachability_root",
"always_run_reason",
+ "public_api",
"pagerank",
"betweenness",
"betweenness_commit",
@@ -490,6 +491,7 @@ async def get_all_graph_nodes(
"is_entry_point": row.is_entry_point,
"is_reachability_root": row.is_reachability_root,
"always_run_reason": row.always_run_reason,
+ "public_api": row.public_api,
"kind": row.kind,
"name": row.name,
"qualified_name": row.qualified_name,
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 6fef880f6..d5ca55a7b 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -295,6 +295,10 @@ class GraphNode(Base):
# or runs the project in a child process). "" on a test checked and found
# ordinary; NULL on a test never checked (an older index) and on non-tests.
always_run_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
+ # On a symbol a package exports, the barrel or entry file exporting it
+ # (``analysis.public_api``); "" on one checked and not exported; NULL on
+ # file nodes and on symbols never checked (an older index).
+ public_api: Mapped[str | None] = mapped_column(Text, nullable=True)
pagerank: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
betweenness: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
# The commit ``betweenness`` was last actually computed at. Betweenness is
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 382552e67..5c3cb623b 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -2139,21 +2139,14 @@ async def persist_incremental_index(
# run, so a skipped write heals itself on the next update.
_skip("Doc-drift 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)
-
# 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.
+ # 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
@@ -2162,6 +2155,15 @@ async def persist_incremental_index(
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
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 35b1f8436..bb5a65ce4 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -509,6 +509,7 @@ async def persist_graph_nodes(
"visibility": data.get("visibility"),
"signature": data.get("signature"),
"parent_symbol_id": data.get("parent_name"),
+ "public_api": data.get("public_api"),
}
)
nodes.append(node_dict)
diff --git a/tests/unit/analysis/test_public_api_flag.py b/tests/unit/analysis/test_public_api_flag.py
new file mode 100644
index 000000000..2f5ef9cf3
--- /dev/null
+++ b/tests/unit/analysis/test_public_api_flag.py
@@ -0,0 +1,90 @@
+"""Which symbols a package exports, stamped on the graph per symbol."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.traverser import FileTraverser
+
+_REPO = {
+ # A library another package here imports, and an application that runs a
+ # console script.
+ "lib/pyproject.toml": '[project]\nname = "lib"\n',
+ "lib/lib/__init__.py": "from .core import Client, internal\n__all__ = ['Client']\n",
+ "lib/lib/core.py": (
+ "from .hidden import helper\n\n"
+ "class Client:\n def send(self):\n pass\n\n def _retry(self):\n pass\n\n"
+ "def internal():\n pass\n\ndef unlisted():\n pass\n"
+ ),
+ "lib/lib/store/__init__.py": "from .disk import Store\n",
+ "lib/lib/store/disk.py": "class Store:\n pass\n",
+ "lib/lib/hidden/__init__.py": "from .impl import helper\n",
+ "lib/lib/hidden/impl.py": "def helper():\n pass\n",
+ "app/pyproject.toml": (
+ '[project]\nname = "app"\n[project.scripts]\napp = "app.main:run"\n'
+ ),
+ "app/app/__init__.py": "",
+ "app/app/main.py": (
+ "from lib.store import Store\nfrom app.schemas import Model\n\ndef run():\n pass\n"
+ ),
+ "app/app/schemas/__init__.py": "from .models import Model\n",
+ "app/app/schemas/models.py": "class Model:\n pass\n",
+ "tests/__init__.py": "from .helpers import fixture\n",
+ "tests/helpers.py": "def fixture():\n pass\n",
+ "package.json": json.dumps({"private": True, "workspaces": ["web"]}),
+ "web/package.json": json.dumps(
+ {"name": "web", "exports": {".": "./src/main.ts", "./extra": "./src/extra.ts"}}
+ ),
+ "web/src/main.ts": "export { render } from './render';\n",
+ "web/src/render.ts": "export function render(): void {}\nexport function hidden(): void {}\n",
+ "web/src/extra.ts": "export function extra(): void {}\n",
+}
+
+
+def build_fixture(repo: Path) -> GraphBuilder:
+ for rel, body in _REPO.items():
+ (repo / rel).parent.mkdir(parents=True, exist_ok=True)
+ (repo / rel).write_text(body, encoding="utf-8")
+ parser = ASTParser()
+ builder = GraphBuilder(repo)
+ for fi in FileTraverser(repo).traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ builder.build()
+ return builder
+
+
+EXPORTED = {
+ "lib/lib/core.py::Client": "lib/lib/__init__.py",
+ "lib/lib/core.py::Client::send": "lib/lib/__init__.py",
+ "lib/lib/store/disk.py::Store": "lib/lib/store/__init__.py",
+ "web/src/render.ts::render": "web/src/main.ts",
+ "web/src/extra.ts::extra": "web/src/extra.ts",
+}
+
+
+def test_exported_symbols_carry_the_file_that_exports_them(tmp_path: Path) -> None:
+ graph = build_fixture(tmp_path).graph()
+ flags = {
+ node: data["public_api"]
+ for node, data in graph.nodes(data=True)
+ if data.get("node_type") == "symbol" and "public_api" in data
+ }
+ assert {node: root for node, root in flags.items() if root} == EXPORTED
+ # ``__all__`` leaves ``internal`` out; a private method, a console script's
+ # module, a test barrel, a library barrel only its own package reads and
+ # an application's subpackage barrel export nothing.
+ for node in (
+ "lib/lib/core.py::internal",
+ "lib/lib/core.py::unlisted",
+ "lib/lib/core.py::Client::_retry",
+ "lib/lib/hidden/impl.py::helper",
+ "app/app/main.py::run",
+ "app/app/schemas/models.py::Model",
+ "tests/helpers.py::fixture",
+ "web/src/render.ts::hidden",
+ ):
+ assert flags[node] == "", node
+
diff --git a/tests/unit/generation/test_package_public_api.py b/tests/unit/generation/test_package_public_api.py
index ce32dc574..35fa0191d 100644
--- a/tests/unit/generation/test_package_public_api.py
+++ b/tests/unit/generation/test_package_public_api.py
@@ -14,7 +14,7 @@ from types import SimpleNamespace
import networkx as nx
-from repowise.core.generation.context.public_api import (
+from repowise.core.analysis.public_api import (
_Resolver,
api_roots,
compute_public_api,
diff --git a/tests/unit/health/test_plan_annotations.py b/tests/unit/health/test_plan_annotations.py
index 22966bc6a..a970c955e 100644
--- a/tests/unit/health/test_plan_annotations.py
+++ b/tests/unit/health/test_plan_annotations.py
@@ -247,3 +247,42 @@ def test_a_test_reading_the_split_function_source_is_a_risk(tmp_path: Path) -> N
assert annotate(plan(), other, ["tests/test_flow.py::test_a"]).risks == ()
assert annotate(plan(), facts, ["tests/test_plain.py::test_x"]).risks == ()
assert annotate(plan("split_file"), facts, ["tests/test_flow.py::test_a"]).risks == ()
+
+
+def test_changing_an_exported_symbol_warns_about_outside_callers() -> None:
+ exported = {"svc/orders.py": {"svc/orders.py::Orders::handle": "svc/__init__.py"}}
+ facts = AnnotationFacts(exported=exported)
+ notes = annotate(plan(target_symbol="Orders.handle"), facts)
+ assert notes.risks == (
+ PlanRisk(
+ "public_api",
+ "`Orders.handle` is exported from `svc/__init__.py`; changing its signature "
+ "breaks consumers outside the repo.",
+ ),
+ )
+ # Only the exported symbol, never a neighbour in the same file.
+ assert not annotate_any(plan(target_symbol="_helper"), facts)
+ assert not annotate_any(plan(file_path="svc/other.py", target_symbol="handle"), facts)
+
+
+def test_a_moved_exported_method_carries_one_public_api_risk() -> None:
+ exported = {
+ "svc/orders.py": {
+ "svc/orders.py::Order::total": "svc/__init__.py",
+ "svc/orders.py::Order": "svc/__init__.py",
+ "svc/orders.py::Pricing": "svc/__init__.py",
+ }
+ }
+ moved = plan(
+ "move_method",
+ target_symbol="Order.total",
+ plan={"from_class": "Order", "to_class": "Pricing"},
+ blast_radius={"callers": 2},
+ )
+ notes = annotate(moved, AnnotationFacts(exported=exported))
+ assert kinds(notes) == ["public_api"]
+ text = notes.risks[0].text
+ # Callers inside the repo first, then every exported symbol the plan changes.
+ assert text.startswith("`Order.total` has 2 callers")
+ assert "`Order` (from `svc/__init__.py`)" in text and "`Pricing`" in text
+ assert text.endswith("are exported; changing their signatures breaks consumers outside the repo.")
diff --git a/tests/unit/persistence/test_public_api_round_trip.py b/tests/unit/persistence/test_public_api_round_trip.py
new file mode 100644
index 000000000..8b50e7ae1
--- /dev/null
+++ b/tests/unit/persistence/test_public_api_round_trip.py
@@ -0,0 +1,25 @@
+"""The public API flag survives graph_nodes, and the plan reader sees only real exports."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.health.refactoring.annotations import _exported_symbols
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.persistence.crud import get_all_graph_nodes
+from repowise.core.pipeline.persist import persist_graph_nodes
+from tests.unit.analysis.test_public_api_flag import EXPORTED, build_fixture
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def test_the_flag_round_trips_through_graph_nodes(tmp_path: Path, async_session) -> None:
+ builder = build_fixture(tmp_path)
+ repo = await insert_repo(async_session)
+ await persist_graph_nodes(async_session, repo.id, builder, ep_scores={})
+ files = sorted({path.split("::", 1)[0] for path in EXPORTED} | {"lib/lib/hidden/impl.py"})
+ exported = await _exported_symbols(async_session, repo.id, files)
+ # "" (checked, not exported) and NULL (file nodes) are left out.
+ assert {sid: root for rows in exported.values() for sid, root in rows.items()} == EXPORTED
+ rehydrated = GraphBuilder.from_persisted(await get_all_graph_nodes(async_session, repo.id), [])
+ assert rehydrated.graph().nodes["lib/lib/core.py::Client"]["public_api"] == "lib/lib/__init__.py"
+ assert rehydrated.graph().nodes["lib/lib/core.py::internal"]["public_api"] == ""
diff --git a/tests/unit/pipeline/test_graph_nodes_before_health.py b/tests/unit/pipeline/test_graph_nodes_before_health.py
new file mode 100644
index 000000000..3700959ca
--- /dev/null
+++ b/tests/unit/pipeline/test_graph_nodes_before_health.py
@@ -0,0 +1,29 @@
+"""Every update path writes graph nodes before health.
+
+Plan annotations, stored when health is persisted, read each symbol's
+``public_api`` from ``graph_nodes``; written after, they would read the
+previous run's flags (none at all on the first update after an upgrade).
+"""
+
+from __future__ import annotations
+
+import inspect
+
+import pytest
+
+from repowise.cli.commands.update_cmd import persistence as cli_update
+from repowise.core.pipeline import incremental
+
+
+ ("function", "health_call"),
+ [
+ (incremental.persist_incremental_index, "await persist_partial_health("),
+ (cli_update._persist_full_update_async, "await _persist_partial_health("),
+ (cli_update._rescore_health_from_db, "await save_full_health_report("),
+ ],
+)
+def test_graph_nodes_persist_before_health(function, health_call: str) -> None:
+ source = inspect.getsource(function)
+ assert "await persist_graph_nodes(" in source and health_call in source
+ assert source.index("await persist_graph_nodes(") < source.index(health_call)
diff --git a/tests/unit/test_no_barrel_filename_copies.py b/tests/unit/test_no_barrel_filename_copies.py
index 748fe2c14..e6c52c000 100644
--- a/tests/unit/test_no_barrel_filename_copies.py
+++ b/tests/unit/test_no_barrel_filename_copies.py
@@ -16,7 +16,7 @@ _KNOWN: frozenset[str] = frozenset(
)
_PACKAGES = pathlib.Path(__file__).resolve().parents[2] / "packages"
-_HOME = "packages/core/src/repowise/core/analysis/dead_code/file_reachability.py"
+_HOME = "packages/core/src/repowise/core/ingestion/barrels.py"
_BARREL_MARKERS = {
"index.ts",
"index.tsx",
@@ -88,7 +88,7 @@ def _offenders() -> dict[str, list[str]]:
def test_no_new_barrel_filename_copies() -> None:
offenders = {p: hits for p, hits in _offenders().items() if p not in _KNOWN}
assert not offenders, (
- "New inline barrel-filename definition(s) outside file_reachability.py:\n"
+ "New inline barrel-filename definition(s) outside ingestion/barrels.py:\n"
+ "\n".join(f" {p}: {', '.join(hits)}" for p, hits in sorted(offenders.items()))
)