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): say when the system graph has too little evidence instead of scoring it clean (#4500)

Raghav Chamadiyafa30eb6e516f
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index ab6371570..8386c959a 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -333,7 +333,7 @@ The report covers:
- `external_host`, the call targets a literal third-party host (Stripe, Formspree, ...) that is not a workspace service, so it is intentionally excluded from matching.
- **Orphan providers**, endpoints declared but never consumed by any repo.
- **Weak links**, matched links below the confidence threshold.
-- **Extraction coverage**: how many contracts came from the parsed symbol table (`index`) versus a text dialect (`regex`), and how many HTTP client calls were located but could not be resolved to an endpoint. The HTTP coverage percentage is calls resolved over calls located. It is not total recall, because a call no dialect recognises is not in either number. It is the figure that turns a large orphan-provider count from alarming into explained.
+- **Extraction coverage**: how many contracts came from the parsed symbol table (`index`) versus a text dialect (`regex`), and how many HTTP client calls were located but could not be resolved to an endpoint. The HTTP coverage percentage is calls resolved over calls located, plus one per file that makes a network call (a client library, channel or raw request) no dialect read, so an unsupported client lowers the figure instead of dropping out of it. Each such file counts once, so it is a floor on what was missed, not total recall. It is the figure that turns a large orphan-provider count from alarming into explained.
The same data is available over REST at `GET /api/workspace/diagnostics` and is embedded in the system graph artifact's `diagnostics` block.
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/_shared.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/_shared.py
index e413fec71..dca0e9643 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/_shared.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/_shared.py
@@ -2,11 +2,13 @@
from __future__ import annotations
+from collections.abc import Iterable
from datetime import UTC
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import click
+from rich.markup import escape
from repowise.cli.helpers import console, find_workspace_root
@@ -58,6 +60,7 @@ def _report_artifact_provenance(
ws_config: WorkspaceConfig, # type: ignore[name-defined]
generated_at: str | None,
artifact_repos: list[str],
+ walked_repos: Iterable[str] = (),
) -> None:
"""Print how old the artifact is, and flag config/artifact disagreement.
@@ -65,6 +68,10 @@ def _report_artifact_provenance(
of the tree right now. When the config and the artifact list different
repos, that gap is itself the finding — it means the artifact describes a
workspace that no longer exists, or that the config lost a repo.
+
+ *walked_repos* are the repos the last extraction read (the graph's
+ ``repo_provenance``). One of those missing from *artifact_repos* yielded no
+ contracts; re-running the update would change nothing, so it is not told to.
"""
console.print(f"[dim]Read from .repowise-workspace/, built {_format_age(generated_at)}.[/dim]")
@@ -78,9 +85,41 @@ def _report_artifact_provenance(
f"{'is' if len(missing_from_config) == 1 else 'are'} no longer in "
f"{ws_root.name}/.repowise-workspace.yaml."
)
- if missing_from_artifact:
+ walked = set(walked_repos)
+ no_contracts = [r for r in missing_from_artifact if r in walked]
+ never_read = [r for r in missing_from_artifact if r not in walked]
+ if no_contracts:
+ console.print(
+ f"[yellow]![/yellow] {', '.join(no_contracts)} "
+ f"{'was' if len(no_contracts) == 1 else 'were'} read but yielded no "
+ "contracts, so the graph has nothing to place for "
+ f"{'it' if len(no_contracts) == 1 else 'them'}."
+ )
+ if never_read:
console.print(
- f"[yellow]![/yellow] {', '.join(missing_from_artifact)} "
- f"{'is' if len(missing_from_artifact) == 1 else 'are'} configured but "
+ f"[yellow]![/yellow] {', '.join(never_read)} "
+ f"{'is' if len(never_read) == 1 else 'are'} configured but "
"absent from this artifact; re-run 'repowise update --workspace'."
)
+
+
+def _print_evidence(evidence: dict[str, Any] | None) -> None:
+ """State how much evidence the graph rests on, before any figure built on it.
+
+ *evidence* is :meth:`GraphEvidence.to_dict`. Measured gets one quiet line;
+ partial and insufficient list every reason, since each names what is unseen.
+ """
+ if not evidence:
+ return
+ state = evidence.get("state")
+ if state == "measured":
+ console.print(
+ f"[dim]Evidence: measured ({evidence.get('runtime_edges', 0)} runtime and "
+ f"{evidence.get('build_edges', 0)} build edge(s) across "
+ f"{evidence.get('services', 0)} service(s)).[/dim]"
+ )
+ return
+ label = "Not determined" if state == "insufficient" else "Partial evidence"
+ console.print(f"[yellow]{label}:[/yellow]")
+ for reason in evidence.get("reasons", []):
+ console.print(f" [yellow]-[/yellow] {escape(reason.get('message', ''))}")
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/check.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/check.py
index d3dd7ce9c..defe5f607 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/check.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/check.py
@@ -6,17 +6,19 @@ from pathlib import Path
from typing import TYPE_CHECKING
import click
+from rich.markup import escape
from repowise.cli.helpers import console, resolve_repo_path
from repowise.cli.output import emit_json, format_option, json_option, resolve_format
-from ._shared import _report_artifact_provenance, _require_workspace
+from ._shared import _print_evidence, _report_artifact_provenance, _require_workspace
from .group import workspace_group
if TYPE_CHECKING:
from repowise.core.workspace.breaking_change import BreakingChange, BreakingChangeReport
from repowise.core.workspace.config import WorkspaceConfig
from repowise.core.workspace.conformance import ConformanceReport
+ from repowise.core.workspace.cycles import DependencyCycle
from repowise.core.workspace.system_graph import SystemGraph
@@ -87,7 +89,7 @@ def workspace_check(path: str | None, breaking: bool, fmt: str, as_json: bool) -
_print_breaking_changes(breaking_changes, bc_report)
if not report.has_findings and not breaking_changes:
- _print_check_pass(report.rules_evaluated, bc_ran)
+ _print_check_pass(report, bc_ran)
return
# Only claim a breaking-change count when a detection pass produced one.
@@ -150,8 +152,13 @@ def _print_check_scope(
them is a pass.
"""
_report_artifact_provenance(
- ws_root, ws_config, graph.generated_at, sorted({n.repo for n in graph.nodes})
+ ws_root,
+ ws_config,
+ graph.generated_at,
+ sorted({n.repo for n in graph.nodes}),
+ graph.repo_provenance,
)
+ _print_evidence(report.evidence)
console.print(
f"Checked [bold]{len(graph.nodes)}[/bold] service(s) across "
f"[bold]{len({n.repo for n in graph.nodes})}[/bold] repo(s) against "
@@ -182,9 +189,27 @@ def _print_cycles(report: ConformanceReport) -> None:
if not report.cycles:
return
console.print(f"\n[red]✗ {len(report.cycles)} dependency cycle(s):[/red]")
+ console.print(
+ " [dim]a -\\[kind]-> b: a depends on b (a subscriber depends on its publisher).[/dim]"
+ )
for c in report.cycles:
- loop = " -> ".join([*c.nodes, c.nodes[0]]) if c.nodes else ""
- console.print(f" [red]{loop}[/red]")
+ console.print(f" [red]{escape(_cycle_path(c))}[/red]")
+ if c.async_legs:
+ console.print(
+ f" [dim]{c.async_legs} of {len(c.leg_kinds)} leg(s) only an event "
+ "joins; the loop still couples schemas and deploy order.[/dim]"
+ )
+
+
+def _cycle_path(cycle: DependencyCycle) -> str:
+ """``a -[http]-> b -[event]-> a``, each leg labelled with its edge kinds."""
+ if not cycle.nodes:
+ return ""
+ parts = [cycle.nodes[0]]
+ for i, kinds in enumerate(cycle.leg_kinds):
+ nxt = cycle.nodes[(i + 1) % len(cycle.nodes)]
+ parts.append(f" -[{'/'.join(kinds) or '?'}]-> {nxt}")
+ return "".join(parts)
def _print_breaking_changes(
@@ -213,12 +238,25 @@ def _print_breaking_changes(
)
-def _print_check_pass(rule_count: int, bc_ran: bool) -> None:
+def _print_check_pass(report: ConformanceReport, bc_ran: bool) -> None:
+ """The pass line, which never calls an unmeasured graph acyclic.
+
+ Not determined is not a violation, so the check still exits 0; the reasons
+ are printed above it by :func:`_print_evidence`.
+ """
+ rule_count = report.rules_evaluated
+ state = (report.evidence or {}).get("state")
+ mark = "[green]✓[/green]"
+ if state == "insufficient":
+ mark = "[yellow]?[/yellow]"
+ cycles = "dependency cycles not determined (see above)"
+ elif state == "partial":
+ cycles = "no dependency cycles among the edges detected (partial evidence)"
+ else:
+ cycles = "no dependency cycles"
if rule_count:
- console.print(
- f"\n[green]✓[/green] No violations of {rule_count} rule(s); no dependency cycles."
- )
+ console.print(f"\n{mark} No violations of {rule_count} rule(s); {cycles}.")
else:
- console.print("\n[green]✓[/green] No dependency cycles.")
+ console.print(f"\n{mark} {cycles[0].upper()}{cycles[1:]}.")
if bc_ran:
console.print("[green]✓[/green] No breaking contract changes.")
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
index 466caf87a..1cefa3be0 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
@@ -11,7 +11,7 @@ from rich.table import Table
from repowise.cli.helpers import console, resolve_repo_path
from repowise.cli.output import emit_json, format_option, json_option, resolve_format
-from ._shared import _report_artifact_provenance, _require_workspace
+from ._shared import _print_evidence, _report_artifact_provenance, _require_workspace
from .group import workspace_group
if TYPE_CHECKING:
@@ -39,6 +39,7 @@ def workspace_diagnostics(
the answer to "why are there so few links?". Reads the system graph built
during 'repowise update --workspace'.
"""
+ from repowise.core.workspace.graph_evidence import graph_evidence
from repowise.core.workspace.system_graph import load_system_graph
fmt = resolve_format(fmt, as_json)
@@ -60,8 +61,13 @@ def workspace_diagnostics(
return
_report_artifact_provenance(
- ws_root, ws_config, graph.generated_at, [r.repo for r in diag.repo_breakdown]
+ ws_root,
+ ws_config,
+ graph.generated_at,
+ [r.repo for r in diag.repo_breakdown],
+ graph.repo_provenance,
)
+ _print_evidence(graph_evidence(graph).to_dict())
_print_breakdown_table(ws_root.name, breakdown)
_print_link_totals(diag)
_print_extraction_coverage(diag)
@@ -96,6 +102,8 @@ def _emit_diagnostics_json(
unmatched: list[UnmatchedConsumer],
orphans: list[OrphanProvider],
) -> None:
+ from repowise.core.workspace.graph_evidence import graph_evidence
+
diag = graph.diagnostics
emit_json(
{
@@ -112,6 +120,8 @@ def _emit_diagnostics_json(
"consumers_by_layer": diag.consumers_by_layer,
"http_consumers_unresolved": diag.http_consumers_unresolved,
"http_consumer_coverage": diag.http_consumer_coverage,
+ "unrecognised_call_files": diag.unrecognised_call_files,
+ "evidence": graph_evidence(graph).to_dict(),
}
)
@@ -162,19 +172,46 @@ def _print_extraction_coverage(diag: ExtractionDiagnostics) -> None:
if diag.consumers_by_layer:
layers = _layers(diag.consumers_by_layer)
console.print(f" Consumers {diag.total_consumers} ({layers})")
+ _print_call_coverage(diag)
+ console.print(
+ " [dim]'index' contracts come from the parsed symbol table, 'regex' "
+ "from a text dialect.[/dim]"
+ )
+
+
+def _print_call_coverage(diag: ExtractionDiagnostics) -> None:
+ """Resolved calls over every call seen, misses named per repo.
+
+ The denominator carries one call per file the network probe found calling
+ out with no contract read from it, so an unknown client library lowers the
+ figure. An artifact older than the probe gets counts and no percentage.
+ """
+ http_consumers = sum(r.consumers_by_type.get("http", 0) for r in diag.repo_breakdown)
+ unresolved = diag.http_consumers_unresolved
+ missed = diag.unrecognised_call_file_count
coverage = diag.http_consumer_coverage
- if coverage is not None:
- http_consumers = sum(r.consumers_by_type.get("http", 0) for r in diag.repo_breakdown)
+ if missed is None:
console.print(
- f" HTTP calls {http_consumers} of "
- f"{http_consumers + diag.http_consumers_unresolved} resolved to an "
- f"endpoint ([bold]{coverage * 100:.0f}%[/bold]); "
- f"{diag.http_consumers_unresolved} located but not statically resolvable."
+ f" HTTP calls {http_consumers} resolved, {unresolved} located but not "
+ "statically resolvable; calls no dialect recognises were not counted "
+ "(this artifact predates that count)."
)
+ return
+ if coverage is None:
+ console.print(" HTTP calls none located, and no file makes a recognisable network call.")
+ return
console.print(
- " [dim]'index' contracts come from the parsed symbol table, 'regex' "
- "from a text dialect. Calls no dialect recognises are not counted here.[/dim]"
+ f" HTTP calls {http_consumers} of {http_consumers + unresolved + missed} resolved "
+ f"([bold]{coverage * 100:.0f}%[/bold]): {unresolved} located but not statically "
+ f"resolvable, {missed} file(s) calling out through code no dialect reads."
)
+ by_repo = [(repo, n) for repo, n in (diag.unrecognised_call_files or {}).items() if n]
+ if by_repo:
+ console.print(
+ " [dim]unread network calls: "
+ + ", ".join(f"{repo} {n}" for repo, n in by_repo)
+ + "[/dim]"
+ )
_REASON_LABELS = {
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/impacted.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/impacted.py
index 59c2fae7c..f7a13faa6 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/impacted.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/impacted.py
@@ -21,6 +21,10 @@ _UNRESOLVED_REASONS = {
_EMPTY_REASONS = {
"no_contract_store": "there is no contract map yet; run 'repowise update --workspace'",
"no_matching_links": "no contract link connects the changed files to a consumer",
+ "no_contract_links": (
+ "could not determine; the contract map links no consumer to any provider in "
+ "this workspace (see 'repowise workspace diagnostics')"
+ ),
"no_changed_files": "no changed files were given",
}
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/metrics.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/metrics.py
index a5333ee09..ed3b2132d 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/metrics.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/metrics.py
@@ -7,7 +7,7 @@ import click
from repowise.cli.helpers import console, resolve_repo_path
from repowise.cli.output import emit_json, format_option, json_option, resolve_format
-from ._shared import _report_artifact_provenance, _require_workspace
+from ._shared import _print_evidence, _report_artifact_provenance, _require_workspace
from .group import workspace_group
@@ -65,13 +65,28 @@ def workspace_metrics(path: str | None, fmt: str, as_json: bool) -> None:
return
_report_artifact_provenance(
- ws_root, ws_config, graph.generated_at, sorted({n.repo for n in graph.nodes})
+ ws_root,
+ ws_config,
+ graph.generated_at,
+ sorted({n.repo for n in graph.nodes}),
+ graph.repo_provenance,
)
+ evidence = metrics.evidence.to_dict() if metrics.evidence is not None else None
+ _print_evidence(evidence)
+ if metrics.score is None:
+ # Nothing was seen to relate: no score, coupling or role is claimed.
+ console.print(
+ f"\n Architecture score [bold]not determined[/bold] [dim]({metrics.node_count} "
+ f"service(s), {metrics.structural_edge_count} structural edge(s))[/dim]"
+ )
+ return
+
+ qualifier = "" if evidence is None or evidence["state"] == "measured" else ", partial evidence"
score_color = "green" if metrics.score >= 8 else "yellow" if metrics.score >= 4 else "red"
console.print(
f"\n Architecture score [bold {score_color}]{metrics.score:.1f}[/bold {score_color}]"
- f" / 10 [dim]({metrics.architecture_type})[/dim]"
+ f" / 10 [dim]({metrics.architecture_type}{qualifier})[/dim]"
)
console.print(
f" Propagation cost [bold]{metrics.propagation_cost_pct:.1f}%[/bold]"
diff --git a/packages/core/src/repowise/core/workspace/architecture_metrics.py b/packages/core/src/repowise/core/workspace/architecture_metrics.py
index 1fddeda73..35a70c60c 100644
--- a/packages/core/src/repowise/core/workspace/architecture_metrics.py
+++ b/packages/core/src/repowise/core/workspace/architecture_metrics.py
@@ -41,6 +41,7 @@ from statistics import median
from typing import Any
from repowise.core.workspace.cycles import detect_cycles
+from repowise.core.workspace.graph_evidence import GraphEvidence, graph_evidence
from repowise.core.workspace.system_graph import SystemGraph
_log = logging.getLogger("repowise.workspace.architecture_metrics")
@@ -84,6 +85,8 @@ ROLE_ORDER: tuple[str, ...] = (ROLE_CORE, ROLE_SHARED, ROLE_CONTROL, ROLE_PERIPH
#: Architecture-type labels.
ARCH_CORE_PERIPHERY = "core-periphery"
ARCH_HIERARCHICAL = "hierarchical"
+#: The graph's evidence cannot support either label (see :mod:`.graph_evidence`).
+ARCH_UNDETERMINED = "undetermined"
# ---------------------------------------------------------------------------
@@ -142,17 +145,20 @@ class ArchitectureMetrics:
node_count: int
structural_edge_count: int
- propagation_cost: float # 0-1 fraction
- propagation_cost_pct: float # percentage, 1 decimal — for display
- core_size: int
- core_ratio: float # core_size / node_count
+ # Each measured figure is None when the graph's evidence is insufficient
+ # (see :mod:`.graph_evidence`): zero edges is "not seen", not "decoupled".
+ propagation_cost: float | None # 0-1 fraction
+ propagation_cost_pct: float | None # percentage, 1 decimal — for display
+ core_size: int | None
+ core_ratio: float | None # core_size / node_count
core_members: list[str]
- cycle_count: int
+ cycle_count: int | None
conformance_violations: int
- architecture_type: str # core-periphery | hierarchical
- score: float # 1-10
+ architecture_type: str # core-periphery | hierarchical | undetermined
+ score: float | None # 1-10
roles: list[NodeArchitectureRole] = field(default_factory=list)
generated_at: str = ""
+ evidence: GraphEvidence | None = None
def role_breakdown(self) -> dict[str, int]:
"""Count of services per role, in canonical role order."""
@@ -177,26 +183,9 @@ class ArchitectureMetrics:
"role_breakdown": self.role_breakdown(),
"roles": [r.to_dict() for r in self.roles],
"generated_at": self.generated_at,
+ "evidence": self.evidence.to_dict() if self.evidence is not None else None,
}
- @classmethod
- def from_dict(cls, data: dict[str, Any]) -> ArchitectureMetrics:
- return cls(
- node_count=data.get("node_count", 0),
- structural_edge_count=data.get("structural_edge_count", 0),
- propagation_cost=data.get("propagation_cost", 0.0),
- propagation_cost_pct=data.get("propagation_cost_pct", 0.0),
- core_size=data.get("core_size", 0),
- core_ratio=data.get("core_ratio", 0.0),
- core_members=list(data.get("core_members", [])),
- cycle_count=data.get("cycle_count", 0),
- conformance_violations=data.get("conformance_violations", 0),
- architecture_type=data.get("architecture_type", ARCH_HIERARCHICAL),
- score=data.get("score", SCORE_MAX),
- roles=[NodeArchitectureRole.from_dict(r) for r in data.get("roles", [])],
- generated_at=data.get("generated_at", ""),
- )
-
# ---------------------------------------------------------------------------
# Visibility (reachability) matrix — structural edges only
@@ -370,34 +359,25 @@ def compute_architecture_metrics(
adj = _structural_adjacency(graph)
structural_edge_count = sum(len(t) for t in adj.values())
- # Empty / single-service workspaces are vacuously decoupled — no coupling is
- # possible, so the score is the maximum and there is no core.
- if n <= 1:
- roles = [
- NodeArchitectureRole(
- id=node.id,
- repo=node.repo,
- name=node.name,
- visibility_fan_in=1,
- visibility_fan_out=1,
- role=ROLE_PERIPHERAL,
- )
- for node in graph.nodes
- ]
+ # Fewer than two services, or none joined by an edge: nothing was seen to
+ # relate, which is not the same as "decoupled". No figure is claimed.
+ evidence = graph_evidence(graph)
+ if not evidence.determined:
return ArchitectureMetrics(
node_count=n,
structural_edge_count=structural_edge_count,
- propagation_cost=0.0,
- propagation_cost_pct=0.0,
- core_size=0,
- core_ratio=0.0,
+ propagation_cost=None,
+ propagation_cost_pct=None,
+ core_size=None,
+ core_ratio=None,
core_members=[],
- cycle_count=0,
+ cycle_count=None,
conformance_violations=conformance_violations,
- architecture_type=ARCH_HIERARCHICAL,
- score=SCORE_MAX,
- roles=roles,
+ architecture_type=ARCH_UNDETERMINED,
+ score=None,
+ roles=[],
generated_at=generated_at,
+ evidence=evidence,
)
visibility = _visibility_matrix(node_ids, adj)
@@ -469,4 +449,5 @@ def compute_architecture_metrics(
score=score,
roles=roles,
generated_at=generated_at,
+ evidence=evidence,
)
diff --git a/packages/core/src/repowise/core/workspace/blast_radius.py b/packages/core/src/repowise/core/workspace/blast_radius.py
index ac27a7904..375fa075b 100644
--- a/packages/core/src/repowise/core/workspace/blast_radius.py
+++ b/packages/core/src/repowise/core/workspace/blast_radius.py
@@ -30,6 +30,7 @@ from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any
+from repowise.core.workspace.graph_evidence import graph_evidence
from repowise.core.workspace.system_graph import SystemGraph
# ---------------------------------------------------------------------------
@@ -106,6 +107,11 @@ class CrossRepoBlastRadius:
max_distance: int # deepest hop reached
total_impacted: int # true count before MAX_IMPACTED capping
unresolved_targets: list[str] = field(default_factory=list)
+ #: Resolved targets no structural edge touches in either direction. An
+ #: empty impact set for one of these is "not seen", not "nothing depends".
+ undetermined_targets: list[str] = field(default_factory=list)
+ #: :func:`.graph_evidence.graph_evidence` of the graph walked, as a dict.
+ evidence: dict[str, Any] | None = None
def to_dict(self) -> dict[str, Any]:
return {
@@ -118,6 +124,8 @@ class CrossRepoBlastRadius:
"max_distance": self.max_distance,
"total_impacted": self.total_impacted,
"unresolved_targets": self.unresolved_targets,
+ "undetermined_targets": self.undetermined_targets,
+ "evidence": self.evidence,
}
@@ -181,6 +189,7 @@ def cross_repo_blast_radius(
"""
depth = max(1, min(max_depth, MAX_DEPTH_LIMIT))
resolved, unresolved = resolve_targets(graph, targets)
+ evidence = graph_evidence(graph).to_dict()
nodes_by_id = {n.id: n for n in graph.nodes}
target_set = set(resolved)
@@ -197,11 +206,15 @@ def cross_repo_blast_radius(
max_distance=0,
total_impacted=0,
unresolved_targets=unresolved,
+ evidence=evidence,
)
# Impact direction: a change to a node reaches whatever depends on it, and
# co-change edges are symmetric, so both endpoints reach each other.
adj = graph.adjacency(behavioral=include_behavioral, impact=True)
+ # Undetermined means the walk itself has no edge at the target, so this
+ # reads the same view: co-change counts exactly when the walk follows it.
+ touched = set(adj) | {node for neighbours in adj.values() for node in neighbours}
best: dict[str, _Accum] = {}
# Frontier value per node: (propagated score, path-is-all-structural).
@@ -275,4 +288,6 @@ def cross_repo_blast_radius(
max_distance=max_distance,
total_impacted=total,
unresolved_targets=unresolved,
+ undetermined_targets=[t for t in resolved if t not in touched],
+ evidence=evidence,
)
diff --git a/packages/core/src/repowise/core/workspace/conformance.py b/packages/core/src/repowise/core/workspace/conformance.py
index aaab371fb..0ea56e9cd 100644
--- a/packages/core/src/repowise/core/workspace/conformance.py
+++ b/packages/core/src/repowise/core/workspace/conformance.py
@@ -48,6 +48,7 @@ from repowise.core.workspace.config import (
ensure_workspace_data_dir,
)
from repowise.core.workspace.cycles import DependencyCycle, detect_cycles
+from repowise.core.workspace.graph_evidence import graph_evidence
from repowise.core.workspace.system_graph import SystemGraph, SystemNode
_log = logging.getLogger("repowise.workspace.conformance")
@@ -201,6 +202,17 @@ class ConformanceReport:
cycles: list[DependencyCycle] = field(default_factory=list)
#: True cycle count before :data:`cycles.MAX_CYCLES` capped ``cycles``.
total_cycles: int = 0
+ #: :func:`.graph_evidence.graph_evidence` of the checked graph, as a dict.
+ #: None on a report written before evidence was recorded.
+ evidence: dict[str, Any] | None = None
+
+ @property
+ def cycles_determined(self) -> bool | None:
+ """False when the graph had too little evidence for "no cycles" to mean anything.
+
+ None when the report predates the evidence record, so it cannot say.
+ """
+ return None if self.evidence is None else bool(self.evidence.get("determined"))
@property
def has_findings(self) -> bool:
@@ -232,6 +244,8 @@ class ConformanceReport:
"cycle_count": len(self.cycles),
"total_cycles": self.total_cycles or len(self.cycles),
"violating_repos": self.violating_repos,
+ "cycles_determined": self.cycles_determined,
+ "evidence": self.evidence,
}
@classmethod
@@ -247,6 +261,7 @@ class ConformanceReport:
violations=[ConformanceViolation.from_dict(v) for v in data.get("violations", [])],
cycles=cycles,
total_cycles=data.get("total_cycles", len(cycles)),
+ evidence=data.get("evidence"),
)
@@ -348,6 +363,7 @@ def build_conformance_report(
violations=violations,
cycles=cycles,
total_cycles=total_cycles,
+ evidence=graph_evidence(graph).to_dict(),
)
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index dfa6a6055..72366a813 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -70,7 +70,9 @@ CONTRACTS_FILENAME = "contracts.json"
# strategy (see :mod:`.origins`), and stops linking a Laravel job class to a
# publisher that is not Laravel; HTTP consumers resolve hosts through the
# service-name map (:mod:`.service_names`), and ``service_links`` holds the
-# service-level edges for calls whose host is known but whose route is not.
+# service-level edges for calls whose host is known but whose route is not;
+# each repo also counts the files whose network calls produced no contract
+# (see :mod:`.network_probe`).
CONTRACTS_VERSION = 15
#: ``meta["kind"]`` of a topic contract: the destination a broker call names.
@@ -857,6 +859,7 @@ async def _extract_one_repo(
from .extractors import assign_service, detect_service_boundaries, merge_openapi_providers
from .extractors.base import iter_source_files
from .extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX
+ from .network_probe import UNRECOGNISED_CALL_FILES_STAT, count_unrecognised_call_files
code_surface = extraction.code_surface
contracts: list[Contract] = []
@@ -914,6 +917,12 @@ async def _extract_one_repo(
stats.update(bind_symbol_ids(contracts, repo_index))
stats.update(attach_signature_schemas(contracts, repo_index))
+ # The calls no dialect read, the miss half of any coverage figure.
+ consumer_files = {c.file_path for c in contracts if c.role == "consumer"}
+ stats[UNRECOGNISED_CALL_FILES_STAT] = await asyncio.to_thread(
+ count_unrecognised_call_files, files, consumer_files
+ )
+
unresolved = stats.get("http_consumer_unresolved", 0)
if unresolved:
_log.info(
diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.py
index 9211e752c..65ac5bfb1 100644
--- a/packages/core/src/repowise/core/workspace/diagnostics.py
+++ b/packages/core/src/repowise/core/workspace/diagnostics.py
@@ -30,6 +30,7 @@ from repowise.core.workspace.contracts import (
same_service,
)
from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX
+from repowise.core.workspace.network_probe import UNRECOGNISED_CALL_FILES_STAT
from repowise.core.workspace.signature_schema import SCHEMA_SOURCE
# ---------------------------------------------------------------------------
@@ -330,19 +331,36 @@ class ExtractionDiagnostics:
code_api: CodeApiCoverage = field(default_factory=CodeApiCoverage)
#: OpenAPI document, operation, per-side fidelity, and refusal coverage.
openapi: OpenApiCoverage = field(default_factory=OpenApiCoverage)
+ #: Per repo, files with a network-call token that produced no consumer
+ #: contract (:mod:`.network_probe`): calls no dialect recognised. None when
+ #: no repo was probed (an artifact older than the probe).
+ unrecognised_call_files: dict[str, int] | None = None
@property
- def http_consumer_coverage(self) -> float | None:
- """Share of located HTTP client calls that became a contract.
+ def unrecognised_call_file_count(self) -> int | None:
+ if self.unrecognised_call_files is None:
+ return None
+ return sum(self.unrecognised_call_files.values())
- ``None`` when nothing was located, because 0/0 is not 100%. This is a
- genuine ratio over calls extraction *saw*: it says nothing about calls
- no dialect recognised, and must not be presented as total recall.
+ @property
+ def http_consumer_coverage(self) -> float | None:
+ """Share of client calls that became an HTTP contract, misses included.
+
+ The denominator is every call extraction resolved or located, plus one
+ per file the network probe saw calling out with no contract read from
+ it, so a client library no dialect knows lowers the figure instead of
+ vanishing from it. Each such file counts once, a floor on its calls.
+ ``None`` when nothing was seen, because 0/0 is not 100%, and when the
+ artifact predates the probe, since a ratio over located calls alone
+ reads 100% whatever was missed.
"""
+ missed = self.unrecognised_call_file_count
+ if missed is None:
+ return None
http_consumers = sum(
r.consumers_by_type.get("http", 0) for r in self.repo_breakdown
)
- denominator = http_consumers + self.http_consumers_unresolved
+ denominator = http_consumers + self.http_consumers_unresolved + missed
if denominator == 0:
return None
return http_consumers / denominator
@@ -365,6 +383,8 @@ class ExtractionDiagnostics:
"schema_coverage": self.schema_coverage.to_dict(),
"code_api": self.code_api.to_dict(),
"openapi": self.openapi.to_dict(),
+ "unrecognised_call_files": self.unrecognised_call_files,
+ "unrecognised_call_file_count": self.unrecognised_call_file_count,
}
@classmethod
@@ -438,6 +458,7 @@ class ExtractionDiagnostics:
linked_providers=code.get("linked_providers", 0),
),
openapi=OpenApiCoverage.from_dict(openapi),
+ unrecognised_call_files=data.get("unrecognised_call_files"),
)
@@ -642,4 +663,17 @@ def build_diagnostics(
schema_coverage=schema,
code_api=code_api,
openapi=OpenApiCoverage.from_stats(stats_by_repo),
+ unrecognised_call_files=_unrecognised_call_files(stats_by_repo),
)
+
+
+def _unrecognised_call_files(
+ stats_by_repo: dict[str, dict[str, int]],
+) -> dict[str, int] | None:
+ """The probe's per-repo counts, or None when no repo carries one."""
+ counts = {
+ repo: stats[UNRECOGNISED_CALL_FILES_STAT]
+ for repo, stats in sorted(stats_by_repo.items())
+ if UNRECOGNISED_CALL_FILES_STAT in stats
+ }
+ return counts or None
diff --git a/packages/core/src/repowise/core/workspace/graph_evidence.py b/packages/core/src/repowise/core/workspace/graph_evidence.py
new file mode 100644
index 000000000..738744d45
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/graph_evidence.py
@@ -0,0 +1,245 @@
+"""How much evidence the system graph rests on, stated once for every view.
+
+A graph with no cross-service edges scores as perfectly decoupled, has no
+cycles and no blast radius, which reads as a clean result when it means
+nothing was linked. :func:`graph_evidence` names that state once, from the
+graph alone, so the metrics, ``workspace check``, blast radius, test impact,
+diagnostics, MCP and REST all say the same thing about the same artifact:
+
+* ``insufficient``: fewer than two services carry a contract, or no structural
+ edge joins any two. Scores, cycle verdicts and impact sets are not determined.
+* ``partial``: edges exist, but part of the estate is out of sight (only build
+ references, services with no detected dependency, repos that yielded no
+ contracts). Figures are computed and carry the reasons beside them.
+* ``measured``: every service takes part in a runtime dependency.
+
+Pure and I/O-free. Each rule is one entry in :data:`_RULES`, so a new kind of
+missing evidence is one function and one registry line.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import Any
+
+from repowise.core.workspace.system_graph import SystemGraph
+
+EVIDENCE_MEASURED = "measured"
+EVIDENCE_PARTIAL = "partial"
+EVIDENCE_INSUFFICIENT = "insufficient"
+
+#: Edge kinds that record a build-time reference (a manifest dependency, a
+#: project reference, a published-package import), not a runtime call.
+BUILD_EDGE_KINDS: frozenset[str] = frozenset({"package"})
+
+#: Cap on the names a reason lists; its count is always the true one.
+_MAX_NAMED = 8
+
+
+@dataclass(frozen=True)
+class EvidenceReason:
+ """One reason the evidence is short of measured, with the subjects it names."""
+
+ code: str
+ state: str # the state this reason alone implies: partial | insufficient
+ message: str
+ subjects: list[str] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "code": self.code,
+ "state": self.state,
+ "message": self.message,
+ "subjects": self.subjects,
+ }
+
+
+@dataclass(frozen=True)
+class GraphEvidence:
+ """The evidence state of one system graph, plus the counts behind it."""
+
+ state: str
+ reasons: list[EvidenceReason]
+ services: int
+ runtime_edges: int
+ build_edges: int
+ providers: int
+ consumers: int
+
+ @property
+ def determined(self) -> bool:
+ """False when a score, cycle verdict or impact set would be vacuous."""
+ return self.state != EVIDENCE_INSUFFICIENT
+
+ @property
+ def summary(self) -> str:
+ """The reasons as one sentence, empty when measured."""
+ return "; ".join(r.message for r in self.reasons)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "state": self.state,
+ "determined": self.determined,
+ "summary": self.summary,
+ "reasons": [r.to_dict() for r in self.reasons],
+ "services": self.services,
+ "runtime_edges": self.runtime_edges,
+ "build_edges": self.build_edges,
+ "providers": self.providers,
+ "consumers": self.consumers,
+ }
+
+
+@dataclass(frozen=True)
+class _Facts:
+ """What every rule reads, computed once per graph."""
+
+ services: list[str]
+ runtime_edges: int
+ build_edges: int
+ providers: int
+ consumers: int
+ connected: set[str]
+ walked_repos: list[str]
+ node_repos: set[str]
+
+
+def _named(subjects: list[str]) -> str:
+ shown = ", ".join(subjects[:_MAX_NAMED])
+ extra = len(subjects) - _MAX_NAMED
+ return f"{shown}, +{extra} more" if extra > 0 else shown
+
+
+def _too_few_services(facts: _Facts) -> EvidenceReason | None:
+ if len(facts.services) >= 2:
+ return None
+ count = len(facts.services)
+ return EvidenceReason(
+ code="too_few_services",
+ state=EVIDENCE_INSUFFICIENT,
+ message=(
+ "no service carries a contract"
+ if count == 0
+ else "only one service carries a contract, so there is nothing to relate it to"
+ ),
+ subjects=list(facts.services),
+ )
+
+
+def _no_cross_service_edges(facts: _Facts) -> EvidenceReason | None:
+ if len(facts.services) < 2 or facts.runtime_edges or facts.build_edges:
+ return None
+ return EvidenceReason(
+ code="no_cross_service_edges",
+ state=EVIDENCE_INSUFFICIENT,
+ message=(
+ f"no dependency between services was detected ({facts.providers} provider(s) "
+ f"and {facts.consumers} consumer(s) located, none linked across services)"
+ ),
+ )
+
+
+def _build_edges_only(facts: _Facts) -> EvidenceReason | None:
+ if facts.runtime_edges or not facts.build_edges:
+ return None
+ return EvidenceReason(
+ code="build_edges_only",
+ state=EVIDENCE_PARTIAL,
+ message=(
+ f"every detected dependency is a build reference ({facts.build_edges} package "
+ "or project edge(s)); no runtime call, event or shared table was linked"
+ ),
+ )
+
+
+def _isolated_services(facts: _Facts) -> EvidenceReason | None:
+ if not facts.connected:
+ return None # nothing is connected: the edge rules above own that case
+ isolated = [s for s in facts.services if s not in facts.connected]
+ if not isolated:
+ return None
+ return EvidenceReason(
+ code="isolated_services",
+ state=EVIDENCE_PARTIAL,
+ message=(
+ f"{len(isolated)} of {len(facts.services)} service(s) have no detected "
+ f"dependency in either direction: {_named(isolated)}"
+ ),
+ subjects=isolated,
+ )
+
+
+def _repos_without_contracts(facts: _Facts) -> EvidenceReason | None:
+ missing = [r for r in facts.walked_repos if r not in facts.node_repos]
+ if not missing:
+ return None
+ return EvidenceReason(
+ code="repos_without_contracts",
+ state=EVIDENCE_PARTIAL,
+ message=(
+ f"{len(missing)} repo(s) were read but yielded no contracts, so they are "
+ f"not in the graph: {_named(missing)}"
+ ),
+ subjects=missing,
+ )
+
+
+#: Every rule, in reporting order. A rule returns a reason or None.
+_RULES: tuple[Callable[[_Facts], EvidenceReason | None], ...] = (
+ _too_few_services,
+ _no_cross_service_edges,
+ _build_edges_only,
+ _isolated_services,
+ _repos_without_contracts,
+)
+
+
+def _facts(graph: SystemGraph) -> _Facts:
+ services = sorted(n.id for n in graph.nodes)
+ known = set(services)
+ runtime = build = 0
+ connected: set[str] = set()
+ for edge in graph.edges:
+ if not edge.structural or edge.source not in known or edge.target not in known:
+ continue
+ if edge.kind in BUILD_EDGE_KINDS:
+ build += 1
+ else:
+ runtime += 1
+ connected.update((edge.source, edge.target))
+ diagnostics = graph.diagnostics
+ return _Facts(
+ services=services,
+ runtime_edges=runtime,
+ build_edges=build,
+ providers=diagnostics.total_providers,
+ consumers=diagnostics.total_consumers,
+ connected=connected,
+ walked_repos=sorted(graph.repo_provenance),
+ node_repos={n.repo for n in graph.nodes},
+ )
+
+
+def graph_evidence(graph: SystemGraph) -> GraphEvidence:
+ """The evidence state of *graph*: measured, partial or insufficient, with reasons.
+
+ The state is the worst any rule implies. Pure; linear in nodes and edges.
+ """
+ facts = _facts(graph)
+ reasons = [r for rule in _RULES if (r := rule(facts)) is not None]
+ if any(r.state == EVIDENCE_INSUFFICIENT for r in reasons):
+ state = EVIDENCE_INSUFFICIENT
+ elif reasons:
+ state = EVIDENCE_PARTIAL
+ else:
+ state = EVIDENCE_MEASURED
+ return GraphEvidence(
+ state=state,
+ reasons=reasons,
+ services=len(facts.services),
+ runtime_edges=facts.runtime_edges,
+ build_edges=facts.build_edges,
+ providers=facts.providers,
+ consumers=facts.consumers,
+ )
diff --git a/packages/core/src/repowise/core/workspace/network_probe.py b/packages/core/src/repowise/core/workspace/network_probe.py
new file mode 100644
index 000000000..a819c28d1
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/network_probe.py
@@ -0,0 +1,180 @@
+"""Count source files that make network calls no contract was read from.
+
+Coverage over the calls a dialect located is a ratio over what extraction
+already saw: a repo whose client library no dialect knows locates nothing and
+reads as 100%. This probe is the cheap other half. Over the files the one
+extraction walk already holds in memory, it counts those that carry a
+network-call token (a client library, a channel, a raw request) yet produced no
+consumer contract. Each such file is at least one call the graph does not have.
+
+Lexical by design: it never names an endpoint or makes a contract, it only
+says that something was missed and where. Ceilings, stated so they read as
+intent: only extensions some extractor walks are probed; a token in a string
+literal still counts (comments are masked); a file whose calls were located but
+not resolved can be counted here and in ``http_consumer_unresolved`` both.
+
+Adding a client library or a language is one entry in :data:`PROBE_ROWS`.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Collection, Sequence
+from dataclasses import dataclass
+from functools import cache
+
+from repowise.core.analysis.security.masking import mask_comments_and_strings, mask_dialect
+from repowise.core.workspace.extractors import langs
+from repowise.core.workspace.extractors.base import SourceFile
+
+#: The ``extraction_stats`` key the probe writes, per repo.
+UNRECOGNISED_CALL_FILES_STAT = "call_files_unrecognised"
+
+
+@dataclass(frozen=True)
+class ProbeRow:
+ """The network-call tokens of one language, as data."""
+
+ language: str
+ extensions: frozenset[str]
+ #: Regexes, any of which marks a file as making a network call.
+ tokens: tuple[str, ...]
+ #: Whether ``#`` opens a comment in this language.
+ hash_comments: bool = False
+
+
+_JS_LIBS = r"request|request-promise(?:-native)?|superagent|needle|node-fetch|undici|got|axios|ky|ofetch|cross-fetch|isomorphic-fetch"
+
+#: One row per language, sorted by language.
+PROBE_ROWS: tuple[ProbeRow, ...] = (
+ ProbeRow(
+ "csharp",
+ langs.CSHARP | langs.VBNET,
+ (
+ r"\bHttpClient\b",
+ r"\bHttpRequestMessage\b",
+ r"\b(?:Get|Post|Put|Patch|Delete)(?:FromJson|AsJson)Async\b",
+ r"\bGrpcChannel\b",
+ r"\bAddGrpcClient\b",
+ r"\bRestSharp\b",
+ ),
+ ),
+ ProbeRow(
+ "go",
+ langs.GO,
+ (
+ r"\bhttp\.(?:Get|Post|PostForm|Head|NewRequest(?:WithContext)?)\s*\(",
+ r"\bgrpc\.(?:Dial|DialContext|NewClient)\s*\(",
+ r"\bresty\.New\s*\(",
+ ),
+ ),
+ ProbeRow(
+ "java",
+ langs.JAVA | langs.KOTLIN,
+ (
+ r"\bRestTemplate\b",
+ r"\bWebClient\b",
+ r"\bRestClient\b",
+ r"@FeignClient\b",
+ r"\bOkHttpClient\b",
+ r"\bHttpURLConnection\b",
+ r"\bHttpClient\.new",
+ r"\bManagedChannelBuilder\b",
+ ),
+ ),
+ ProbeRow(
+ "javascript",
+ langs.JS_TS,
+ (
+ rf"\brequire\(\s*['\"](?:{_JS_LIBS})['\"]\s*\)",
+ rf"\bfrom\s+['\"](?:{_JS_LIBS})['\"]",
+ # The global, not a method named fetch: no `this.fetch(` call and no
+ # declaration (`async fetch(id) {`, `fetch(id) {`, whose `)` meets `{`).
+ r"(?<![\w.$])(?<!function )(?<!async )fetch\s*\((?![^()\n]*\)\s*\{)",
+ r"\$http\s*[.(]",
+ r"\bnew\s+XMLHttpRequest\b",
+ r"\bhttps?\.(?:request|get)\s*\(",
+ ),
+ ),
+ ProbeRow(
+ "php",
+ langs.PHP,
+ (
+ r"\bcurl_init\s*\(",
+ r"\bHttp::(?:get|post|put|patch|delete|withHeaders|acceptJson|baseUrl)\b",
+ r"\bGuzzleHttp\\",
+ r"\bfile_get_contents\s*\(\s*['\"]https?://",
+ ),
+ hash_comments=True,
+ ),
+ ProbeRow(
+ "python",
+ langs.PYTHON,
+ (
+ r"\brequests\.(?:get|post|put|patch|delete|head|request|Session)\b",
+ r"\bhttpx\.(?:get|post|put|patch|delete|request|Client|AsyncClient)\b",
+ r"\baiohttp\.ClientSession\b",
+ r"\burllib\.request\.urlopen\b",
+ r"\bgrpc\.(?:insecure_|secure_)channel\b",
+ ),
+ hash_comments=True,
+ ),
+ ProbeRow(
+ "ruby",
+ langs.RUBY,
+ (
+ r"\bNet::HTTP\b",
+ r"\bFaraday\b",
+ r"\bHTTParty\b",
+ r"\bRestClient\b",
+ ),
+ hash_comments=True,
+ ),
+ ProbeRow(
+ "rust",
+ langs.RUST,
+ (
+ r"\breqwest::",
+ r"\bhyper::Client\b",
+ r"\bureq::",
+ r"\btonic::transport::Channel\b",
+ ),
+ ),
+)
+
+
+@cache
+def _by_extension() -> dict[str, tuple[re.Pattern[str], bool]]:
+ """One compiled alternation per extension, built once per process."""
+ table: dict[str, tuple[re.Pattern[str], bool]] = {}
+ for row in PROBE_ROWS:
+ pattern = re.compile("|".join(f"(?:{t})" for t in row.tokens))
+ for ext in row.extensions:
+ table[ext] = (pattern, row.hash_comments)
+ return table
+
+
+def count_unrecognised_call_files(
+ files: Sequence[SourceFile], consumer_files: Collection[str]
+) -> int:
+ """Files in *files* with a network-call token and no consumer contract.
+
+ *consumer_files* are the paths a consumer contract came from. One regex
+ search per remaining file of a probed language; only a hit pays for the
+ comment mask that confirms it.
+ """
+ table = _by_extension()
+ count = 0
+ for rel_path, suffix, content in files:
+ entry = table.get(suffix)
+ if entry is None or rel_path in consumer_files:
+ continue
+ pattern, hash_comments = entry
+ if not pattern.search(content):
+ continue
+ masked = mask_comments_and_strings(
+ content, strings=False, hash_comments=hash_comments, **mask_dialect(rel_path)
+ )
+ if pattern.search(masked):
+ count += 1
+ return count
diff --git a/packages/core/src/repowise/core/workspace/reads.py b/packages/core/src/repowise/core/workspace/reads.py
index 30d00a4e3..7abbef09c 100644
--- a/packages/core/src/repowise/core/workspace/reads.py
+++ b/packages/core/src/repowise/core/workspace/reads.py
@@ -441,6 +441,8 @@ def conformance_view(report: dict, *, repo: str | None = None) -> dict[str, Any]
# The unscoped total: how many cycles the workspace has does not change
# because the view was narrowed.
"total_cycles": total_cycles,
+ "cycles_determined": report.get("cycles_determined"),
+ "evidence": report.get("evidence"),
"violating_repos": sorted(
{_node_repo(v.get("source", "")) for v in violations}
| {_node_repo(v.get("target", "")) for v in violations}
diff --git a/packages/core/src/repowise/core/workspace/test_impact.py b/packages/core/src/repowise/core/workspace/test_impact.py
index f15a4ef46..990ce2d04 100644
--- a/packages/core/src/repowise/core/workspace/test_impact.py
+++ b/packages/core/src/repowise/core/workspace/test_impact.py
@@ -497,7 +497,10 @@ async def analyze_workspace_test_impact(
}
if not kept:
- summary["reason"] = "no_matching_links"
+ # An empty link map cannot say whether the files have consumers; only
+ # a map that links something can say these files have none.
+ linked = any(not _internal_call(link) for link in links)
+ summary["reason"] = "no_matching_links" if linked else "no_contract_links"
return WorkspaceTestImpactResult(summary=summary)
by_consumer: dict[str, list[ContractLink]] = defaultdict(list)
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index 6c6624be6..47416cfa6 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -450,18 +450,31 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
"blocks",
("role_breakdown",),
expansion_argument=None,
- protected=("summary", "architecture_type", "score", "core_members", "error"),
+ protected=("summary", "architecture_type", "score", "core_members", "evidence", "error"),
),
"get_conformance": ResponseBudgetContract(
"blocks",
expansion_argument=None,
- protected=("summary", "violation_count", "cycle_count", "total_cycles", "error"),
+ protected=(
+ "summary",
+ "violation_count",
+ "cycle_count",
+ "total_cycles",
+ "cycles_determined",
+ "error",
+ ),
),
"get_blast_radius": ResponseBudgetContract(
"blocks",
("impact_score_semantics",),
expansion_argument=None,
- protected=("summary", "targets", "total_impacted", "unresolved_targets"),
+ protected=(
+ "summary",
+ "targets",
+ "total_impacted",
+ "unresolved_targets",
+ "undetermined_targets",
+ ),
),
"list_repos": ResponseBudgetContract(
"blocks",
diff --git a/packages/server/src/repowise/server/mcp_server/_test_impact.py b/packages/server/src/repowise/server/mcp_server/_test_impact.py
index 35d0668c3..75029685e 100644
--- a/packages/server/src/repowise/server/mcp_server/_test_impact.py
+++ b/packages/server/src/repowise/server/mcp_server/_test_impact.py
@@ -111,7 +111,8 @@ async def cross_repo_tests_for(
``None`` only outside workspace mode or without contract data, so a caller
can omit its block entirely. Every other empty answer names its reason in
``summary``: ``no_matching_links`` when the contract map knows no consumer
- of those files, ``lookup_failed`` when the join itself broke. Never raises.
+ of those files, ``no_contract_links`` when it links no consumer anywhere (so
+ it cannot tell), ``lookup_failed`` when the join itself broke. Never raises.
"""
if _state._registry is None:
return None
@@ -140,7 +141,12 @@ async def cross_repo_tests_for(
{lk.consumer_repo for lk in links if lk.consumer_repo != lk.provider_repo}
)
if not changed or not consumers:
- return _empty_result("no_matching_links")
+ # Only a map that links something can say these files have no consumer.
+ linked = any(
+ raw.get("consumer_repo") != raw.get("provider_repo")
+ for raw in enricher.contract_links
+ )
+ return _empty_result("no_matching_links" if linked else "no_contract_links")
async with _lock():
opened = {}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_architecture.py b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
index 41b191fdf..b64e6be96 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_architecture.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
@@ -75,23 +75,10 @@ def architecture_payload(metrics: dict[str, Any]) -> dict[str, Any]:
core_members = metrics.get("core_members", [])
shown_core = core_members[:_MCP_CORE_MEMBER_LIMIT]
breakdown = metrics.get("role_breakdown", {})
-
- if metrics.get("core_size", 0):
- core_phrase = (
- f"a cyclic core of {metrics['core_size']} service(s) "
- f"({metrics.get('core_ratio', 0) * 100:.0f}% of the system)"
- )
- else:
- core_phrase = "no cyclic core (acyclic structure)"
- summary = (
- f"Architecture score {metrics.get('score', 0)}/10 "
- f"({metrics.get('architecture_type', 'hierarchical')}): propagation cost "
- f"{metrics.get('propagation_cost_pct', 0)}%, {core_phrase}, "
- f"{metrics.get('cycle_count', 0)} dependency cycle(s)."
- )
+ evidence = metrics.get("evidence") or {}
return {
- "score": metrics.get("score", 0.0),
+ "score": metrics.get("score"),
"architecture_type": metrics.get("architecture_type", "hierarchical"),
"propagation_cost_pct": metrics.get("propagation_cost_pct", 0.0),
"node_count": metrics.get("node_count", 0),
@@ -102,5 +89,32 @@ def architecture_payload(metrics: dict[str, Any]) -> dict[str, Any]:
"cycle_count": metrics.get("cycle_count", 0),
"conformance_violations": metrics.get("conformance_violations", 0),
"role_breakdown": breakdown,
- "summary": summary,
+ "evidence": evidence or None,
+ "summary": _summary(metrics, evidence),
}
+
+
+def _summary(metrics: dict[str, Any], evidence: dict[str, Any]) -> str:
+ """One sentence, which says "not determined" rather than score an unseen graph."""
+ if metrics.get("score") is None:
+ return (
+ f"Architecture not determined for {metrics.get('node_count', 0)} service(s): "
+ f"{evidence.get('summary') or 'no dependency between services was detected'}. "
+ "A score, coupling or cycle verdict over this graph would be vacuous."
+ )
+ if metrics.get("core_size", 0):
+ core_phrase = (
+ f"a cyclic core of {metrics['core_size']} service(s) "
+ f"({metrics.get('core_ratio', 0) * 100:.0f}% of the system)"
+ )
+ else:
+ core_phrase = "no cyclic core (acyclic structure)"
+ summary = (
+ f"Architecture score {metrics['score']}/10 "
+ f"({metrics.get('architecture_type', 'hierarchical')}): propagation cost "
+ f"{metrics.get('propagation_cost_pct', 0)}%, {core_phrase}, "
+ f"{metrics.get('cycle_count', 0)} dependency cycle(s)."
+ )
+ if evidence.get("state") == "partial":
+ summary += f" Partial evidence: {evidence.get('summary')}."
+ return summary
diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
index 850e06024..85c549eef 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
@@ -161,6 +161,8 @@ async def blast_radius_payload(
f"None of the requested targets matched a service in the graph: "
f"{result.unresolved_targets}."
)
+ elif result.undetermined_targets:
+ summary = _undetermined_summary(result)
# After the override: an unmatched-targets response must not claim consumers.
if symbol_targets and result.targets:
consumers = sum(t["consumer_count"] for t in symbol_targets)
@@ -181,6 +183,8 @@ async def blast_radius_payload(
"max_distance": result.max_distance,
"total_impacted": result.total_impacted,
"unresolved_targets": result.unresolved_targets,
+ "undetermined_targets": result.undetermined_targets,
+ "evidence": result.evidence,
"impact_score_semantics": workspace_impact_score_semantics(),
"summary": summary,
}
@@ -189,6 +193,18 @@ async def blast_radius_payload(
return payload
+def _undetermined_summary(result: Any) -> str:
+ """An empty reach for a target no edge touches is "not seen", said with why."""
+ names = ", ".join(result.undetermined_targets)
+ why = (result.evidence or {}).get("summary") or "no dependency on or from it was detected"
+ if len(result.undetermined_targets) == len(result.targets):
+ return f"Could not determine the downstream impact of {names}: {why}."
+ return (
+ f"Changing {len(result.targets)} service(s) impacts {result.total_impacted} "
+ f"downstream service(s); impact could not be determined for {names}: {why}."
+ )
+
+
def _graph_node_for(nodes_by_repo: dict[str, list[Any]], contract: dict[str, Any]) -> str | None:
"""The system-graph node that carries *contract*, or ``None``.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_conformance.py b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
index 35ec4ee96..661ea0af8 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_conformance.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
@@ -103,11 +103,17 @@ def conformance_payload(report: dict[str, Any], repo: str | None = None) -> dict
shown_violations = violations[:_MCP_VIOLATION_LIMIT]
shown_cycles = cycles[:_MCP_CYCLE_LIMIT]
+ evidence = report.get("evidence") or {}
if violations or cycles:
summary = (
f"{len(violations)} architecture rule violation(s) and {total_cycles} "
f"dependency cycle(s) from {report.get('rules_evaluated', 0)} declared rule(s)."
)
+ elif report.get("cycles_determined") is False:
+ summary = (
+ f"{report.get('rules_evaluated', 0)} declared rule(s), no violation; dependency "
+ f"cycles not determined: {evidence.get('summary')}."
+ )
elif report.get("rules_evaluated", 0):
summary = "No conformance violations or dependency cycles detected."
else:
@@ -127,5 +133,7 @@ def conformance_payload(report: dict[str, Any], repo: str | None = None) -> dict
"cycle_count": len(cycles),
"total_cycles": total_cycles,
"checked_at": report.get("generated_at"),
+ "cycles_determined": report.get("cycles_determined"),
+ "evidence": evidence or None,
"summary": summary,
}
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index d5482cd7d..48ebb25bf 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -360,9 +360,14 @@ class WorkspaceExtractionDiagnostics(BaseModel):
providers_by_layer: dict[str, int] = {}
consumers_by_layer: dict[str, int] = {}
http_consumers_unresolved: int = 0
- #: Share of located HTTP client calls that became a contract. ``None`` when
- #: none were located — 0/0 is not 100%.
+ #: Share of client calls that became an HTTP contract, counting one miss per
+ #: file that calls out through code no dialect reads. ``None`` when nothing
+ #: was seen (0/0 is not 100%) or the artifact predates that count.
http_consumer_coverage: float | None = None
+ #: Per repo, files with a network-call token and no consumer contract.
+ #: ``None`` on an artifact written before the count existed.
+ unrecognised_call_files: dict[str, int] | None = None
+ unrecognised_call_file_count: int | None = None
symbol_identity: dict[str, WorkspaceSymbolIdentity] = {}
schema_coverage: WorkspaceSchemaCoverage = WorkspaceSchemaCoverage()
@@ -371,6 +376,35 @@ class WorkspaceExtractionDiagnostics(BaseModel):
model_config = ConfigDict(extra="forbid")
+class WorkspaceEvidenceReason(BaseModel):
+ """One reason a graph's evidence is short of measured."""
+
+ code: str
+ #: The state this reason alone implies: ``partial`` or ``insufficient``.
+ state: str
+ message: str
+ subjects: list[str] = []
+
+
+class WorkspaceGraphEvidence(BaseModel):
+ """How much evidence the system graph rests on.
+
+ Mirrors ``repowise.core.workspace.graph_evidence.GraphEvidence``. When
+ ``determined`` is false, a score, cycle verdict or impact set over the
+ graph would be vacuous and is reported as not determined.
+ """
+
+ state: Literal["measured", "partial", "insufficient"]
+ determined: bool
+ summary: str = ""
+ reasons: list[WorkspaceEvidenceReason] = []
+ services: int = 0
+ runtime_edges: int = 0
+ build_edges: int = 0
+ providers: int = 0
+ consumers: int = 0
+
+
class WorkspaceSystemGraphResponse(BaseModel):
version: int = 1
generated_at: str = ""
@@ -406,6 +440,10 @@ class WorkspaceBlastRadiusResponse(BaseModel):
max_distance: int = 0
total_impacted: int = 0
unresolved_targets: list[str] = []
+ #: Resolved targets no structural edge touches: an empty reach for one of
+ #: these means "not seen", not "nothing depends on it".
+ undetermined_targets: list[str] = []
+ evidence: WorkspaceGraphEvidence | None = None
# ---------------------------------------------------------------------------
@@ -505,6 +543,10 @@ class WorkspaceConformanceResponse(BaseModel):
cycle_count: int = 0
total_cycles: int = 0
violating_repos: list[str] = []
+ #: False when the graph had too little evidence for "no cycles" to mean
+ #: anything; ``None`` on a report written before evidence was recorded.
+ cycles_determined: bool | None = None
+ evidence: WorkspaceGraphEvidence | None = None
class WorkspaceNodeArchitectureRole(BaseModel):
@@ -517,22 +559,27 @@ class WorkspaceNodeArchitectureRole(BaseModel):
class WorkspaceArchitectureResponse(BaseModel):
- """Architecture-complexity metrics over the system graph (Phase 6)."""
+ """Architecture-complexity metrics over the system graph (Phase 6).
+
+ Every measured figure is ``None`` when there is no graph, or when its
+ ``evidence`` is insufficient: nothing seen is not a 10/10.
+ """
node_count: int = 0
structural_edge_count: int = 0
- propagation_cost: float = 0.0
- propagation_cost_pct: float = 0.0
- core_size: int = 0
- core_ratio: float = 0.0
+ propagation_cost: float | None = None
+ propagation_cost_pct: float | None = None
+ core_size: int | None = None
+ core_ratio: float | None = None
core_members: list[str] = []
- cycle_count: int = 0
+ cycle_count: int | None = None
conformance_violations: int = 0
- architecture_type: str = "hierarchical"
- score: float = 10.0
+ architecture_type: str = "undetermined"
+ score: float | None = None
role_breakdown: dict[str, int] = {}
roles: list[WorkspaceNodeArchitectureRole] = []
generated_at: str = ""
+ evidence: WorkspaceGraphEvidence | None = None
# ---------------------------------------------------------------------------
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index d88c903cc..3b05f4cba 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4428,22 +4428,28 @@ export interface WorkspaceActionsResponse {
cross_repo: WorkspaceCrossRepoAction[];
}
-/** Architecture-complexity metrics over the system graph (Phase 6). */
+/**
+ * Architecture-complexity metrics over the system graph (Phase 6).
+ *
+ * Every measured figure is ``None`` when there is no graph, or when its
+ * ``evidence`` is insufficient: nothing seen is not a 10/10.
+ */
export interface WorkspaceArchitectureResponse {
node_count?: number;
structural_edge_count?: number;
- propagation_cost?: number;
- propagation_cost_pct?: number;
- core_size?: number;
- core_ratio?: number;
+ propagation_cost?: number | null;
+ propagation_cost_pct?: number | null;
+ core_size?: number | null;
+ core_ratio?: number | null;
core_members?: string[];
- cycle_count?: number;
+ cycle_count?: number | null;
conformance_violations?: number;
architecture_type?: string;
- score?: number;
+ score?: number | null;
role_breakdown?: Record<string, number>;
roles?: WorkspaceNodeArchitectureRole[];
generated_at?: string;
+ evidence?: WorkspaceGraphEvidence | null;
}
export interface WorkspaceBlastRadiusResponse {
@@ -4456,6 +4462,8 @@ export interface WorkspaceBlastRadiusResponse {
max_distance?: number;
total_impacted?: number;
unresolved_targets?: string[];
+ undetermined_targets?: string[];
+ evidence?: WorkspaceGraphEvidence | null;
}
export interface WorkspaceBreakingChange {
@@ -4540,6 +4548,8 @@ export interface WorkspaceConformanceResponse {
cycle_count?: number;
total_cycles?: number;
violating_repos?: string[];
+ cycles_determined?: boolean | null;
+ evidence?: WorkspaceGraphEvidence | null;
}
export interface WorkspaceConformanceViolation {
@@ -4643,6 +4653,14 @@ export interface WorkspaceDependencyCycle {
async_legs?: number;
}
+/** One reason a graph's evidence is short of measured. */
+export interface WorkspaceEvidenceReason {
+ code: string;
+ state: string;
+ message: string;
+ subjects?: string[];
+}
+
export interface WorkspaceExtractionDiagnostics {
total_providers?: number;
total_consumers?: number;
@@ -4656,6 +4674,8 @@ export interface WorkspaceExtractionDiagnostics {
consumers_by_layer?: Record<string, number>;
http_consumers_unresolved?: number;
http_consumer_coverage?: number | null;
+ unrecognised_call_files?: Record<string, number> | null;
+ unrecognised_call_file_count?: number | null;
symbol_identity?: Record<string, WorkspaceSymbolIdentity>;
schema_coverage?: WorkspaceSchemaCoverage;
code_api?: WorkspaceCodeApiCoverage;
@@ -4670,6 +4690,25 @@ export interface WorkspaceGraphEdge {
label?: string | null;
}
+/**
+ * How much evidence the system graph rests on.
+ *
+ * Mirrors ``repowise.core.workspace.graph_evidence.GraphEvidence``. When
+ * ``determined`` is false, a score, cycle verdict or impact set over the
+ * graph would be vacuous and is reported as not determined.
+ */
+export interface WorkspaceGraphEvidence {
+ state: "measured" | "partial" | "insufficient";
+ determined: boolean;
+ summary?: string;
+ reasons?: WorkspaceEvidenceReason[];
+ services?: number;
+ runtime_edges?: number;
+ build_edges?: number;
+ providers?: number;
+ consumers?: number;
+}
+
export interface WorkspaceGraphNode {
repo_id: string;
name: string;
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index a8ea9e28d..b03d0046e 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -214,11 +214,41 @@ export interface ExtractionDiagnostics {
/** HTTP client calls located but not resolvable to an endpoint. */
http_consumers_unresolved: number;
/**
- * Share of located HTTP client calls that became a contract, or `null` when
- * none were located — 0/0 is not 100%. Covers only calls a dialect
- * recognised, so it is not total recall.
+ * Share of client calls that became an HTTP contract, counting one miss per
+ * file that calls out through code no dialect reads. `null` when nothing was
+ * seen (0/0 is not 100%) or the artifact predates that count.
*/
http_consumer_coverage: number | null;
+ /** Per repo, files with a network-call token and no consumer contract; `null` before the count existed. */
+ unrecognised_call_files?: Record<string, number> | null;
+ unrecognised_call_file_count?: number | null;
+}
+
+/** One reason a graph's evidence is short of measured. */
+export interface GraphEvidenceReason {
+ code: string;
+ /** The state this reason alone implies. */
+ state: "partial" | "insufficient";
+ message: string;
+ subjects: string[];
+}
+
+/**
+ * How much evidence the system graph rests on. When `determined` is false a
+ * score, cycle verdict or impact set over it is "not determined", never a
+ * clean result. Mirror of `core/workspace/graph_evidence.py`.
+ */
+export interface GraphEvidence {
+ state: "measured" | "partial" | "insufficient";
+ determined: boolean;
+ /** The reasons as one sentence; empty when measured. */
+ summary: string;
+ reasons: GraphEvidenceReason[];
+ services: number;
+ runtime_edges: number;
+ build_edges: number;
+ providers: number;
+ consumers: number;
}
// ---------------------------------------------------------------------------
@@ -263,6 +293,9 @@ export interface CrossRepoBlastRadius {
total_impacted: number;
/** Target strings that matched no node or repo. */
unresolved_targets: string[];
+ /** Targets no structural edge touches: their empty reach is "not seen". */
+ undetermined_targets?: string[];
+ evidence?: GraphEvidence | null;
}
// ---------------------------------------------------------------------------
@@ -450,6 +483,9 @@ export interface ConformanceReport {
total_cycles: number;
/** Distinct repos participating in a violation. */
violating_repos: string[];
+ /** False when the graph had too little evidence for "no cycles" to mean anything. */
+ cycles_determined?: boolean | null;
+ evidence?: GraphEvidence | null;
}
// ---------------------------------------------------------------------------
@@ -495,7 +531,7 @@ export interface DsmMatrix {
export type NodeRole = "core" | "shared" | "control" | "peripheral";
/** Whether the dependency structure is core-periphery or hierarchical. */
-export type ArchitectureType = "core-periphery" | "hierarchical";
+export type ArchitectureType = "core-periphery" | "hierarchical" | "undetermined";
/** Per-service architectural role and visibility profile. */
export interface NodeArchitectureRole {
@@ -509,32 +545,36 @@ export interface NodeArchitectureRole {
role: NodeRole;
}
-/** The whole-workspace architecture-complexity metrics. */
+/**
+ * The whole-workspace architecture-complexity metrics. Every measured figure
+ * is `null` when `evidence` is insufficient: nothing seen is not a 10/10.
+ */
export interface ArchitectureMetrics {
node_count: number;
/** Count of structural (dependency) edges the metrics were computed over. */
structural_edge_count: number;
/** Fraction (0-1) of other services the average service can reach. */
- propagation_cost: number;
+ propagation_cost: number | null;
/** `propagation_cost` as a percentage, 1 decimal — for display. */
- propagation_cost_pct: number;
+ propagation_cost_pct: number | null;
/** Size of the largest cyclic group (largest SCC ≥ 2). */
- core_size: number;
+ core_size: number | null;
/** `core_size / node_count`. */
- core_ratio: number;
+ core_ratio: number | null;
/** Service ids in the largest cyclic group. */
core_members: string[];
/** Elementary dependency cycles (matches the conformance report's count). */
- cycle_count: number;
+ cycle_count: number | null;
/** Declared-rule violations folded into the score (0 when no rules). */
conformance_violations: number;
architecture_type: ArchitectureType;
/** Deterministic 1-10 architecture score (higher = lower coupling). */
- score: number;
+ score: number | null;
/** Count of services per role. */
role_breakdown: Record<NodeRole, number>;
roles: NodeArchitectureRole[];
generated_at: string;
+ evidence?: GraphEvidence | null;
}
// ---------------------------------------------------------------------------
@@ -621,7 +661,7 @@ export interface WorkspaceTestImpactResponse {
/**
* Counters plus, when the answer is empty, the `reason` that produced it
* ("no_contract_data" | "no_changed_files" | "no_matching_links" |
- * "no_contract_store" | "lookup_failed"), and for "lookup_failed" a
+ * "no_contract_links" | "no_contract_store" | "lookup_failed"), and for "lookup_failed" a
* `detail` naming what failed.
*/
summary: Record<string, unknown>;
diff --git a/packages/ui/src/workspace/contract-tests-section.tsx b/packages/ui/src/workspace/contract-tests-section.tsx
index bb7a460f4..2b73a37b1 100644
--- a/packages/ui/src/workspace/contract-tests-section.tsx
+++ b/packages/ui/src/workspace/contract-tests-section.tsx
@@ -57,6 +57,8 @@ const SUMMARY_REASON_WORDS: Record<string, string> = {
"This workspace carries no contract data, so there is no link from this file to a consumer to follow.",
no_matching_links:
"No contract link joins this file to a consumer repository, so no test in another repository can be traced back to it.",
+ no_contract_links:
+ "Could not determine: the contract map links no consumer to any provider in this workspace, so an empty answer here says nothing about this file.",
no_changed_files:
"No provider file was submitted for analysis, so nothing was traced.",
lookup_failed:
diff --git a/packages/ui/src/workspace/dsm/dsm-matrix.tsx b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
index 6b93e37e1..21924f476 100644
--- a/packages/ui/src/workspace/dsm/dsm-matrix.tsx
+++ b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
@@ -161,12 +161,17 @@ export function DsmMatrixView({ matrix, metrics, onSelectCell }: DsmMatrixViewPr
showing top {n} of {total} services by connectivity
</span>
)}
- {metrics && (
+ {metrics && metrics.score === null && (
+ <span title={metrics.evidence?.summary ?? "Too little evidence to score"}>
+ score <strong style={{ color: "var(--color-text-secondary)" }}>not determined</strong>
+ </span>
+ )}
+ {metrics && metrics.score !== null && (
<span title="Deterministic 1-10 architecture score (higher = lower coupling)">
score <strong style={{ color: "var(--color-text-secondary)" }}>{metrics.score.toFixed(1)}</strong>
</span>
)}
- {metrics && (
+ {metrics && metrics.propagation_cost_pct !== null && (
<span title="Share of other services the average service can reach transitively">
propagation{" "}
<strong style={{ color: "var(--color-text-secondary)" }}>
@@ -174,7 +179,7 @@ export function DsmMatrixView({ matrix, metrics, onSelectCell }: DsmMatrixViewPr
</strong>
</span>
)}
- {metrics && metrics.core_size > 0 && (
+ {metrics && (metrics.core_size ?? 0) > 0 && (
<span style={{ color: "var(--color-warning)" }} title="Largest cyclic group of services">
core {metrics.core_size}
</span>
diff --git a/packages/ui/src/workspace/system-map/system-map-lens-results.tsx b/packages/ui/src/workspace/system-map/system-map-lens-results.tsx
index 7f04820d3..4bdfb58d5 100644
--- a/packages/ui/src/workspace/system-map/system-map-lens-results.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-lens-results.tsx
@@ -246,7 +246,9 @@ function ConformanceResults({ conformance, graph, onSelect, onPrompt, conformanc
? "No dependency rules are declared, so only cycles are checked."
: `${plural(conformance.rules_evaluated, "rule", "rules")} checked, ${plural(conformance.violation_count, "violation", "violations")}.`;
const cycles =
- total > conformance.cycle_count
+ conformance.cycles_determined === false && conformance.cycle_count === 0
+ ? `Dependency cycles not determined: ${conformance.evidence?.summary ?? "too little evidence"}.`
+ : total > conformance.cycle_count
? `${conformance.cycle_count} of ${plural(total, "dependency cycle", "dependency cycles")} listed.`
: `${plural(conformance.cycle_count, "dependency cycle", "dependency cycles")}.`;
@@ -390,7 +392,9 @@ function CoreResults({ architecture, graph, selection, onSelect }: SystemMapLens
.join(", ");
const core = architecture.core_members.map(name);
const description =
- architecture.core_size === 0
+ architecture.core_size === null
+ ? `Core and roles not determined: ${architecture.evidence?.summary ?? "too little evidence"}.`
+ : architecture.core_size === 0
? `No services form a cycle, so there is no cyclic core. Roles: ${breakdown}.`
: `${core.join(" and ")} form the cyclic core: ${architecture.core_size} of ${architecture.node_count} services that all reach each other through contracts or imports. Roles: ${breakdown}. Reach counts other services along structural dependencies.`;
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 870e19d75..bed14a3a0 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -1561,6 +1561,10 @@
"ledeUnit": "out of 10",
"ledeSeeSystemMap": "See the system map",
"ledeSentence": "A change here can reach {pct}% of the system through {links} structural links between {services} services. The score weighs that reach against the size of the mutually dependent core and any cycles; it is computed from the system graph on every request, so it does not depend on the check below having run.",
+ "notDetermined": "not determined",
+ "ledeNotDetermined": "Not determined: {reason}. A score over a graph with nothing linked would read as perfectly decoupled, so none is given.",
+ "cyclesTitleUndetermined": "Dependency cycles",
+ "cyclesNotDeterminedTitle": "Cycles not determined",
"ledeNoGraph": "No system graph has been built yet, so there is nothing to measure. Run a workspace sync to build one.",
"dsmTitle": "Dependency-structure matrix",
"dsmDescription": "Each filled cell means the row service depends on the column service, tinted by transport. Red cells break a declared rule; amber cells sit on a cycle. The matrix counts co-change relationships too, so its total runs above the structural-link figure above.",
@@ -1827,6 +1831,8 @@
"label": "Architecture score",
"labelHint": "A 1 to 10 roll-up of propagation cost, the size of the cyclic core, dependency cycles and rule violations, over structural edges only. Higher means less coupled.",
"unit": "out of 10",
+ "notDetermined": "Not determined: {reason}.",
+ "partialEvidence": "Partial evidence: {reason}.",
"counts": "{services, plural, one {# service} other {# services}} in {repos, plural, one {# repository} other {# repositories}}, joined by {relationships, plural, one {# relationship} other {# relationships}}: {structural} structural (a contract or import in code) and {behavioral} co-change (files that change in the same commits, not a call).",
"cycleMore": "{count, plural, one {# more cycle is} other {# more cycles are}} listed under Needs attention.",
"cycleOne": "It is listed under Needs attention with a prompt to break it.",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index d36757d36..6db5f791a 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -1561,6 +1561,10 @@
"ledeUnit": "满分 10",
"ledeSeeSystemMap": "查看系统地图",
"ledeSentence": "这里的改动可经 {services} 个服务之间的 {links} 条结构链接触达全系统的 {pct}%。评分会把这一触达范围与相互依赖的核心规模以及循环依赖一起权衡;它每次请求都从系统图重新计算,因此不依赖下方检查是否运行过。",
+ "notDetermined": "无法确定",
+ "ledeNotDetermined": "无法确定:{reason}。在没有任何链接的图上评分会显得完全解耦,因此不给出分数。",
+ "cyclesTitleUndetermined": "循环依赖",
+ "cyclesNotDeterminedTitle": "无法确定循环依赖",
"ledeNoGraph": "尚未构建系统图,因此没有可度量的内容。运行一次工作区同步即可构建。",
"dsmTitle": "依赖结构矩阵",
"dsmDescription": "每个填充格表示行服务依赖列服务,颜色按传输方式着色。红色格违反了声明的规则;琥珀色格处于循环依赖上。矩阵同时统计共同变更关系,因此其总数高于上方的结构链接数量。",
@@ -1827,6 +1831,8 @@
"label": "架构评分",
"labelHint": "对影响范围、循环核心规模、依赖循环与规则违反的 1 到 10 综合评分,仅统计结构边。分数越高表示耦合越低。",
"unit": "满分 10",
+ "notDetermined": "无法确定:{reason}。",
+ "partialEvidence": "证据不完整:{reason}。",
"counts": "{services} 个服务分布在 {repos} 个仓库中,由 {relationships} 条关系相连:{structural} 条结构关系(代码中的契约或导入)与 {behavioral} 条共同变更关系(在同一批提交中一起改动的文件,而非调用)。",
"cycleMore": "另有 {count} 个循环列在「需要注意」下。",
"cycleOne": "它列在「需要注意」下,并附有一段打破它的提示词。",
diff --git a/packages/web/src/app/workspace/conformance/page.tsx b/packages/web/src/app/workspace/conformance/page.tsx
index ae526b09f..a4c5a9ed8 100644
--- a/packages/web/src/app/workspace/conformance/page.tsx
+++ b/packages/web/src/app/workspace/conformance/page.tsx
@@ -66,7 +66,13 @@ export default async function ConformancePage() {
// Cycle *membership* comes from the report, but the count is recomputed from
// the graph on every request, so it stays true even when nothing has run.
const cycles = report?.cycles ?? [];
+ // Null when the graph's evidence is insufficient: a count of zero over a
+ // graph with no edges would read as "no cycles", which nothing measured.
+ const undetermined = metrics != null && metrics.score === null;
const cycleCount = metrics?.cycle_count ?? cycles.length;
+ const notDetermined = t("notDetermined");
+ const fixed = (value: number | null | undefined, digits: number) =>
+ value == null ? "—" : value.toFixed(digits);
const matrix = buildDsm(graph, report);
@@ -83,19 +89,23 @@ export default async function ConformancePage() {
},
{
label: t("ribbon.propagationCost"),
- value: metrics ? `${metrics.propagation_cost_pct.toFixed(1)}%` : "—",
+ value:
+ metrics?.propagation_cost_pct != null
+ ? `${metrics.propagation_cost_pct.toFixed(1)}%`
+ : "—",
sub: t("ribbon.propagationCostSub"),
},
{
label: t("ribbon.coreSize"),
- value: metrics ? formatNumber(metrics.core_size) : "—",
- sub: metrics
- ? t("ribbon.coreSizeSubPct", { pct: Math.round(metrics.core_ratio * 100) })
- : t("ribbon.coreSizeSub"),
+ value: metrics?.core_size != null ? formatNumber(metrics.core_size) : "—",
+ sub:
+ metrics?.core_ratio != null
+ ? t("ribbon.coreSizeSubPct", { pct: Math.round(metrics.core_ratio * 100) })
+ : t("ribbon.coreSizeSub"),
},
{
label: t("ribbon.cycles"),
- value: metrics ? formatNumber(cycleCount) : "—",
+ value: metrics && !undetermined ? formatNumber(cycleCount) : "—",
sub: t("ribbon.cyclesSub"),
},
];
@@ -108,10 +118,14 @@ export default async function ConformancePage() {
>
<PageLede
label={t("ledeLabel")}
- value={metrics ? metrics.score.toFixed(1) : "—"}
+ value={fixed(metrics?.score, 1)}
unit={t("ledeUnit")}
{...(metrics?.architecture_type
- ? { band: { label: metrics.architecture_type } }
+ ? {
+ band: {
+ label: undetermined ? notDetermined : metrics.architecture_type,
+ },
+ }
: {})}
layout="beside"
action={
@@ -120,10 +134,12 @@ export default async function ConformancePage() {
</LedeLink>
}
>
- {metrics ? (
+ {undetermined ? (
+ <p>{t("ledeNotDetermined", { reason: metrics?.evidence?.summary ?? "" })}</p>
+ ) : metrics ? (
<p>
{t("ledeSentence", {
- pct: metrics.propagation_cost_pct.toFixed(1),
+ pct: fixed(metrics.propagation_cost_pct, 1),
links: formatNumber(metrics.structural_edge_count),
services: formatNumber(metrics.node_count),
})}
@@ -204,10 +220,16 @@ export default async function ConformancePage() {
</OverviewSection>
<OverviewSection
- title={t("cyclesTitle", { count: cycleCount })}
+ title={undetermined ? t("cyclesTitleUndetermined") : t("cyclesTitle", { count: cycleCount })}
description={t("cyclesDescription")}
>
- {cycles.length === 0 ? (
+ {cycles.length === 0 && undetermined ? (
+ <EmptyState
+ className="p-6"
+ title={t("cyclesNotDeterminedTitle")}
+ description={metrics?.evidence?.summary ?? ""}
+ />
+ ) : cycles.length === 0 ? (
<EmptyState
className="p-6"
title={
diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsx
index 8f0b04cbe..25274da23 100644
--- a/packages/web/src/app/workspace/system-map/page.tsx
+++ b/packages/web/src/app/workspace/system-map/page.tsx
@@ -330,7 +330,8 @@ function lensOptionsFor(
{
value: "core",
label: t("lens.core.label"),
- count: architecture ? String(architecture.core_size) : undefined,
+ // Null when the graph's evidence is insufficient; the lens then says why.
+ count: architecture?.core_size != null ? String(architecture.core_size) : undefined,
hint: t("lens.core.hint"),
disabledReason: failed.architecture
? t("lens.core.disabledFailed")
@@ -366,10 +367,20 @@ function Lede({
<PageLede
label={t("lede.label")}
labelHint={t("lede.labelHint")}
- value={architecture ? architecture.score.toFixed(1) : "–"}
+ value={architecture?.score != null ? architecture.score.toFixed(1) : "–"}
unit={t("lede.unit")}
layout="beside"
>
+ {architecture?.evidence && architecture.evidence.state !== "measured" ? (
+ <p>
+ {t(
+ architecture.evidence.state === "insufficient"
+ ? "lede.notDetermined"
+ : "lede.partialEvidence",
+ { reason: architecture.evidence.summary },
+ )}
+ </p>
+ ) : null}
<p>
{t("lede.counts", {
services: graph.nodes.length,
@@ -392,7 +403,9 @@ function Lede({
) : conformance?.generated_at ? (
<p>{t("lede.noCycles")}</p>
) : null}
- {architecture && (
+ {architecture &&
+ architecture.propagation_cost_pct != null &&
+ architecture.core_size != null && (
<p>
{t("lede.reachAndScore", {
pct: architecture.propagation_cost_pct.toFixed(1),
@@ -431,7 +444,10 @@ function ribbon(
},
{
label: t("ribbon.propagationCost"),
- value: architecture ? `${architecture.propagation_cost_pct.toFixed(1)}%` : "–",
+ value:
+ architecture?.propagation_cost_pct != null
+ ? `${architecture.propagation_cost_pct.toFixed(1)}%`
+ : "–",
sub: t("ribbon.propagationCostSub"),
hint: t("ribbon.propagationCostHint"),
},
diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.py
index 3f8f8c610..ba9237bb4 100644
--- a/tests/unit/cli/test_workspace_cmd.py
+++ b/tests/unit/cli/test_workspace_cmd.py
@@ -581,6 +581,7 @@ class TestWorkspaceDiagnosticsReport:
providers_by_layer={} if clean else {"index": 20, "regex": 10},
consumers_by_layer={} if clean else {"regex": 12},
http_consumers_unresolved=3,
+ unrecognised_call_files={"web": 0},
)
if not clean:
diag.unmatched_consumers = [
@@ -734,6 +735,45 @@ class TestWorkspaceCheck:
assert "cycle" in result.output.lower()
assert "frontend !-> db" in result.output
+ def test_a_cycle_closed_by_an_event_fails_and_names_each_leg(self, runner, tmp_path):
+ from repowise.core.workspace.system_graph import (
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+ save_system_graph,
+ )
+
+ self._write_config_with_rule(tmp_path, [])
+
+ def edge(s, t, kind):
+ return SystemEdge(
+ id=f"{s}->{t}:{kind}",
+ source=s,
+ target=t,
+ kind=kind,
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ )
+
+ save_system_graph(
+ SystemGraph(
+ nodes=[SystemNode(id=n, repo=n, service_path=None, name=n) for n in ("db", "frontend")],
+ edges=[edge("frontend", "db", "http"), edge("db", "frontend", "event")],
+ ),
+ tmp_path,
+ )
+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])
+ assert result.exit_code == 1, result.output
+ # networkx picks the loop's starting node, so either rotation is right.
+ assert (
+ "db -[event]-> frontend -[http]-> db" in result.output
+ or "frontend -[http]-> db -[event]-> frontend" in result.output
+ )
+ assert "1 of 2 leg(s) only an event joins" in result.output
+ assert "a subscriber depends on its publisher" in result.output
+
def test_check_clean_passes(self, runner, tmp_path):
self._write_config_with_rule(tmp_path, [{"source": "frontend", "target": "db"}])
# frontend never depends on db directly, and the graph is acyclic
@@ -1017,9 +1057,24 @@ class TestWorkspaceCheckBreaking:
assert result.exit_code == 0, result.output
assert "Checked 2 service(s) across 2 repo(s) against 0 declared rule(s)." in result.output
assert "No conformance rules declared." in result.output
- assert "No dependency cycles." in result.output
+ # Two services and no edge between them: "no cycles" would be vacuous.
+ assert "Not determined:" in result.output
+ assert "no dependency between services was detected" in result.output
+ assert "Dependency cycles not determined" in result.output
+ assert "No dependency cycles." not in result.output
assert "No violations" not in result.output
+ def test_not_determined_json_says_so(self, runner, tmp_path):
+ import json
+
+ self._write_config(tmp_path)
+ self._save_graph(tmp_path)
+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path), "--format", "json"])
+ assert result.exit_code == 0, result.output
+ data = json.loads(result.output)
+ assert data["cycles_determined"] is False
+ assert data["evidence"]["state"] == "insufficient"
+
def test_no_breaking_json_omits_the_breaking_half(self, runner, tmp_path):
import json
@@ -1138,6 +1193,74 @@ class TestWorkspaceMetrics:
assert data["conformance_violations"] == 1
assert set(data["role_breakdown"]) >= {"core", "shared", "control", "peripheral"}
+ def test_metrics_with_no_edges_is_not_determined(self, runner, tmp_path):
+ import json
+
+ self._write(tmp_path, [], [])
+ from repowise.core.workspace.system_graph import (
+ SystemGraph,
+ SystemNode,
+ save_system_graph,
+ )
+
+ save_system_graph(
+ SystemGraph(
+ nodes=[SystemNode(id=n, repo=n, service_path=None, name=n) for n in ("a", "b")],
+ repo_provenance={"a": {}, "b": {}, "c": {}},
+ ),
+ tmp_path,
+ )
+ result = runner.invoke(cli, ["workspace", "metrics", str(tmp_path)])
+ assert result.exit_code == 0, result.output
+ assert "Architecture score not determined" in result.output
+ assert "10.0" not in result.output
+ assert "1 repo(s) were read but yielded no contracts" in result.output
+ assert "Service roles" not in result.output
+ data = json.loads(
+ runner.invoke(cli, ["workspace", "metrics", str(tmp_path), "--format", "json"]).output
+ )
+ assert data["score"] is None
+ assert data["cycle_count"] is None
+ assert data["evidence"]["state"] == "insufficient"
+
+ def test_a_repo_read_without_contracts_is_not_told_to_rerun(self, runner, tmp_path):
+ from repowise.core.workspace.system_graph import (
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+ save_system_graph,
+ )
+
+ _write_workspace_config(
+ tmp_path, [{"path": n, "alias": n} for n in ("api", "web", "docs", "new")]
+ )
+ save_system_graph(
+ SystemGraph(
+ nodes=[SystemNode(id=n, repo=n, service_path=None, name=n) for n in ("api", "web")],
+ edges=[
+ SystemEdge(
+ id="web->api:http",
+ source="web",
+ target="api",
+ kind="http",
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ )
+ ],
+ repo_provenance={"api": {}, "web": {}, "docs": {}},
+ ),
+ tmp_path,
+ )
+ result = runner.invoke(cli, ["workspace", "metrics", str(tmp_path)])
+ assert result.exit_code == 0, result.output
+ out = " ".join(result.output.split())
+ assert "docs was read but yielded no contracts" in out
+ assert "new is configured but absent from this artifact" in out
+ assert "docs is configured but absent" not in out
+ assert "Partial evidence" in out
+
def test_metrics_empty_graph(self, runner, tmp_path):
self._write(tmp_path, [], [])
result = runner.invoke(cli, ["workspace", "metrics", str(tmp_path)])
diff --git a/tests/unit/server/test_mcp_blast_radius.py b/tests/unit/server/test_mcp_blast_radius.py
index e928dd9f4..f7d4cd9d9 100644
--- a/tests/unit/server/test_mcp_blast_radius.py
+++ b/tests/unit/server/test_mcp_blast_radius.py
@@ -431,3 +431,35 @@ def test_directive_reports_what_the_provider_cap_left_out(tmp_path: Path):
)
assert len(directive) == 5
assert dropped == 2
+
+
+async def test_a_target_reached_only_by_co_change_is_not_undetermined():
+ """With behavioral edges on, a co-change partner is impact the walk found."""
+ from repowise.core.workspace.system_graph import SystemEdge, SystemGraph, SystemNode
+ from repowise.server.mcp_server.tool_blast_radius import blast_radius_payload
+
+ graph = SystemGraph(
+ nodes=[SystemNode(id=n, repo=n, service_path=None, name=n) for n in ("a", "b")],
+ edges=[
+ SystemEdge(
+ id="a->b:co_change",
+ source="a",
+ target="b",
+ kind="co_change",
+ match_type="inferred",
+ confidence=1.0,
+ weight=1,
+ structural=False,
+ )
+ ],
+ )
+ payload = await blast_radius_payload(None, graph.to_dict(), ["a"])
+ assert payload["undetermined_targets"] == []
+ assert payload["total_impacted"] == 1
+ assert payload["summary"].startswith("Changing 1 service(s) impacts 1")
+
+ structural_only = await blast_radius_payload(
+ None, graph.to_dict(), ["a"], include_behavioral=False
+ )
+ assert structural_only["undetermined_targets"] == ["a"]
+ assert structural_only["summary"].startswith("Could not determine")
diff --git a/tests/unit/server/test_mcp_conformance.py b/tests/unit/server/test_mcp_conformance.py
index b96d36ce8..afc8099a0 100644
--- a/tests/unit/server/test_mcp_conformance.py
+++ b/tests/unit/server/test_mcp_conformance.py
@@ -248,3 +248,21 @@ async def test_the_architecture_payload_is_the_tool_answer_without_meta(workspac
enricher.get_architecture_metrics()
)
assert tool["node_count"] == 2
+
+
+def test_an_unseen_graph_reads_not_determined_to_an_agent():
+ """No edge between services is no score and no "no cycles", with the reason."""
+ from repowise.core.workspace.architecture_metrics import compute_architecture_metrics
+ from repowise.server.mcp_server.tool_architecture import architecture_payload
+ from repowise.server.mcp_server.tool_conformance import conformance_payload
+
+ graph = SystemGraph(nodes=[*_graph().nodes], edges=[])
+ payload = architecture_payload(compute_architecture_metrics(graph).to_dict())
+ assert payload["score"] is None
+ assert payload["cycle_count"] is None
+ assert payload["evidence"]["state"] == "insufficient"
+ assert payload["summary"].startswith("Architecture not determined for 2 service(s)")
+
+ report = conformance_payload(build_conformance_report(graph, []).to_dict())
+ assert report["cycles_determined"] is False
+ assert "cycles not determined" in report["summary"]
diff --git a/tests/unit/server/test_mcp_test_impact.py b/tests/unit/server/test_mcp_test_impact.py
index cfe897792..d01b43bff 100644
--- a/tests/unit/server/test_mcp_test_impact.py
+++ b/tests/unit/server/test_mcp_test_impact.py
@@ -100,6 +100,7 @@ class _FakeEnricher:
def __init__(self, links: list[ContractLink]) -> None:
# One dict per link, built once: the helper deduplicates by identity.
self._by_provider: dict[tuple[str, str], list[dict[str, Any]]] = {}
+ self.contract_links = [link.to_dict() for link in links]
for link in links:
key = (link.provider_repo, link.provider_file)
self._by_provider.setdefault(key, []).append(link.to_dict())
@@ -349,6 +350,14 @@ async def test_no_link_for_the_changed_file_is_named_not_silent(workspace: Path)
assert result.recommendations == []
+async def test_an_empty_link_map_says_it_cannot_tell(workspace: Path) -> None:
+ """No link anywhere is "could not determine", not "nothing consumes this file"."""
+ with _in_workspace(workspace, _FakeEnricher([])):
+ result = await cross_repo_tests("backend", [PROVIDER_FILE])
+ assert result is not None
+ assert result.summary["reason"] == "no_contract_links"
+
+
async def test_a_failed_join_names_itself_on_every_row(
workspace: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
index 583babc5b..5a90b9a3c 100644
--- a/tests/unit/server/test_workspace_router.py
+++ b/tests/unit/server/test_workspace_router.py
@@ -1237,6 +1237,31 @@ class TestGetBlastRadius:
assert "frontend" in {n["id"] for n in data["impacted"]}
assert data["structural_count"] >= 1
assert "frontend" in data["impacted_repos"]
+ assert data["undetermined_targets"] == []
+ assert data["evidence"]["state"] == "measured"
+
+ @pytest.mark.asyncio
+ async def test_architecture_states_its_evidence(self, tmp_path: Path) -> None:
+ enricher = _make_system_graph_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/architecture")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["score"] is not None
+ assert data["evidence"]["state"] == "measured"
+
+ @pytest.mark.asyncio
+ async def test_architecture_without_a_graph_claims_no_score(self) -> None:
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=None)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/architecture")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["score"] is None
+ assert data["architecture_type"] == "undetermined"
@pytest.mark.asyncio
async def test_unresolved_target_reported(self, tmp_path: Path) -> None:
diff --git a/tests/unit/workspace/test_architecture_metrics.py b/tests/unit/workspace/test_architecture_metrics.py
index 6999983a4..45c20ca7e 100644
--- a/tests/unit/workspace/test_architecture_metrics.py
+++ b/tests/unit/workspace/test_architecture_metrics.py
@@ -11,6 +11,7 @@ from __future__ import annotations
from repowise.core.workspace.architecture_metrics import (
ARCH_CORE_PERIPHERY,
ARCH_HIERARCHICAL,
+ ARCH_UNDETERMINED,
ROLE_CONTROL,
ROLE_CORE,
ROLE_PERIPHERAL,
@@ -217,6 +218,7 @@ def test_snapshot_shape_and_score_are_locked():
"role_breakdown",
"roles",
"generated_at",
+ "evidence",
}
# score = 10 - 5*(14/30) - 3*(3/6) - min(2, 0.5*1) - 0
# = 10 - 2.3333 - 1.5 - 0.5 = 5.6667 -> 5.7
@@ -241,31 +243,58 @@ def test_conformance_violations_lower_the_score():
# ---------------------------------------------------------------------------
-def test_empty_workspace():
+def _assert_undetermined(m, code):
+ assert m.score is None
+ assert m.propagation_cost is None
+ assert m.propagation_cost_pct is None
+ assert m.core_size is None
+ assert m.cycle_count is None
+ assert m.architecture_type == ARCH_UNDETERMINED
+ assert m.roles == []
+ assert m.evidence.state == "insufficient"
+ assert m.evidence.reasons[0].code == code
+ assert m.to_dict()["evidence"]["determined"] is False
+
+
+def test_empty_workspace_is_not_determined():
m = compute_architecture_metrics(SystemGraph(nodes=[], edges=[]))
assert m.node_count == 0
- assert m.propagation_cost == 0.0
- assert m.core_size == 0
- assert m.score == SCORE_MAX
- assert m.architecture_type == ARCH_HIERARCHICAL
- assert m.roles == []
+ _assert_undetermined(m, "too_few_services")
-def test_single_service_is_decoupled():
+def test_single_service_is_not_determined():
m = compute_architecture_metrics(_graph(["solo"], []))
assert m.node_count == 1
- assert m.propagation_cost == 0.0
- assert m.core_size == 0
- assert m.score == SCORE_MAX
- roles = _roles_by_id(m)
- assert roles["solo"].role == ROLE_PERIPHERAL
+ _assert_undetermined(m, "too_few_services")
-def test_independent_services_are_fully_decoupled():
+def test_services_with_no_edges_are_not_scored_as_decoupled():
+ """Zero edges is "nothing seen", never a 10/10."""
m = compute_architecture_metrics(_graph(["A", "B", "C"], []))
- assert m.propagation_cost == 0.0
- assert m.score == SCORE_MAX
- assert all(r.role == ROLE_PERIPHERAL for r in m.roles)
+ assert m.node_count == 3
+ _assert_undetermined(m, "no_cross_service_edges")
+
+
+def test_cochange_alone_is_not_evidence_of_structure():
+ m = compute_architecture_metrics(
+ _graph(["A", "B"], [_edge("A", "B", kind="co_change", structural=False)])
+ )
+ _assert_undetermined(m, "no_cross_service_edges")
+
+
+def test_build_references_only_are_scored_as_partial():
+ m = compute_architecture_metrics(
+ _graph(["A", "B", "C"], [_edge("A", "B", kind="package"), _edge("B", "C", kind="package")])
+ )
+ assert m.score is not None
+ assert m.evidence.state == "partial"
+ assert [r.code for r in m.evidence.reasons] == ["build_edges_only"]
+
+
+def test_a_connected_graph_is_measured():
+ m = compute_architecture_metrics(_graph(["A", "B", "C"], [_edge("A", "B"), _edge("B", "C")]))
+ assert m.evidence.state == "measured"
+ assert m.evidence.reasons == []
# ---------------------------------------------------------------------------
diff --git a/tests/unit/workspace/test_blast_radius.py b/tests/unit/workspace/test_blast_radius.py
index 1bfadd4aa..1c40f73fc 100644
--- a/tests/unit/workspace/test_blast_radius.py
+++ b/tests/unit/workspace/test_blast_radius.py
@@ -325,6 +325,8 @@ def test_to_dict_shape_is_locked():
"max_distance",
"total_impacted",
"unresolved_targets",
+ "undetermined_targets",
+ "evidence",
}
assert set(data["impacted"][0]) == {
"id",
diff --git a/tests/unit/workspace/test_diagnostics.py b/tests/unit/workspace/test_diagnostics.py
index 1f2291d93..e9db9c2e3 100644
--- a/tests/unit/workspace/test_diagnostics.py
+++ b/tests/unit/workspace/test_diagnostics.py
@@ -180,7 +180,7 @@ def test_contract_with_no_recorded_layer_counts_as_regex():
def test_unresolved_calls_reach_the_diagnostics_from_the_extraction_stats():
contracts = [_consumer("web", "http::GET::/u")]
- stats = {"web": {"http_consumer_unresolved": 3}}
+ stats = {"web": {"http_consumer_unresolved": 3, "call_files_unrecognised": 0}}
diag = build_diagnostics(contracts, [], stats)
@@ -212,7 +212,9 @@ def test_coverage_ignores_non_http_consumers():
_consumer("web", "http::GET::/u", ctype="http"),
_consumer("web", "grpc::Svc::M", ctype="grpc"),
]
- diag = build_diagnostics(contracts, [], {"web": {"http_consumer_unresolved": 1}})
+ diag = build_diagnostics(
+ contracts, [], {"web": {"http_consumer_unresolved": 1, "call_files_unrecognised": 0}}
+ )
assert diag.http_consumer_coverage == 0.5
@@ -220,9 +222,34 @@ def test_coverage_survives_a_serialization_round_trip():
from repowise.core.workspace.diagnostics import ExtractionDiagnostics
diag = build_diagnostics(
- [_consumer("web", "http::GET::/u")], [], {"web": {"http_consumer_unresolved": 1}}
+ [_consumer("web", "http::GET::/u")],
+ [],
+ {"web": {"http_consumer_unresolved": 1, "call_files_unrecognised": 2}},
)
restored = ExtractionDiagnostics.from_dict(diag.to_dict())
assert restored.http_consumers_unresolved == 1
- assert restored.http_consumer_coverage == 0.5
+ assert restored.unrecognised_call_files == {"web": 2}
+ assert restored.http_consumer_coverage == 0.25
assert restored.to_dict() == diag.to_dict()
+
+
+def test_unrecognised_call_files_lower_the_coverage():
+ """1 located and resolved is not 100% when 3 files call out unread."""
+ stats = {"web": {"call_files_unrecognised": 3}}
+ diag = build_diagnostics([_consumer("web", "http::GET::/u")], [], stats)
+ assert diag.unrecognised_call_file_count == 3
+ assert diag.http_consumer_coverage == 0.25
+
+
+def test_unrecognised_calls_in_a_repo_with_no_contracts_still_count():
+ """Nothing located anywhere, but files call out: 0%, not "undefined"."""
+ diag = build_diagnostics([], [], {"web": {"call_files_unrecognised": 4}})
+ assert diag.unrecognised_call_files == {"web": 4}
+ assert diag.http_consumer_coverage == 0.0
+
+
+def test_coverage_is_not_stated_before_the_probe_ran():
+ """A ratio over located calls alone reads 100% whatever was missed."""
+ diag = build_diagnostics([_consumer("web", "http::GET::/u")], [], {"web": {}})
+ assert diag.unrecognised_call_files is None
+ assert diag.http_consumer_coverage is None
diff --git a/tests/unit/workspace/test_graph_evidence.py b/tests/unit/workspace/test_graph_evidence.py
new file mode 100644
index 000000000..76b34123c
--- /dev/null
+++ b/tests/unit/workspace/test_graph_evidence.py
@@ -0,0 +1,140 @@
+"""The system graph's evidence state, and the views that must honour it."""
+
+from __future__ import annotations
+
+from repowise.core.workspace.blast_radius import cross_repo_blast_radius
+from repowise.core.workspace.conformance import build_conformance_report
+from repowise.core.workspace.diagnostics import ExtractionDiagnostics
+from repowise.core.workspace.graph_evidence import (
+ _RULES,
+ EVIDENCE_INSUFFICIENT,
+ EVIDENCE_MEASURED,
+ EVIDENCE_PARTIAL,
+ graph_evidence,
+)
+from repowise.core.workspace.system_graph import SystemEdge, SystemGraph, SystemNode
+
+
+def _edge(source: str, target: str, kind: str = "http", structural: bool = True) -> SystemEdge:
+ return SystemEdge(
+ id=f"{source}->{target}:{kind}",
+ source=source,
+ target=target,
+ kind=kind,
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=structural,
+ )
+
+
+def _graph(nodes: list[str], edges: list[SystemEdge], walked: list[str] | None = None):
+ return SystemGraph(
+ nodes=[SystemNode(id=n, repo=n, service_path=None, name=n) for n in nodes],
+ edges=edges,
+ diagnostics=ExtractionDiagnostics(total_providers=55, total_consumers=7),
+ repo_provenance={r: {} for r in (walked if walked is not None else nodes)},
+ )
+
+
+def _codes(evidence) -> list[str]:
+ return [r.code for r in evidence.reasons]
+
+
+def test_providers_without_any_link_are_insufficient():
+ """The Sock Shop shape: 55 providers, 7 consumers, 0 edges."""
+ evidence = graph_evidence(_graph(["carts", "orders", "front-end"], []))
+ assert evidence.state == EVIDENCE_INSUFFICIENT
+ assert not evidence.determined
+ assert _codes(evidence) == ["no_cross_service_edges"]
+ assert "55 provider(s) and 7 consumer(s)" in evidence.summary
+
+
+def test_one_service_is_insufficient():
+ evidence = graph_evidence(_graph(["solo"], [], walked=["solo", "other"]))
+ assert evidence.state == EVIDENCE_INSUFFICIENT
+ assert _codes(evidence) == ["too_few_services", "repos_without_contracts"]
+
+
+def test_build_references_only_are_partial():
+ """The eShop shape: project references and no runtime edge."""
+ evidence = graph_evidence(
+ _graph(["a", "b", "c"], [_edge("a", "b", "package"), _edge("b", "c", "package")])
+ )
+ assert evidence.state == EVIDENCE_PARTIAL
+ assert evidence.determined
+ assert _codes(evidence) == ["build_edges_only"]
+ assert evidence.build_edges == 2
+ assert evidence.runtime_edges == 0
+
+
+def test_an_isolated_service_and_a_repo_without_contracts_are_partial():
+ graph = _graph(
+ ["web", "api", "batch"], [_edge("web", "api")], walked=["web", "api", "batch", "infra"]
+ )
+ evidence = graph_evidence(graph)
+ assert evidence.state == EVIDENCE_PARTIAL
+ assert _codes(evidence) == ["isolated_services", "repos_without_contracts"]
+ assert evidence.reasons[0].subjects == ["batch"]
+ assert evidence.reasons[1].subjects == ["infra"]
+
+
+def test_a_co_change_edge_connects_nothing():
+ graph = _graph(["a", "b"], [_edge("a", "b", "co_change", structural=False)])
+ assert graph_evidence(graph).state == EVIDENCE_INSUFFICIENT
+
+
+def test_every_service_on_a_runtime_edge_is_measured():
+ graph = _graph(["a", "b", "c"], [_edge("a", "b"), _edge("c", "b", "event")])
+ evidence = graph_evidence(graph)
+ assert evidence.state == EVIDENCE_MEASURED
+ assert evidence.reasons == []
+ assert evidence.summary == ""
+ assert evidence.to_dict()["determined"] is True
+
+
+def test_every_rule_reports_a_closed_state():
+ """A rule's reason names the state it implies, from the closed vocabulary."""
+ worst = _graph(["x"], [], walked=["x", "y"])
+ graphs = [
+ worst,
+ _graph(["a", "b"], []),
+ _graph(["a", "b"], [_edge("a", "b", "package")]),
+ _graph(["a", "b", "c"], [_edge("a", "b")], walked=["a", "b", "c", "d"]),
+ ]
+ seen = {r.code: r.state for g in graphs for r in graph_evidence(g).reasons}
+ assert len(seen) == len(_RULES)
+ assert set(seen.values()) <= {EVIDENCE_PARTIAL, EVIDENCE_INSUFFICIENT}
+
+
+def test_conformance_report_carries_the_evidence():
+ report = build_conformance_report(_graph(["a", "b"], []), [])
+ assert report.cycles == []
+ assert report.cycles_determined is False
+ assert report.to_dict()["evidence"]["state"] == EVIDENCE_INSUFFICIENT
+
+ measured = build_conformance_report(_graph(["a", "b"], [_edge("a", "b")]), [])
+ assert measured.cycles_determined is True
+
+
+def test_blast_radius_names_targets_it_cannot_judge():
+ graph = _graph(["web", "api", "batch"], [_edge("web", "api")])
+ result = cross_repo_blast_radius(graph, ["api", "batch"])
+ assert result.undetermined_targets == ["batch"]
+ assert [n.id for n in result.impacted] == ["web"]
+ assert result.to_dict()["evidence"]["state"] == EVIDENCE_PARTIAL
+
+ empty = cross_repo_blast_radius(_graph(["a", "b"], []), ["a"])
+ assert empty.total_impacted == 0
+ assert empty.undetermined_targets == ["a"]
+ assert empty.evidence["determined"] is False
+
+
+def test_a_co_change_partner_is_determined_when_the_walk_follows_co_change():
+ graph = _graph(["a", "b"], [_edge("a", "b", "co_change", structural=False)])
+ walked = cross_repo_blast_radius(graph, ["a"])
+ assert walked.undetermined_targets == []
+ assert [n.id for n in walked.impacted] == ["b"]
+ assert cross_repo_blast_radius(graph, ["a"], include_behavioral=False).undetermined_targets == [
+ "a"
+ ]
diff --git a/tests/unit/workspace/test_network_probe.py b/tests/unit/workspace/test_network_probe.py
new file mode 100644
index 000000000..946dc5962
--- /dev/null
+++ b/tests/unit/workspace/test_network_probe.py
@@ -0,0 +1,80 @@
+"""The lexical probe for network calls no dialect turned into a contract."""
+
+from __future__ import annotations
+
+import re
+
+from repowise.core.ingestion.languages.registry import REGISTRY
+from repowise.core.workspace.network_probe import PROBE_ROWS, count_unrecognised_call_files
+
+
+def test_every_row_declares_what_the_probe_needs():
+ """A new row cannot skip a known language, its extensions or a compiling token."""
+ languages = [row.language for row in PROBE_ROWS]
+ assert languages == sorted(languages)
+ assert len(set(languages)) == len(languages)
+ for row in PROBE_ROWS:
+ assert REGISTRY.extensions_for([row.language]), row.language
+ assert row.extensions, row.language
+ assert all(ext.startswith(".") and ext == ext.lower() for ext in row.extensions)
+ assert row.tokens, row.language
+ for token in row.tokens:
+ re.compile(token)
+ claimed = [ext for row in PROBE_ROWS for ext in row.extensions]
+ assert len(claimed) == len(set(claimed)), "one extension, one row"
+
+
+def _count(files: dict[str, str], consumers: set[str] | None = None) -> int:
+ rows = [(path, "." + path.rsplit(".", 1)[1], text) for path, text in files.items()]
+ return count_unrecognised_call_files(rows, consumers or set())
+
+
+def test_a_client_library_no_dialect_reads_is_counted():
+ files = {
+ "api/cart.js": "var request = require('request');\nrequest(url, function () {});\n",
+ "Orders.java": "class O { private RestTemplate rest; }\n",
+ "Svc.cs": "var x = await client.GetFromJsonAsync<Item>(uri);\n",
+ "kernel.php": "<?php\n$ch = curl_init($url);\n",
+ }
+ assert _count(files) == 4
+
+
+def test_a_file_a_consumer_came_from_is_not_counted():
+ files = {"api/cart.js": "const r = require('request');\n"}
+ assert _count(files, {"api/cart.js"}) == 0
+
+
+def test_a_token_only_in_a_comment_is_not_counted():
+ files = {
+ "helpers.js": "/**\n * Example: fetch('http://api.example.org/users')\n */\nmodule.exports = {};\n",
+ "worker.py": "# requests.get('http://x') was removed\nimport os\n",
+ "Notes.cs": "// HttpClient is injected elsewhere\nclass N {}\n",
+ }
+ assert _count(files) == 0
+
+
+def test_a_method_named_fetch_is_not_a_network_call():
+ files = {
+ "store.js": "class S {\n async fetch(id) { return this.fetch(id); }\n}\nstore.fetch(1);\n",
+ "api.js": "export async function load() { return fetch('/api/x'); }\n",
+ }
+ assert _count(files) == 1
+
+
+def test_a_fetch_method_declaration_is_not_a_call_but_real_calls_are():
+ declarations = {
+ "repo.js": "class Repo {\n fetch(id) {\n return this.db.get(id);\n }\n}\n",
+ "api.ts": "const api = {\n fetch(id: string) { return cache[id]; },\n};\n",
+ }
+ assert _count(declarations) == 0
+ calls = {
+ "a.js": "fetch(url).then((r) => r.json());\n",
+ "b.js": "const r = await fetch(url);\n",
+ "c.js": "if (ok) { fetch(`/api/${id}`, { method: 'POST' }); }\n",
+ }
+ assert _count(calls) == 3
+
+
+def test_files_with_no_network_token_or_language_are_ignored():
+ files = {"util.js": "export const add = (a, b) => a + b;\n", "schema.sql": "SELECT 1;\n"}
+ assert _count(files) == 0
diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.py
index 8259f01f1..3f0c06b37 100644
--- a/tests/unit/workspace/test_system_graph.py
+++ b/tests/unit/workspace/test_system_graph.py
@@ -352,6 +352,8 @@ def test_system_graph_json_shape_is_locked():
"schema_coverage",
"openapi",
"code_api",
+ "unrecognised_call_files",
+ "unrecognised_call_file_count",
}
diff --git a/tests/unit/workspace/test_test_impact.py b/tests/unit/workspace/test_test_impact.py
index 3a6d30c80..44acff61a 100644
--- a/tests/unit/workspace/test_test_impact.py
+++ b/tests/unit/workspace/test_test_impact.py
@@ -494,10 +494,22 @@ async def test_a_link_inside_one_repo_and_service_is_not_cross_repo(
)
assert result.summary["relevant_contract_links"] == 0
- assert result.summary["reason"] == "no_matching_links"
+ # The only link is intra-service, so the map links no consumer across
+ # services and cannot say this file has none.
+ assert result.summary["reason"] == "no_contract_links"
assert not result.recommendations
+async def test_a_map_with_links_elsewhere_says_no_matching_links(
+ workspace: WorkspaceIndex,
+) -> None:
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND], [{"repo": "backend", "path": "app/untouched.py"}]
+ )
+
+ assert result.summary["reason"] == "no_matching_links"
+
+
async def test_a_changed_file_no_contract_names_is_reported(
workspace: WorkspaceIndex,
) -> None: