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(workspace): make a library's public API a cross-repo contract (#1846)

Raghav Chamadiya916f73713536
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
index 30ebf7aa6..94f746e16 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
@@ -56,6 +56,11 @@ class MSBuildProject:
project_references: list[Path] = field(default_factory=list) # absolute paths to referenced .csproj
package_references: set[str] = field(default_factory=set) # NuGet package ids
project_usings: set[str] = field(default_factory=set) # <Using Include="X"/> namespaces
+ package_id: str | None = None # <PackageId>, the id this project publishes under
+ #: Tri-state on purpose: None = the project says nothing, which is not the
+ #: same as an explicit <IsPackable>false</IsPackable>.
+ is_packable: bool | None = None
+ generate_package_on_build: bool = False
@property
def name(self) -> str:
@@ -74,6 +79,19 @@ def _bool(value: str | None) -> bool:
return (value or "").strip().lower() in ("true", "enable", "1")
+def _tristate(value: str | None) -> bool | None:
+ """None for anything that is not a literal boolean.
+
+ ``<IsPackable>$(PublishLibraries)</IsPackable>`` is the normal way to
+ centralise the flag; reading an unevaluated property as ``false`` would
+ record an unknown as an explicit no.
+ """
+ text = (value or "").strip().lower()
+ if text in ("true", "enable", "1"):
+ return True
+ return False if text in ("false", "disable", "0") else None
+
+
def parse_csproj(csproj_path: Path) -> MSBuildProject | None:
"""Parse a single .csproj file. Returns None on parse failure."""
try:
@@ -94,6 +112,15 @@ def parse_csproj(csproj_path: Path) -> MSBuildProject | None:
project.assembly_name = elem.text.strip()
elif tag == "ImplicitUsings" and elem.text:
project.implicit_usings = _bool(elem.text)
+ elif tag == "PackageId" and elem.text:
+ project.package_id = elem.text.strip()
+ elif tag == "IsPackable" and elem.text:
+ # Last literal wins; a conditional PropertyGroup is not evaluated.
+ packable = _tristate(elem.text)
+ if packable is not None:
+ project.is_packable = packable
+ elif tag == "GeneratePackageOnBuild" and elem.text:
+ project.generate_package_on_build = _bool(elem.text)
elif tag == "ProjectReference":
include = elem.get("Include")
if include:
diff --git a/packages/core/src/repowise/core/workspace/code_api.py b/packages/core/src/repowise/core/workspace/code_api.py
new file mode 100644
index 000000000..a3b6ad2c4
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/code_api.py
@@ -0,0 +1,625 @@
+"""Code-API contracts — a library's public surface as a cross-repo contract.
+
+The four transports already extracted all cross a wire. A package boundary does
+not, which is the gap the reported .NET case falls through: a repo that ships a
+library *provides* its public symbols, and a repo that imports the package
+*consumes* them. Delete one, or add a required parameter to it, and every
+importing repo breaks.
+
+Both halves read the index rather than the text. A provider knows its symbol at
+emission, so it carries a ``symbol_id`` and
+:func:`..signature_schema.attach_signature_schemas` turns the parameter list
+into its schema — which is what makes the field rules fire on a method. A
+consumer comes from the ``imports`` edges to an ``external:`` target, which
+already name the symbols they bring in.
+
+**Published, not merely public.** The surface is what the *manifest* exposes,
+never every public symbol under the package: the two differ by an order of
+magnitude, and the larger number is also wrong, since a symbol no entry point
+re-exports cannot be imported by package name. Where an ecosystem has no entry
+file the whole project directory is the surface, allowed only when the manifest
+carries an explicit publish opt-in to bound it — .NET has one, Go and Maven do
+not.
+
+**Package identity is the manifest's declared name, and only that.** It is the
+one of this repo's several package notions that can be joined to an
+``external:<pkg>`` node id, since that id is whatever the importing source
+wrote. Nothing here reads or changes the others.
+
+Reuse, not extension: ``_removed_endpoint`` already covers a deleted public
+symbol and the three field rules cover its parameters, so this module writes no
+breaking-change rule.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from pathlib import Path
+
+ from repowise.core.workspace.repo_index import IndexedSymbol, RepoIndex, WorkspaceIndex
+
+_log = logging.getLogger("repowise.workspace.code_api")
+
+#: ``Contract.contract_type`` for everything this module produces.
+CODE_CONTRACT_TYPE = "code"
+
+#: Both sides are index-resolved, not regex-matched — the manifest and the
+#: import edge each name their half outright.
+_CONFIDENCE = 0.9
+
+#: Manifest basenames handled here, mapped to the ecosystem they declare.
+_MANIFESTS: dict[str, str] = {
+ "package.json": "npm",
+ "pyproject.toml": "pypi",
+ "Cargo.toml": "cargo",
+}
+
+#: Not implemented, but counted, so the coverage figure names what it misses.
+_UNSUPPORTED_MANIFESTS: dict[str, str] = {"go.mod": "go", "pom.xml": "maven"}
+
+#: Ecosystem tokens a resolver prefixes onto an external node id — a C#
+#: `using` that matches a PackageReference resolves to `external:nuget:<ns>`.
+_EXTERNAL_PREFIXES = ("nuget:", "pub:", "gem:")
+
+#: The bound ``external_systems._discover`` uses, so both see one manifest set.
+_MANIFEST_DEPTH = 3
+
+#: The language an entry-file-less ecosystem's surface is written in.
+_ECOSYSTEM_LANGUAGE = {"nuget": "csharp"}
+
+#: Kinds a consumer can import by name.
+_EXPORTABLE_KINDS = frozenset({"function", "method", "class", "interface", "struct", "enum"})
+
+
+@dataclass(frozen=True)
+class PublishedPackage:
+ """One package a repo ships, as its own manifest declares it."""
+
+ name: str # the manifest's declared name — what an importer writes
+ ecosystem: str
+ repo: str # workspace alias
+ manifest: str # repo-relative POSIX path
+ root: str # repo-relative POSIX dir, "" at the repo root
+ #: ``None`` where the ecosystem has no entry file and *root* is the surface.
+ entry_files: frozenset[str] | None = None
+ #: ``__all__`` names defined elsewhere in the package.
+ reexported: frozenset[str] = frozenset()
+ #: What an importing source actually writes. Not the same as ``name``:
+ #: a PyPI distribution ships a differently-named module, and Cargo
+ #: rewrites `-` to `_`.
+ import_names: frozenset[str] = frozenset()
+
+
+# ---------------------------------------------------------------------------
+# Manifest reading — one small function per ecosystem
+# ---------------------------------------------------------------------------
+
+
+def _rel(path: Path, repo_path: Path) -> str | None:
+ try:
+ return path.relative_to(repo_path).as_posix()
+ except ValueError:
+ return None
+
+
+def _npm(data: dict[str, Any], root: str) -> tuple[str, frozenset[str]] | None:
+ """``name`` plus every file ``exports`` / ``main`` / ``module`` / ``types`` names.
+
+ ``private`` is deliberately not read. It blocks the public registry, not
+ workspace consumption — this workspace's own ``@repowise-dev/types`` is
+ ``private: true`` and imported across repos — and an app with no entry point
+ is already excluded by having no surface.
+ """
+ name = data.get("name")
+ if not isinstance(name, str) or not name:
+ return None
+ targets: set[str] = set()
+
+ def add(value: Any) -> None:
+ if isinstance(value, str):
+ # `exports` values are spelt `./x`; `main`/`module`/`types` are
+ # routinely bare. A URL or an `#imports` alias names no file.
+ if value.startswith(("/", "#")) or "://" in value:
+ return
+ rel = value[2:] if value.startswith("./") else value
+ if rel:
+ targets.add(f"{root}/{rel}" if root else rel)
+ elif isinstance(value, dict): # conditional exports: {"import": "./x.js"}
+ for nested in value.values():
+ add(nested)
+ elif isinstance(value, list): # fallback arrays: [{"import": "./a"}, "./b"]
+ for nested in value:
+ add(nested)
+
+ add(data.get("exports"))
+ for key in ("main", "module", "types"):
+ add(data.get(key))
+ return (name, frozenset(targets)) if targets else None
+
+
+def _pypi(text: str, root: str) -> tuple[str, frozenset[str], frozenset[str]] | None:
+ """``[project].name`` (or Poetry's), and the distribution's top-level package."""
+ import tomllib
+
+ try:
+ data = tomllib.loads(text)
+ except (tomllib.TOMLDecodeError, ValueError):
+ return None
+ project = data.get("project")
+ name = project.get("name") if isinstance(project, dict) else None
+ if not isinstance(name, str):
+ name = _table(data, "tool", "poetry").get("name")
+ if not isinstance(name, str) or not name:
+ return None
+ prefix = f"{root}/" if root else ""
+ dirs = _pypi_package_dirs(data)
+ if not dirs:
+ # PEP 503 allows `-`/`.` in a distribution name where the module needs
+ # an identifier, and the two often differ beyond that. A guess, used
+ # only when the build backend declares nothing.
+ module = name.replace("-", "_").replace(".", "_")
+ dirs = [f"src/{module}", module]
+ return name, frozenset(f"{prefix}{d}/__init__.py" for d in dirs), frozenset()
+
+
+def _table(data: Any, *keys: str) -> dict[str, Any]:
+ """Walk a chain of TOML tables, yielding {} the moment one is not a table."""
+ for key in keys:
+ if not isinstance(data, dict):
+ return {}
+ data = data.get(key, {})
+ return data if isinstance(data, dict) else {}
+
+
+def _pypi_package_dirs(data: dict[str, Any]) -> list[str]:
+ """Package directories the build backend declares, newest layouts first.
+
+ Every read is shape-checked: a hand-edited ``pyproject.toml`` must not be
+ able to crash extraction for the whole workspace, and setuptools' auto-
+ discovery spelling (``packages = {find = {...}}``) is a table, not a list.
+ """
+
+ def strings(value: Any) -> list[str]:
+ return [v for v in value if isinstance(v, str)] if isinstance(value, list) else []
+
+ dirs: list[str] = strings(_table(data, "tool", "hatch", "build", "targets", "wheel").get("packages"))
+ dirs += [
+ p.replace(".", "/") for p in strings(_table(data, "tool", "setuptools").get("packages"))
+ ]
+ for entry in _table(data, "tool", "poetry").get("packages") or []:
+ include = entry.get("include") if isinstance(entry, dict) else None
+ if isinstance(include, str):
+ source = entry.get("from")
+ dirs.append(f"{source}/{include}" if isinstance(source, str) else include)
+ return [d.strip("/") for d in dirs if isinstance(d, str) and d.strip("/")]
+
+
+def _dunder_all(repo_path: Path, entry_files: frozenset[str]) -> frozenset[str]:
+ """Names an entry ``__init__.py`` re-exports via ``__all__``.
+
+ Python's entry file usually *declares* nothing — it is a wall of
+ ``from .x import Y`` — so without this a distribution's surface reads as
+ empty. Only plain string literals count; a computed ``__all__`` is refused
+ whole rather than half-read, per the same rule the signature mapper follows.
+ """
+ import ast
+
+ names: set[str] = set()
+ for rel in entry_files:
+ path = repo_path / rel
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
+ except (OSError, SyntaxError, ValueError):
+ continue
+ for node in tree.body:
+ if not isinstance(node, ast.Assign) or not any(
+ isinstance(t, ast.Name) and t.id == "__all__" for t in node.targets
+ ):
+ continue
+ if not isinstance(node.value, ast.List | ast.Tuple):
+ continue
+ names.update(
+ el.value
+ for el in node.value.elts
+ if isinstance(el, ast.Constant) and isinstance(el.value, str)
+ )
+ return frozenset(names)
+
+
+def _cargo(text: str, root: str) -> tuple[str, frozenset[str]] | None:
+ """``[package].name`` and the crate root, which is the whole public surface."""
+ import tomllib
+
+ try:
+ data = tomllib.loads(text)
+ except (tomllib.TOMLDecodeError, ValueError):
+ return None
+ package = data.get("package")
+ name = package.get("name") if isinstance(package, dict) else None
+ if not isinstance(name, str) or not name:
+ return None
+ lib = data.get("lib")
+ path = lib.get("path") if isinstance(lib, dict) else None
+ entry = path if isinstance(path, str) else "src/lib.rs"
+ return name, frozenset({f"{root}/{entry}" if root else entry})
+
+
+def _nuget(project: Any, repo_path: Path, root: str) -> str | None:
+ """The id a packable project publishes under, or None when it is not packable.
+
+ Packability is opt-in, never assumed: an SDK-style project is packable by
+ default, so treating silence as yes would make every internal project in a
+ solution a published library.
+ """
+ if project.is_packable is False:
+ return None
+ if not (
+ project.is_packable
+ or project.generate_package_on_build
+ or project.package_id is not None
+ ):
+ return None
+ return project.package_id or project.assembly_name or project.path.stem
+
+
+# ---------------------------------------------------------------------------
+# Discovery
+# ---------------------------------------------------------------------------
+
+
+def find_published_packages(
+ alias: str, repo_path: Path
+) -> tuple[list[PublishedPackage], dict[str, int]]:
+ """Every package *repo_path* declares it publishes, plus skip counters."""
+ from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
+ from repowise.core.ingestion.resolvers.dotnet.msbuild import find_csproj_files, parse_csproj
+
+ packages: list[PublishedPackage] = []
+ counts: dict[str, int] = {}
+ prune = PRUNED_DIRS | {"target", "dist", "build"}
+
+ for dirpath, dirnames, filenames in walk_repo(repo_path, prune_dirs=prune):
+ if len(dirpath.relative_to(repo_path).parts) >= _MANIFEST_DEPTH:
+ dirnames[:] = []
+ rel_dir = _rel(dirpath, repo_path)
+ if rel_dir is None:
+ continue
+ root = "" if rel_dir == "." else rel_dir
+ for fname in filenames:
+ if fname in _UNSUPPORTED_MANIFESTS:
+ counts["code_unsupported_ecosystem"] = (
+ counts.get("code_unsupported_ecosystem", 0) + 1
+ )
+ continue
+ ecosystem = _MANIFESTS.get(fname)
+ if ecosystem is None:
+ continue
+ manifest = dirpath / fname
+ rel_manifest = _rel(manifest, repo_path)
+ if rel_manifest is None:
+ continue
+ try:
+ text = manifest.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+ parsed = _read_manifest(ecosystem, text, root)
+ if parsed is None:
+ counts["code_unpublished_manifest"] = (
+ counts.get("code_unpublished_manifest", 0) + 1
+ )
+ continue
+ name, entries, reexported = parsed
+ if ecosystem == "pypi":
+ reexported = _dunder_all(repo_path, entries)
+ packages.append(
+ PublishedPackage(
+ name=name,
+ ecosystem=ecosystem,
+ repo=alias,
+ manifest=rel_manifest,
+ root=root,
+ entry_files=entries,
+ reexported=reexported,
+ import_names=_import_names(ecosystem, name, entries),
+ )
+ )
+
+ for csproj in find_csproj_files(repo_path):
+ project = parse_csproj(csproj)
+ rel_manifest = _rel(csproj, repo_path) if project is not None else None
+ if project is None or rel_manifest is None:
+ continue
+ root = rel_manifest.rsplit("/", 1)[0] if "/" in rel_manifest else ""
+ package_id = _nuget(project, repo_path, root)
+ if package_id is None:
+ counts["code_unpublished_manifest"] = counts.get("code_unpublished_manifest", 0) + 1
+ continue
+ packages.append(
+ PublishedPackage(
+ name=package_id,
+ ecosystem="nuget",
+ repo=alias,
+ manifest=rel_manifest,
+ root=root,
+ entry_files=None, # no entry file; the assembly's public types are the surface
+ import_names=frozenset({package_id}),
+ )
+ )
+ return packages, counts
+
+
+def _read_manifest(
+ ecosystem: str, text: str, root: str
+) -> tuple[str, frozenset[str], frozenset[str]] | None:
+ if ecosystem == "npm":
+ try:
+ data = json.loads(text)
+ except ValueError:
+ return None
+ if not isinstance(data, dict):
+ return None
+ npm = _npm(data, root)
+ return (npm[0], npm[1], frozenset()) if npm else None
+ if ecosystem == "pypi":
+ return _pypi(text, root)
+ cargo = _cargo(text, root)
+ return (cargo[0], cargo[1], frozenset()) if cargo else None
+
+
+# ---------------------------------------------------------------------------
+# Surface resolution
+# ---------------------------------------------------------------------------
+
+
+def _exported_name(symbol: IndexedSymbol) -> str:
+ """The path an importer names this symbol by — ``Owner.member`` for a member.
+
+ A bare ``name`` collides across classes, and a member is reachable through
+ the type that owns it, which is what lets a consumer importing ``OrderService``
+ be linked to a change in ``OrderService.PlaceOrder``.
+ """
+ qualified = symbol.qualified_name or symbol.name
+ # qualified_name is module-scoped ("pkg.mod.Owner.member"); the exported
+ # path is the tail, since a package importer never writes the file's path.
+ tail = qualified.rsplit(".", 2)[-2:] if symbol.kind == "method" else [symbol.name]
+ return ".".join(part for part in tail if part) or symbol.name
+
+
+def _surface_symbols(
+ package: PublishedPackage, index: RepoIndex, exclude: Callable[[str], bool]
+) -> list[IndexedSymbol]:
+ """The public symbols *package* publishes, per its entry-file rule."""
+ prefix = f"{package.root}/" if package.root else ""
+ candidates = [
+ s
+ for s in index.public_symbols()
+ if s.kind in _EXPORTABLE_KINDS
+ and not exclude(s.file_path)
+ and s.file_path.startswith(prefix)
+ ]
+ if package.entry_files is None:
+ # A .csproj at the repo root gives prefix "", so without this every
+ # file in the repo — every language — would be an assembly symbol.
+ return [s for s in candidates if s.language == _ECOSYSTEM_LANGUAGE[package.ecosystem]]
+
+ # An `__all__` entry names a symbol its entry file does not declare, so it
+ # resolves by name across the package — and only when that name is unique.
+ # Two `Widget`s would otherwise bind the contract to whichever the index
+ # happened to return first.
+ by_name: dict[str, list[IndexedSymbol]] = {}
+ for symbol in candidates:
+ by_name.setdefault(symbol.name, []).append(symbol)
+ return [
+ s
+ for s in candidates
+ if s.file_path in package.entry_files
+ or (s.name in package.reexported and len(by_name[s.name]) == 1)
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Contract emission
+# ---------------------------------------------------------------------------
+
+
+def contract_id_for(package_name: str, exported: str) -> str:
+ return f"{CODE_CONTRACT_TYPE}::{package_name}::{exported}"
+
+
+@dataclass
+class CodeSurface:
+ """Every workspace repo's published packages and the contracts they imply."""
+
+ by_repo: dict[str, list[Any]] = field(default_factory=dict) # alias -> list[Contract]
+ stats: dict[str, dict[str, int]] = field(default_factory=dict) # alias -> counters
+ #: package name -> the exported paths its provider contracts cover. What lets
+ #: an import of a type expand to the members that type owns.
+ members: dict[str, set[str]] = field(default_factory=dict)
+
+ def for_repo(self, alias: str) -> list[Any]:
+ return self.by_repo.get(alias, [])
+
+
+def build_code_surface(
+ repo_paths: dict[str, Path],
+ workspace_index: WorkspaceIndex | None,
+ exclude: Callable[[str], bool],
+) -> CodeSurface:
+ """Build every ``code`` contract in the workspace, providers before consumers.
+
+ Workspace-wide by necessity, not by preference: a consumer contract only
+ exists when the package it imports is published by *some* repo, so neither
+ half can be decided inside a single repo's extraction.
+ """
+ from repowise.core.workspace.contracts import Contract
+ from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_INDEX
+
+ surface = CodeSurface()
+ if workspace_index is None:
+ return surface
+
+ published: list[PublishedPackage] = []
+ for alias, repo_path in repo_paths.items():
+ packages, counts = find_published_packages(alias, repo_path)
+ published.extend(packages)
+ if counts:
+ surface.stats.setdefault(alias, {}).update(counts)
+
+ # -- providers ---------------------------------------------------------
+ by_name: dict[str, PublishedPackage] = {}
+ by_import: dict[str, PublishedPackage] = {}
+ for package in published:
+ index = workspace_index.get(package.repo)
+ if index is None:
+ continue
+ # Two repos publishing one name is a workspace misconfiguration, not a
+ # contract; keeping the first makes the artifact deterministic.
+ if package.name in by_name:
+ surface.stats.setdefault(package.repo, {})["code_duplicate_package"] = (
+ surface.stats.setdefault(package.repo, {}).get("code_duplicate_package", 0) + 1
+ )
+ continue
+ by_name[package.name] = package
+ for import_name in package.import_names:
+ by_import.setdefault(import_name, package)
+ rows = surface.by_repo.setdefault(package.repo, [])
+ exported_here = surface.members.setdefault(package.name, set())
+ seen: set[str] = set()
+ for symbol in _surface_symbols(package, index, exclude):
+ exported = _exported_name(symbol)
+ if exported in seen:
+ # Two entry files exporting one name: which row survives
+ # would otherwise be decided by index row order.
+ stats = surface.stats.setdefault(package.repo, {})
+ stats["code_ambiguous_export"] = stats.get("code_ambiguous_export", 0) + 1
+ continue
+ seen.add(exported)
+ exported_here.add(exported)
+ rows.append(
+ Contract(
+ repo=package.repo,
+ contract_id=contract_id_for(package.name, exported),
+ contract_type=CODE_CONTRACT_TYPE,
+ role="provider",
+ file_path=symbol.file_path,
+ symbol_name=exported,
+ confidence=_CONFIDENCE,
+ line=symbol.start_line,
+ # Known at emission, so bind_symbol_ids is a no-op here and
+ # attach_signature_schemas reaches the parameter list.
+ symbol_id=symbol.symbol_id,
+ meta={
+ "package": package.name,
+ "ecosystem": package.ecosystem,
+ EXTRACTION_LAYER_KEY: LAYER_INDEX,
+ },
+ )
+ )
+ stats = surface.stats.setdefault(package.repo, {})
+ stats["code_published_packages"] = stats.get("code_published_packages", 0) + 1
+ stats["code_provider_symbols"] = stats.get("code_provider_symbols", 0) + len(seen)
+
+ # -- consumers ---------------------------------------------------------
+ for alias in repo_paths:
+ index = workspace_index.get(alias)
+ if index is None:
+ continue
+ rows = surface.by_repo.setdefault(alias, [])
+ stats = surface.stats.setdefault(alias, {})
+ seen_pairs: set[tuple[str, str, str]] = set()
+ for edge in index.external_import_edges():
+ package = _package_for(edge.external_name, by_import)
+ if package is None:
+ continue
+ if package.repo == alias or exclude(edge.source_file):
+ continue
+ for name in edge.imported_names:
+ for exported in _consumed_exports(name, surface.members[package.name]):
+ key = (package.name, exported, edge.source_file)
+ if key in seen_pairs:
+ continue
+ seen_pairs.add(key)
+ rows.append(
+ Contract(
+ repo=alias,
+ contract_id=contract_id_for(package.name, exported),
+ contract_type=CODE_CONTRACT_TYPE,
+ role="consumer",
+ file_path=edge.source_file,
+ symbol_name=f"{package.name}:{exported}",
+ confidence=_CONFIDENCE,
+ meta={
+ "package": package.name,
+ "ecosystem": package.ecosystem,
+ EXTRACTION_LAYER_KEY: LAYER_INDEX,
+ },
+ )
+ )
+ stats["code_consumer_imports"] = len(seen_pairs)
+
+ _log.debug(
+ "Code-API surface: %d package(s), %d contract(s)",
+ len(by_name),
+ sum(len(rows) for rows in surface.by_repo.values()),
+ )
+ return surface
+
+
+def _import_names(ecosystem: str, name: str, entry_files: frozenset[str] | None) -> frozenset[str]:
+ """What an importing source writes for this package.
+
+ Only npm's publish id and import specifier are the same string. A PyPI
+ distribution ships a module named by its build backend (``repowise-core``
+ ships ``repowise``), and Cargo rewrites ``-`` to ``_``.
+ """
+ names = {name}
+ if ecosystem == "cargo":
+ names.add(name.replace("-", "_"))
+ elif ecosystem == "pypi" and entry_files:
+ names.update(f.rsplit("/", 2)[-2] for f in entry_files if "/" in f)
+ return frozenset(n for n in names if n)
+
+
+def _package_for(
+ external_name: str, by_import: dict[str, PublishedPackage]
+) -> PublishedPackage | None:
+ """Resolve an ``external:`` target to a published package.
+
+ The target carries whatever the importing source reached: a subpath
+ (``@scope/ui/lib/format``), a child namespace (``nuget:Contoso.Orders.Models``)
+ or a submodule (``mylib.sub``). The longest import name that prefixes it on a
+ separator wins — a bare prefix would match ``@scope/ui`` for an unrelated
+ ``@scope/ui-icons``.
+ """
+ for prefix in _EXTERNAL_PREFIXES:
+ if external_name.startswith(prefix):
+ external_name = external_name[len(prefix) :]
+ break
+ if external_name in by_import:
+ return by_import[external_name]
+ best: tuple[int, PublishedPackage] | None = None
+ for name, package in by_import.items():
+ if external_name.startswith((f"{name}/", f"{name}.")) and (
+ best is None or len(name) > best[0]
+ ):
+ best = (len(name), package)
+ return best[1] if best else None
+
+
+def _consumed_exports(imported: str, exported: set[str]) -> list[str]:
+ """The provider exports an import of *imported* consumes.
+
+ The name itself, plus every member it owns. Importing a type consumes its
+ methods: a required parameter added to one breaks the importer whether or
+ not this call site passes it, which is the same directness the module-level
+ non-goal on call-site argument matching states.
+ """
+ out = [imported] if imported in exported else []
+ out.extend(name for name in exported if name.startswith(f"{imported}."))
+ return out
diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.py
index 8cfd97ea4..943880ebe 100644
--- a/packages/core/src/repowise/core/workspace/config.py
+++ b/packages/core/src/repowise/core/workspace/config.py
@@ -108,6 +108,8 @@ class ContractConfig:
detect_socket: bool = True
detect_topics: bool = True
detect_data: bool = True
+ #: A library's public API as a contract (``contract_type="code"``).
+ detect_code_api: bool = True
manual_links: list[ManualContractLink] = field(default_factory=list)
# Map a consumer base token or absolute host to the repo alias it targets,
# so a ``fetch(`${API_BASE}/users`)`` whose base resolves to ``backend`` links
@@ -125,6 +127,7 @@ class ContractConfig:
"detect_socket": self.detect_socket,
"detect_topics": self.detect_topics,
"detect_data": self.detect_data,
+ "detect_code_api": self.detect_code_api,
}
if self.manual_links:
d["manual_links"] = [ml.to_dict() for ml in self.manual_links]
@@ -143,6 +146,7 @@ class ContractConfig:
detect_socket=bool(data.get("detect_socket", True)),
detect_topics=bool(data.get("detect_topics", True)),
detect_data=bool(data.get("detect_data", True)),
+ detect_code_api=bool(data.get("detect_code_api", True)),
manual_links=manual,
service_bases={str(k): str(v) for k, v in data.get("service_bases", {}).items()},
exclude_globs=[str(g) for g in data.get("exclude_globs", [])],
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index e649176e1..412638fc7 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -45,7 +45,7 @@ CONTRACTS_FILENAME = "contracts.json"
#: to 3 when providers gained a signature-derived ``schema``.
#: A store written under an older version is readable but not reusable: its
#: rows carry no identity, and nothing short of re-extraction can give them one.
-CONTRACTS_VERSION = 3
+CONTRACTS_VERSION = 4
# ---------------------------------------------------------------------------
@@ -59,7 +59,7 @@ class Contract:
repo: str # repo alias
contract_id: str # e.g. "http::GET::/api/users/{param}", "data::orders"
- contract_type: str # "http" | "grpc" | "socket" | "topic" | "data"
+ contract_type: str # "http" | "grpc" | "socket" | "topic" | "data" | "code"
role: str # "provider" | "consumer"
file_path: str # relative to repo root
symbol_name: str # handler name, service.method, etc. — display only
@@ -119,7 +119,7 @@ class ContractLink:
"""A matched provider↔consumer pair across repos."""
contract_id: str
- contract_type: str # "http" | "grpc" | "socket" | "topic" | "data"
+ contract_type: str # "http" | "grpc" | "socket" | "topic" | "data" | "code"
match_type: str # "exact" | "candidate" | "manual"
confidence: float
provider_repo: str
@@ -314,6 +314,11 @@ def normalize_contract_id(contract_id: str) -> str:
if ctype == "topic" and len(parts) == 2:
return f"topic::{parts[1].lower()}"
+ # Package name is case-insensitive, the symbol is not: the lowercase
+ # fallback would conflate `Order` with `order`.
+ if ctype == "code" and len(parts) == 3:
+ return f"code::{parts[1].lower()}::{parts[2]}"
+
return contract_id.lower()
@@ -864,6 +869,7 @@ async def run_contract_extraction(
mislabel both. Matching is dict-indexed and costs milliseconds against
seconds of extraction, so scoping it would buy nothing and risk everything.
"""
+ from .code_api import CodeSurface, build_code_surface
from .extractors import (
DataExtractor,
GrpcExtractor,
@@ -891,6 +897,15 @@ async def run_contract_extraction(
if len(repo_paths) < 2:
return ContractStore()
+ # Built once, workspace-wide: a code consumer only exists when some *other*
+ # repo publishes the package it imports, so neither half of it can be
+ # decided inside one repo's extraction.
+ code_surface = (
+ await asyncio.to_thread(build_code_surface, repo_paths, workspace_index, exclude)
+ if contract_config.detect_code_api
+ else CodeSurface()
+ )
+
# Which repos can be carried forward, and which must be re-extracted.
# Probing a repo's state costs a `git rev-parse` and a dirty check; the
# alternative is trusting changed_repos, which is exactly the trust a stale
@@ -905,8 +920,13 @@ async def run_contract_extraction(
# repo extracted under `detect_data: false`, or before a `service_bases`
# entry existed, holds rows that answer a question no longer being asked —
# and its HEAD is unchanged, so nothing else here would notice.
+ # The published-package set joins it because a code consumer depends on
+ # *another* repo's manifests: adding the repo that publishes what this one
+ # imports moves no HEAD here, so nothing else would notice.
config_fp = hashlib.sha256(
- json.dumps(contract_config.to_dict(), sort_keys=True).encode()
+ json.dumps(
+ [contract_config.to_dict(), sorted(code_surface.members)], sort_keys=True
+ ).encode()
).hexdigest()[:16]
# A store written before contracts carried identity holds rows that cannot
@@ -975,8 +995,9 @@ async def run_contract_extraction(
extractors.append(TopicExtractor())
if contract_config.detect_data:
extractors.append(DataExtractor())
- if not extractors:
- return contracts, {}
+ code_rows = code_surface.for_repo(alias)
+ if not extractors and not code_rows:
+ return contracts, dict(code_surface.stats.get(alias, {}))
# One walk per repo, shared by every extractor. Each used to walk and
# re-read the tree itself, so a file claimed by N extractors was read N
@@ -1020,6 +1041,13 @@ async def run_contract_extraction(
c.meta.setdefault(EXTRACTION_LAYER_KEY, LAYER_REGEX)
contracts.extend(found)
+ # Before binding, so a code provider's pre-set symbol id flows into
+ # attach_signature_schemas and its parameter list becomes the schema.
+ for c in code_rows:
+ c.service = assign_service(c.file_path, boundaries)
+ contracts.extend(code_rows)
+ stats.update(code_surface.stats.get(alias, {}))
+
stats.update(bind_symbol_ids(contracts, repo_index))
stats.update(attach_signature_schemas(contracts, repo_index))
diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.py
index d6a77e31f..f0f598c6c 100644
--- a/packages/core/src/repowise/core/workspace/diagnostics.py
+++ b/packages/core/src/repowise/core/workspace/diagnostics.py
@@ -21,6 +21,7 @@ from collections import defaultdict
from dataclasses import asdict, dataclass, field
from typing import Any
+from repowise.core.workspace.code_api import CODE_CONTRACT_TYPE
from repowise.core.workspace.contracts import (
Contract,
ContractLink,
@@ -179,6 +180,39 @@ class SchemaCoverage:
}
+@dataclass
+class CodeApiCoverage:
+ """How much of the workspace's package surface became a ``code`` contract.
+
+ Two denominators, as :class:`SchemaCoverage` carries two. *manifests* counts
+ every manifest seen, so *published* against it says how much of the
+ workspace declares a package at all; *linked_ratio* is over the providers
+ actually emitted and says whether the consumer join is working.
+ """
+
+ manifests: int = 0
+ published: int = 0
+ unsupported_ecosystem: int = 0
+ providers: int = 0
+ consumers: int = 0
+ linked_providers: int = 0
+
+ def _ratio(self, numerator: int, denominator: int) -> float | None:
+ return numerator / denominator if denominator > 0 else None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "manifests": self.manifests,
+ "published": self.published,
+ "unsupported_ecosystem": self.unsupported_ecosystem,
+ "providers": self.providers,
+ "consumers": self.consumers,
+ "linked_providers": self.linked_providers,
+ "published_ratio": self._ratio(self.published, self.manifests),
+ "linked_ratio": self._ratio(self.linked_providers, self.providers),
+ }
+
+
@dataclass
class ExtractionDiagnostics:
"""Aggregate explanation of contract extraction + matching coverage."""
@@ -203,6 +237,8 @@ class ExtractionDiagnostics:
#: Request-schema recovery over providers. Reported, never asserted: a
#: provider without a schema keeps matching, it just cannot be field-diffed.
schema_coverage: SchemaCoverage = field(default_factory=SchemaCoverage)
+ #: Published-package surface coverage. Reported, never asserted.
+ code_api: CodeApiCoverage = field(default_factory=CodeApiCoverage)
@property
def http_consumer_coverage(self) -> float | None:
@@ -236,11 +272,13 @@ class ExtractionDiagnostics:
"http_consumer_coverage": self.http_consumer_coverage,
"symbol_identity": {r: v.to_dict() for r, v in sorted(self.symbol_identity.items())},
"schema_coverage": self.schema_coverage.to_dict(),
+ "code_api": self.code_api.to_dict(),
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ExtractionDiagnostics:
schema = data.get("schema_coverage") or {}
+ code = data.get("code_api") or {}
return cls(
total_providers=data.get("total_providers", 0),
total_consumers=data.get("total_consumers", 0),
@@ -298,6 +336,14 @@ class ExtractionDiagnostics:
unsupported_language=schema.get("unsupported_language", 0),
non_callable=schema.get("non_callable", 0),
),
+ code_api=CodeApiCoverage(
+ manifests=code.get("manifests", 0),
+ published=code.get("published", 0),
+ unsupported_ecosystem=code.get("unsupported_ecosystem", 0),
+ providers=code.get("providers", 0),
+ consumers=code.get("consumers", 0),
+ linked_providers=code.get("linked_providers", 0),
+ ),
)
@@ -461,6 +507,24 @@ def build_diagnostics(
),
)
+ code_providers = [c for c in providers if c.contract_type == CODE_CONTRACT_TYPE]
+ published = sum(s.get("code_published_packages", 0) for s in stats_by_repo.values())
+ unsupported = sum(s.get("code_unsupported_ecosystem", 0) for s in stats_by_repo.values())
+ code_api = CodeApiCoverage(
+ manifests=published
+ + unsupported
+ + sum(s.get("code_unpublished_manifest", 0) for s in stats_by_repo.values()),
+ published=published,
+ unsupported_ecosystem=unsupported,
+ providers=len(code_providers),
+ consumers=sum(1 for c in consumers if c.contract_type == CODE_CONTRACT_TYPE),
+ linked_providers=sum(
+ 1
+ for p in code_providers
+ if _contract_key(p.repo, p.file_path, p.contract_id) in matched_providers
+ ),
+ )
+
return ExtractionDiagnostics(
total_providers=len(providers),
total_consumers=len(consumers),
@@ -480,4 +544,5 @@ def build_diagnostics(
),
symbol_identity=identity,
schema_coverage=schema,
+ code_api=code_api,
)
diff --git a/packages/core/src/repowise/core/workspace/system_graph.py b/packages/core/src/repowise/core/workspace/system_graph.py
index a8971ec41..0b883a5c5 100644
--- a/packages/core/src/repowise/core/workspace/system_graph.py
+++ b/packages/core/src/repowise/core/workspace/system_graph.py
@@ -68,6 +68,9 @@ _CONTRACT_TYPE_TO_EDGE_KIND: dict[str, str] = {
"socket": "socket",
"topic": "event",
"data": "db",
+ # A package boundary is exactly what the existing "package" kind means,
+ # so the graph, the conformance rules and the map need no new taxonomy.
+ "code": "package",
}
#: All edge kinds the graph can carry. ``db`` carries the shared-table
@@ -332,7 +335,10 @@ class _GraphBuilder:
for e in edges:
endpoints.add(e.source)
endpoints.add(e.target)
- if e.structural and e.kind != "package":
+ # A `package` edge is a manifest dependency, which says nothing
+ # about whether a contract was consumed — unless a `code` contract
+ # link built it, which `contract_refs` is what distinguishes.
+ if e.structural and (e.kind != "package" or e.contract_refs):
contract_targets.add(e.target)
contract_sources.add(e.source)
diff --git a/tests/unit/workspace/test_code_api.py b/tests/unit/workspace/test_code_api.py
new file mode 100644
index 000000000..91e9dde6e
--- /dev/null
+++ b/tests/unit/workspace/test_code_api.py
@@ -0,0 +1,477 @@
+"""Code-API contracts — a library's published surface as a cross-repo contract.
+
+The four transports that existed all cross a wire, so a repo that breaks its
+consumers by deleting a public method or adding a required parameter to one
+produced nothing. That is the reported .NET case, and the headline test drives
+it end to end through the real parser and the real ``.csproj`` reader.
+
+Two further claims are under test. The surface is what the *manifest* publishes,
+not every public symbol under the package — an entry-file rule that also decides
+which manifests count as publishing anything at all. And the whole thing is
+additive: no breaking-change rule is added, so ``_removed_endpoint`` and the
+three field rules do the work unchanged.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion import ASTParser, FileTraverser
+from repowise.core.workspace.breaking_change import detect_breaking_changes
+from repowise.core.workspace.code_api import (
+ CODE_CONTRACT_TYPE,
+ build_code_surface,
+ find_published_packages,
+)
+from repowise.core.workspace.config import ContractConfig, RepoEntry, WorkspaceConfig
+from repowise.core.workspace.contracts import ContractStore, run_contract_extraction
+from repowise.core.workspace.extractors.base import make_exclude_predicate
+from repowise.core.workspace.repo_index import WorkspaceIndex
+
+from ._repo_index import make_repo_index
+
+# ---------------------------------------------------------------------------
+# The .NET fixture — the reported case
+# ---------------------------------------------------------------------------
+
+CSPROJ = """<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net8.0</TargetFramework>
+ <IsPackable>true</IsPackable>
+ <PackageId>Contoso.Orders</PackageId>
+ </PropertyGroup>
+</Project>
+"""
+
+LIB_BEFORE = """namespace Contoso.Orders;
+
+public class OrderService
+{
+ public void PlaceOrder(string sku)
+ {
+ }
+}
+"""
+LIB_AFTER = LIB_BEFORE.replace("PlaceOrder(string sku)", "PlaceOrder(string sku, string tenant)")
+LIB_REMOVED = LIB_BEFORE.replace("public void PlaceOrder(string sku)\n {\n }\n", "")
+
+
+def _parse(repo: Path) -> dict[str, list]:
+ """Real ingestion output for *repo*, so the test reads real signatures."""
+ parser = ASTParser()
+ out: dict[str, list] = {}
+ for file_info in FileTraverser(repo).traverse():
+ parsed = parser.parse_file(file_info, (repo / file_info.path).read_bytes())
+ if parsed.symbols:
+ out[file_info.path] = list(parsed.symbols)
+ return out
+
+
+async def _extract(root: Path, lib_source: str, monkeypatch) -> ContractStore:
+ """A two-repo .NET workspace: `lib` publishes the package, `app` imports it."""
+ from repowise.core.workspace import contracts as contracts_mod
+
+ monkeypatch.setattr(contracts_mod, "save_contract_store", lambda store, path: path)
+
+ lib = root / "lib"
+ (lib / ".repowise").mkdir(parents=True, exist_ok=True)
+ (lib / "Contoso.Orders.csproj").write_text(CSPROJ, encoding="utf-8")
+ (lib / "OrderService.cs").write_text(lib_source, encoding="utf-8")
+
+ app = root / "app"
+ (app / ".repowise").mkdir(parents=True, exist_ok=True)
+
+ lib_index = await make_repo_index(lib, _parse(lib), alias="lib")
+ # The `nuget:` prefix and the child namespace are what `resolve_csharp_import`
+ # actually writes for a `using` that matches a PackageReference — not the
+ # bare package id, which is why the join strips and walks dotted prefixes.
+ app_index = await make_repo_index(
+ app,
+ {},
+ alias="app",
+ external_edges=[
+ ("Program.cs", "external:nuget:Contoso.Orders.Models", ["OrderService"])
+ ],
+ )
+ config = WorkspaceConfig(
+ repos=[RepoEntry(path="lib", alias="lib"), RepoEntry(path="app", alias="app")],
+ contracts=ContractConfig(),
+ )
+ try:
+ return await run_contract_extraction(
+ config,
+ root,
+ [],
+ workspace_index=WorkspaceIndex({"lib": lib_index, "app": app_index}),
+ )
+ finally:
+ await lib_index.close()
+ await app_index.close()
+
+
+class TestTheReportedCase:
+ """A required parameter added to a published method, on a two-repo fixture."""
+
+ async def test_adding_a_required_parameter_names_the_impacted_consumer(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ):
+ previous = await _extract(tmp_path / "a", LIB_BEFORE, monkeypatch)
+ current = await _extract(tmp_path / "b", LIB_AFTER, monkeypatch)
+
+ method = "code::Contoso.Orders::OrderService.PlaceOrder"
+ provider = next(c for c in previous.contracts if c.contract_id == method)
+ assert provider.role == "provider" and provider.repo == "lib"
+ # The schema is W4's mapper reading the parsed signature — not written here.
+ assert provider.schema is not None
+ assert [f.name for f in provider.schema.request_fields] == ["sku"]
+ assert previous.contract_links, "the consumer must match for impact to resolve"
+
+ report = detect_breaking_changes(previous, current)
+ tightened = [c for c in report.changes if c.kind == "field_required"]
+ assert [c.field_name for c in tightened] == ["tenant"], report.to_dict()
+ change = tightened[0]
+ assert change.severity == "breaking"
+ assert change.contract_type == CODE_CONTRACT_TYPE
+ assert change.provider_symbol_id
+ assert [i.repo for i in change.impacted_consumers] == ["app"]
+
+ async def test_deleting_a_published_method_reuses_the_removed_endpoint_rule(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ):
+ previous = await _extract(tmp_path / "a", LIB_BEFORE, monkeypatch)
+ current = await _extract(tmp_path / "b", LIB_REMOVED, monkeypatch)
+
+ report = detect_breaking_changes(previous, current)
+ removed = [c for c in report.changes if c.kind == "removed_endpoint"]
+ assert [c.contract_id for c in removed] == [
+ "code::Contoso.Orders::OrderService.PlaceOrder"
+ ], report.to_dict()
+ assert [i.repo for i in removed[0].impacted_consumers] == ["app"]
+
+ async def test_an_unchanged_library_reports_nothing(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ):
+ previous = await _extract(tmp_path / "a", LIB_BEFORE, monkeypatch)
+ current = await _extract(tmp_path / "b", LIB_BEFORE, monkeypatch)
+ assert detect_breaking_changes(previous, current).changes == []
+
+ async def test_importing_a_type_consumes_the_members_it_owns(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ):
+ """The v1 non-goal, stated positively: no call-site argument matching.
+
+ ``app`` imports ``OrderService``, never ``PlaceOrder``, and is still
+ impacted by a change to it — a package importer takes the whole type.
+ """
+ store = await _extract(tmp_path / "a", LIB_BEFORE, monkeypatch)
+ consumed = sorted(
+ c.contract_id for c in store.contracts if c.role == "consumer"
+ )
+ assert consumed == [
+ "code::Contoso.Orders::OrderService",
+ "code::Contoso.Orders::OrderService.PlaceOrder",
+ ]
+
+
+class TestPublishability:
+ """Which manifests declare a package, and which only look like they do."""
+
+ def _packages(self, repo: Path):
+ packages, counts = find_published_packages("r", repo)
+ return {p.name: p for p in packages}, counts
+
+ def test_a_csproj_must_opt_in_to_being_packable(self, tmp_path: Path):
+ # SDK-style projects are packable by default, so silence cannot mean
+ # yes: every internal project in a solution would become a library.
+ (tmp_path / "Silent.csproj").write_text(
+ '<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup>'
+ "<TargetFramework>net8.0</TargetFramework></PropertyGroup></Project>",
+ encoding="utf-8",
+ )
+ packages, counts = self._packages(tmp_path)
+ assert packages == {}
+ assert counts["code_unpublished_manifest"] == 1
+
+ @pytest.mark.parametrize(
+ "properties",
+ [
+ "<IsPackable>true</IsPackable>",
+ "<GeneratePackageOnBuild>true</GeneratePackageOnBuild>",
+ "<PackageId>Contoso.Orders</PackageId>",
+ ],
+ )
+ def test_any_explicit_publish_signal_counts(self, tmp_path: Path, properties: str):
+ (tmp_path / "Contoso.Orders.csproj").write_text(
+ f'<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup>{properties}'
+ "</PropertyGroup></Project>",
+ encoding="utf-8",
+ )
+ packages, _ = self._packages(tmp_path)
+ assert set(packages) == {"Contoso.Orders"}
+ assert packages["Contoso.Orders"].entry_files is None # whole project
+
+ def test_is_packable_false_overrides_a_package_id(self, tmp_path: Path):
+ (tmp_path / "Internal.csproj").write_text(
+ '<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup>'
+ "<PackageId>Contoso.Internal</PackageId>"
+ "<IsPackable>false</IsPackable></PropertyGroup></Project>",
+ encoding="utf-8",
+ )
+ assert self._packages(tmp_path)[0] == {}
+
+ def test_an_npm_app_with_no_entry_point_publishes_nothing(self, tmp_path: Path):
+ (tmp_path / "package.json").write_text('{"name": "my-app"}', encoding="utf-8")
+ assert self._packages(tmp_path)[0] == {}
+
+ def test_a_private_npm_package_still_publishes_into_the_workspace(self, tmp_path: Path):
+ # `private` blocks the public registry, not workspace consumption.
+ (tmp_path / "package.json").write_text(
+ '{"name": "@scope/types", "private": true, "exports": {".": "./src/index.ts"}}',
+ encoding="utf-8",
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["@scope/types"].entry_files == frozenset({"src/index.ts"})
+
+ def test_npm_conditional_exports_all_count_as_entry_points(self, tmp_path: Path):
+ (tmp_path / "package.json").write_text(
+ '{"name": "p", "exports": {".": {"import": "./esm/i.js", "require": "./cjs/i.js"}},'
+ ' "types": "./types/i.d.ts"}',
+ encoding="utf-8",
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["p"].entry_files == frozenset(
+ {"esm/i.js", "cjs/i.js", "types/i.d.ts"}
+ )
+
+ def test_a_python_entry_comes_from_the_build_backend_not_the_dist_name(
+ self, tmp_path: Path
+ ):
+ # `repowise-core` ships `src/repowise`; deriving the module from the
+ # distribution name would look for `src/repowise_core` and find nothing.
+ (tmp_path / "pyproject.toml").write_text(
+ '[project]\nname = "repowise-core"\n'
+ '[tool.hatch.build.targets.wheel]\npackages = ["src/repowise"]\n',
+ encoding="utf-8",
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["repowise-core"].entry_files == frozenset(
+ {"src/repowise/__init__.py"}
+ )
+
+ def test_a_python_dunder_all_re_export_joins_the_surface(self, tmp_path: Path):
+ (tmp_path / "pyproject.toml").write_text(
+ '[project]\nname = "lib"\n', encoding="utf-8"
+ )
+ pkg = tmp_path / "lib"
+ pkg.mkdir()
+ (pkg / "__init__.py").write_text(
+ 'from .core import Widget\n\n__all__ = ["Widget"]\n', encoding="utf-8"
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["lib"].reexported == frozenset({"Widget"})
+
+ def test_a_computed_dunder_all_is_refused_rather_than_half_read(self, tmp_path: Path):
+ (tmp_path / "pyproject.toml").write_text(
+ '[project]\nname = "lib"\n', encoding="utf-8"
+ )
+ pkg = tmp_path / "lib"
+ pkg.mkdir()
+ (pkg / "__init__.py").write_text(
+ "__all__ = [*_generated(), 'Widget']\n", encoding="utf-8"
+ )
+ # The literal is still read; the computed half simply cannot be, and a
+ # partial list is a surface, not a lie about one.
+ assert self._packages(tmp_path)[0]["lib"].reexported == frozenset({"Widget"})
+
+ def test_a_cargo_crate_publishes_its_lib_root(self, tmp_path: Path):
+ (tmp_path / "Cargo.toml").write_text(
+ '[package]\nname = "widget"\n', encoding="utf-8"
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["widget"].entry_files == frozenset({"src/lib.rs"})
+
+ def test_an_ecosystem_with_no_publish_opt_in_is_counted_not_guessed(
+ self, tmp_path: Path
+ ):
+ (tmp_path / "go.mod").write_text("module example.com/widget\n", encoding="utf-8")
+ packages, counts = self._packages(tmp_path)
+ assert packages == {}
+ assert counts["code_unsupported_ecosystem"] == 1
+
+
+class TestManifestSpellings:
+ """Shapes a real manifest uses that a happy-path reader silently loses."""
+
+ def _packages(self, repo: Path):
+ packages, counts = find_published_packages("r", repo)
+ return {p.name: p for p in packages}, counts
+
+ def test_a_bare_main_is_an_entry_point(self, tmp_path: Path):
+ # `npm init` writes `"main": "index.js"`. Only `exports` values need `./`.
+ (tmp_path / "package.json").write_text(
+ '{"name": "@acme/sdk", "main": "index.js"}', encoding="utf-8"
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["@acme/sdk"].entry_files == frozenset({"index.js"})
+
+ def test_an_exports_fallback_array_is_walked(self, tmp_path: Path):
+ (tmp_path / "package.json").write_text(
+ '{"name": "p", "exports": {".": [{"import": "./esm.js"}, "./cjs.js"]}}',
+ encoding="utf-8",
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["p"].entry_files == frozenset({"esm.js", "cjs.js"})
+
+ def test_setuptools_auto_discovery_is_a_table_not_a_package_list(
+ self, tmp_path: Path
+ ):
+ # `packages = {find = {where = ["src"]}}` iterated as a list yields the
+ # key "find", which both invents a directory and suppresses the guess.
+ (tmp_path / "pyproject.toml").write_text(
+ '[project]\nname = "mylib"\n[tool.setuptools.packages.find]\nwhere = ["src"]\n',
+ encoding="utf-8",
+ )
+ packages, _ = self._packages(tmp_path)
+ assert packages["mylib"].entry_files == frozenset(
+ {"src/mylib/__init__.py", "mylib/__init__.py"}
+ )
+
+ def test_a_malformed_pyproject_cannot_abort_the_workspace(self, tmp_path: Path):
+ # `tool` as a scalar is legal TOML; an unguarded .get() chain would
+ # raise and take every other contract type down with it.
+ (tmp_path / "pyproject.toml").write_text(
+ '[project]\nname = "a"\ntool = "oops"\n', encoding="utf-8"
+ )
+ assert set(self._packages(tmp_path)[0]) == {"a"}
+
+ def test_an_unevaluated_msbuild_property_is_unknown_not_no(self, tmp_path: Path):
+ # <IsPackable>$(PublishLibraries)</IsPackable> is the normal way to
+ # centralise the flag; reading it as false would drop a real library.
+ (tmp_path / "Lib.csproj").write_text(
+ '<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup>'
+ "<PackageId>Contoso.Lib</PackageId>"
+ "<IsPackable>$(PublishLibraries)</IsPackable>"
+ "</PropertyGroup></Project>",
+ encoding="utf-8",
+ )
+ assert set(self._packages(tmp_path)[0]) == {"Contoso.Lib"}
+
+
+class TestTheImportJoin:
+ """What an importing source writes is not always the manifest's name."""
+
+ @pytest.mark.parametrize(
+ ("ecosystem", "manifest_name", "external_name"),
+ [
+ ("npm", "@scope/ui", "@scope/ui/lib/format"),
+ ("nuget", "Contoso.Orders", "nuget:Contoso.Orders.Models"),
+ ("cargo", "tokio-util", "tokio_util"),
+ ("pypi", "repowise-core", "repowise.workspace"),
+ ],
+ ids=["npm-subpath", "nuget-prefixed-namespace", "cargo-underscore", "pypi-module"],
+ )
+ def test_a_reachable_spelling_resolves_to_its_package(
+ self, ecosystem: str, manifest_name: str, external_name: str
+ ):
+ from repowise.core.workspace.code_api import (
+ PublishedPackage,
+ _import_names,
+ _package_for,
+ )
+
+ entries = frozenset({"src/repowise/__init__.py"}) if ecosystem == "pypi" else None
+ package = PublishedPackage(
+ name=manifest_name,
+ ecosystem=ecosystem,
+ repo="lib",
+ manifest="m",
+ root="",
+ entry_files=entries,
+ import_names=_import_names(ecosystem, manifest_name, entries),
+ )
+ by_import = {n: package for n in package.import_names}
+ assert _package_for(external_name, by_import) is package
+
+ def test_a_sibling_name_sharing_a_prefix_does_not_match(self):
+ from repowise.core.workspace.code_api import PublishedPackage, _package_for
+
+ ui = PublishedPackage(
+ name="@scope/ui", ecosystem="npm", repo="lib", manifest="m", root=""
+ )
+ assert _package_for("@scope/ui-icons", {"@scope/ui": ui}) is None
+
+
+class TestSurfaceScope:
+ """Published, not merely public."""
+
+ async def test_a_public_symbol_outside_an_entry_file_is_not_published(
+ self, tmp_path: Path
+ ):
+ repo = tmp_path / "lib"
+ (repo / "src").mkdir(parents=True)
+ (repo / ".repowise").mkdir()
+ (repo / "package.json").write_text(
+ '{"name": "@scope/lib", "exports": {".": "./src/index.ts"}}', encoding="utf-8"
+ )
+ (repo / "src" / "index.ts").write_text(
+ "export function published(a: string) {}\n", encoding="utf-8"
+ )
+ (repo / "src" / "internal.ts").write_text(
+ "export function hidden(a: string) {}\n", encoding="utf-8"
+ )
+ index = await make_repo_index(repo, _parse(repo), alias="lib")
+ try:
+ surface = build_code_surface(
+ {"lib": repo}, WorkspaceIndex({"lib": index}), make_exclude_predicate()
+ )
+ finally:
+ await index.close()
+ assert [c.contract_id for c in surface.for_repo("lib")] == [
+ "code::@scope/lib::published"
+ ]
+
+ async def test_an_ambiguous_dunder_all_name_is_refused_not_guessed(
+ self, tmp_path: Path
+ ):
+ """A contract's ``symbol_id`` must not be decided by index row order."""
+ repo = tmp_path / "lib"
+ (repo / "pkg").mkdir(parents=True)
+ (repo / ".repowise").mkdir()
+ (repo / "pyproject.toml").write_text(
+ '[project]\nname = "pkg"\n', encoding="utf-8"
+ )
+ (repo / "pkg" / "__init__.py").write_text(
+ "__all__ = ['Widget', 'Gauge']\n", encoding="utf-8"
+ )
+ (repo / "pkg" / "a.py").write_text("class Widget:\n pass\n", encoding="utf-8")
+ (repo / "pkg" / "b.py").write_text(
+ "class Widget:\n pass\n\n\nclass Gauge:\n pass\n", encoding="utf-8"
+ )
+ index = await make_repo_index(repo, _parse(repo), alias="lib")
+ try:
+ surface = build_code_surface(
+ {"lib": repo}, WorkspaceIndex({"lib": index}), make_exclude_predicate()
+ )
+ finally:
+ await index.close()
+ # `Gauge` is unique and published; `Widget` names two symbols, so it is
+ # not published at all rather than published as a coin flip.
+ assert [c.contract_id for c in surface.for_repo("lib")] == ["code::pkg::Gauge"]
+
+ async def test_an_import_of_an_unpublished_package_yields_no_consumer(
+ self, tmp_path: Path
+ ):
+ app = tmp_path / "app"
+ (app / ".repowise").mkdir(parents=True)
+ index = await make_repo_index(
+ app, {}, alias="app", external_edges=[("a.ts", "external:react", ["useState"])]
+ )
+ try:
+ surface = build_code_surface(
+ {"app": app}, WorkspaceIndex({"app": index}), make_exclude_predicate()
+ )
+ finally:
+ await index.close()
+ assert surface.for_repo("app") == []
diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.py
index ebc33a235..21773c049 100644
--- a/tests/unit/workspace/test_system_graph.py
+++ b/tests/unit/workspace/test_system_graph.py
@@ -313,6 +313,7 @@ def test_system_graph_json_shape_is_locked():
"http_consumer_coverage",
"symbol_identity",
"schema_coverage",
+ "code_api",
}