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): stamp, count and bound what the analysis actually did (#1591)

Raghav Chamadiyaa17099c1ed97
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index c63371afb..197a8a1d2 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -225,6 +225,9 @@ Scans source files for HTTP route handlers, gRPC service definitions, and messag
| gRPC | `.proto` service definitions, plus per-language dialects (Go, Java, Python, C#, TypeScript, NestJS `@GrpcMethod`) | gRPC client stubs |
| Data / DB | DDL (`CREATE TABLE`/`VIEW`/`MATERIALIZED VIEW`), ORM dialects (SQLAlchemy, Django, JPA, EF Core, ActiveRecord, Eloquent) | Raw SQL string literals in app code (verb-anchored: `SELECT`/`INSERT`/`UPDATE`/`DELETE`/`MERGE`) |
| Topics | Kafka, RabbitMQ, NATS producers | Corresponding consumers |
+| Socket / WebSocket | SignalR `MapHub<T>("/path")`, FastAPI `@app.websocket("/path")` | ClientWebSocket `ConnectAsync`, SignalR `HubConnectionBuilder.WithUrl`, NativeWebSocket and WebSocketSharp `new WebSocket(...)` |
+
+Socket detection is C#/Python only and is toggled by `detect_socket` in the `contracts:` block below.
Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](#system-graph). The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.
@@ -241,6 +244,7 @@ provides that path and a lower-confidence **candidate** when the target is ambig
contracts:
detect_http: true
detect_grpc: true
+ detect_socket: true
detect_topics: true
detect_data: true
# Map a consumer base token or absolute host to the repo it targets, so a
@@ -264,7 +268,7 @@ excluded from matching and reported under the `external_host` diagnostics reason
### Package Dependency Scanning
-Reads package manifests (`package.json`, `pyproject.toml`, `go.mod`, `pom.xml`, etc.) to detect when one repo depends on another as a package.
+Reads package manifests (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `.csproj`) to detect when one repo depends on another as a package. Maven `pom.xml` is not scanned, so a Maven repo gets no package edges.
---
@@ -305,6 +309,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.
The same data is available over REST at `GET /api/workspace/diagnostics` and is embedded in the system graph artifact's `diagnostics` block.
@@ -374,7 +379,7 @@ Detected change kinds (a registry, adding a kind is one new rule, never an `if/e
| `field_number_changed` | breaking | A proto field's wire number changed |
| `field_required` | breaking | A field became required, or a new required field was added |
-**Non-breaking changes never flag**, an added *optional* field, a widened set, or a brand-new endpoint produces no record. Field-level diffs need a contract *schema*; today gRPC carries one (proto message fields, recovered by the existing proto parser), and HTTP gains field-level checks when an OpenAPI spec is present. Route-level removal is detected for every transport from the contract id alone.
+**Non-breaking changes never flag**, an added *optional* field, a widened set, or a brand-new endpoint produces no record. Field-level diffs need a contract *schema*; today only gRPC carries one (proto message fields, recovered by the existing proto parser), so field-level checks are gRPC-only. HTTP contracts have no schema, and OpenAPI specs are not read. Route-level removal is detected for every transport from the contract id alone, HTTP included.
Impacted consumers are resolved from the matched contract links, the same provider↔consumer evidence the [system graph](#system-graph)'s edges are built from, so impact is endpoint-precise (the consumer file that calls the changed contract) and direct (the first reachability hop, which is exactly what a contract break endangers; transitive ripple stays the job of blast radius).
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index dded80dd2..d290ed340 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -103,7 +103,14 @@ export interface WorkspaceCoChangeEntry {
export interface WorkspaceCoChangesResponse {
co_changes: WorkspaceCoChangeEntry[];
+ /** Pairs matching the query, before `limit` paged them. */
total: number;
+ /**
+ * Pairs the miner scored before its edge caps trimmed the stored overlay.
+ * Not every pair in git history — each session's file list is bounded
+ * before pairing, so some pairs are in neither number.
+ */
+ total_mined: number;
}
export interface WorkspaceGraphNode {
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 16a88c312..9cc21a707 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -47,6 +47,61 @@ def _require_workspace(start: Path | None = None) -> tuple[Path, WorkspaceConfig
return ws_root, ws_config
+def _format_age(generated_at: str | None) -> str:
+ """Render an ISO timestamp as a short age, or say it is missing."""
+ from datetime import datetime
+
+ if not generated_at:
+ return "never built"
+ try:
+ stamped = datetime.fromisoformat(generated_at)
+ except ValueError:
+ return f"stamped {generated_at}"
+ if stamped.tzinfo is None:
+ stamped = stamped.replace(tzinfo=UTC)
+ seconds = (datetime.now(UTC) - stamped).total_seconds()
+ if seconds < 90:
+ return "just now"
+ if seconds < 5400:
+ return f"{round(seconds / 60)} minutes ago"
+ if seconds < 172800:
+ return f"{round(seconds / 3600)} hours ago"
+ return f"{round(seconds / 86400)} days ago"
+
+
+def _report_artifact_provenance(
+ ws_root: Path,
+ ws_config: WorkspaceConfig, # type: ignore[name-defined]
+ generated_at: str | None,
+ artifact_repos: list[str],
+) -> None:
+ """Print how old the artifact is, and flag config/artifact disagreement.
+
+ Commands that read a persisted artifact otherwise present it as the state
+ 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.
+ """
+ console.print(f"[dim]Read from .repowise-workspace/, built {_format_age(generated_at)}.[/dim]")
+
+ configured = {e.alias for e in ws_config.repos}
+ covered = set(artifact_repos)
+ missing_from_config = sorted(covered - configured)
+ missing_from_artifact = sorted(configured - covered)
+ if missing_from_config:
+ console.print(
+ f"[yellow]![/yellow] Covers {', '.join(missing_from_config)}, which "
+ f"{'is' if len(missing_from_config) == 1 else 'are'} no longer in "
+ f"{ws_root.name}/.repowise-workspace.yaml."
+ )
+ if missing_from_artifact:
+ console.print(
+ f"[yellow]![/yellow] {', '.join(missing_from_artifact)} "
+ f"{'is' if len(missing_from_artifact) == 1 else 'are'} configured but "
+ "absent from this artifact; re-run 'repowise update --workspace'."
+ )
+
+
# ---------------------------------------------------------------------------
# Command group
# ---------------------------------------------------------------------------
@@ -795,6 +850,16 @@ def workspace_remove(alias: str) -> None:
default=False,
help="Auto-add all discovered repos without prompting.",
)
+ "--exclude",
+ "exclude_globs",
+ multiple=True,
+ metavar="GLOB",
+ help=(
+ "Skip discovered repos whose path matches this glob, relative to the "
+ "workspace root (e.g. 'test-repos/*'). Repeatable."
+ ),
+)
@click.option(
"--verbose",
"-v",
@@ -802,7 +867,9 @@ def workspace_remove(alias: str) -> None:
default=False,
help="Show debug logs from the pipeline.",
)
-def workspace_scan(path: str | None, yes: bool, verbose: bool) -> None:
+def workspace_scan(
+ path: str | None, yes: bool, exclude_globs: tuple[str, ...], verbose: bool
+) -> None:
"""Scan the workspace root for new repos not yet in the config."""
configure_cli_logging(verbose=verbose)
@@ -824,6 +891,22 @@ def workspace_scan(path: str | None, yes: bool, verbose: bool) -> None:
if r.path.as_posix() not in existing_paths and r.alias not in existing_aliases
]
+ if exclude_globs:
+ from fnmatch import fnmatchcase
+
+ def _excluded(repo_path: Path) -> bool:
+ try:
+ rel = repo_path.relative_to(ws_root).as_posix()
+ except ValueError:
+ rel = repo_path.as_posix()
+ return any(fnmatchcase(rel, g) for g in exclude_globs)
+
+ before = len(new_repos)
+ new_repos = [r for r in new_repos if not _excluded(r.path)]
+ skipped = before - len(new_repos)
+ if skipped:
+ console.print(f"[dim]Excluded {skipped} repo(s) by --exclude.[/dim]")
+
if not new_repos:
console.print("[green]No new repositories discovered.[/green]")
return
@@ -835,6 +918,18 @@ def workspace_scan(path: str | None, yes: bool, verbose: bool) -> None:
console.print()
+ # A scan of a directory full of fixtures can find a hundred repos, and
+ # prompting per repo with no way out but Ctrl-C is not a choice. Ask once
+ # before starting, so declining everything costs one keystroke.
+ if not yes and not click.confirm(
+ f"Review these {len(new_repos)} repo(s) one at a time?", default=True
+ ):
+ console.print(
+ "\nNo repos added. Narrow the scan with [bold]--exclude 'dir/*'[/bold] "
+ "or add all with [bold]--yes[/bold]."
+ )
+ return
+
added = 0
for repo in new_repos:
alias = repo.alias
@@ -927,7 +1022,7 @@ def workspace_diagnostics(
fmt = resolve_format(fmt, as_json)
start = resolve_repo_path(path)
- ws_root, _ws_config = _require_workspace(start)
+ ws_root, ws_config = _require_workspace(start)
graph = load_system_graph(ws_root)
if graph is None:
@@ -948,6 +1043,7 @@ def workspace_diagnostics(
if fmt == "json":
emit_json(
{
+ "generated_at": graph.generated_at or None,
"total_providers": diag.total_providers,
"total_consumers": diag.total_consumers,
"total_links": diag.total_links,
@@ -956,10 +1052,18 @@ def workspace_diagnostics(
"unmatched_consumers": [u.to_dict() for u in unmatched],
"unmatched_by_reason": diag.unmatched_by_reason,
"orphan_providers": [o.to_dict() for o in orphans],
+ "providers_by_layer": diag.providers_by_layer,
+ "consumers_by_layer": diag.consumers_by_layer,
+ "http_consumers_unresolved": diag.http_consumers_unresolved,
+ "http_consumer_coverage": diag.http_consumer_coverage,
}
)
return
+ _report_artifact_provenance(
+ ws_root, ws_config, graph.generated_at, [r.repo for r in diag.repo_breakdown]
+ )
+
# Per-repo provider/consumer breakdown
table = Table(title=f"Contract extraction — {ws_root.name}")
table.add_column("Repo", style="cyan")
@@ -981,6 +1085,35 @@ def workspace_diagnostics(
if diag.weak_link_count:
console.print(f" [yellow]{diag.weak_link_count}[/yellow] weak (low-confidence) link(s).")
+ # Extraction coverage. Only two honest numbers exist here: which tier
+ # produced each contract, and how many client calls were located but not
+ # resolved. There is no count of route decorators nobody recognised, so no
+ # provider recall percentage is claimed.
+ def _layers(counts: dict[str, int]) -> str:
+ return ", ".join(f"{n} {layer}" for layer, n in sorted(counts.items()))
+
+ if diag.providers_by_layer or diag.consumers_by_layer:
+ console.print("\n [bold]Extraction coverage[/bold]")
+ if diag.providers_by_layer:
+ layers = _layers(diag.providers_by_layer)
+ console.print(f" Providers {diag.total_providers} ({layers})")
+ if diag.consumers_by_layer:
+ layers = _layers(diag.consumers_by_layer)
+ console.print(f" Consumers {diag.total_consumers} ({layers})")
+ 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)
+ 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."
+ )
+ 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]"
+ )
+
# Unmatched consumers grouped by reason
if unmatched:
reason_labels = {
@@ -1058,6 +1191,18 @@ def workspace_check(path: str | None, fmt: str, as_json: bool) -> None:
sys.exit(1)
return
+ # State the scope before the verdict. "No cycles" over an empty graph and
+ # "no cycles" over 7 services across 3 repos are the same sentence and very
+ # different results, and only one of them is a pass.
+ _report_artifact_provenance(
+ ws_root, ws_config, graph.generated_at, sorted({n.repo for n in graph.nodes})
+ )
+ 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 "
+ f"[bold]{report.rules_evaluated}[/bold] declared rule(s)."
+ )
+
rule_count = report.rules_evaluated
if rule_count == 0:
console.print(
@@ -1158,6 +1303,10 @@ 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})
+ )
+
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}]"
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 2613dcb18..47a4f9352 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -96,3 +96,11 @@ for _name, _target in _OSS_COMMANDS:
register_lazy_command(_name, f"{_COMMANDS_PKG}.{_target}")
cli_registry.apply(cli)
+
+
+# ``python -m repowise.cli.main`` is the documented fallback when the console
+# script is shadowed, so it has to actually run. Without this it imports the
+# module, defines ``cli``, calls nothing, and exits 0 with no output — a silent
+# no-op at exactly the moment someone is already debugging their install.
+if __name__ == "__main__":
+ cli()
diff --git a/packages/core/src/repowise/core/workspace/architecture_metrics.py b/packages/core/src/repowise/core/workspace/architecture_metrics.py
index 618381526..e56c3d1ba 100644
--- a/packages/core/src/repowise/core/workspace/architecture_metrics.py
+++ b/packages/core/src/repowise/core/workspace/architecture_metrics.py
@@ -452,7 +452,9 @@ def compute_architecture_metrics(
for node in graph.nodes
]
- cycle_count = len(detect_cycles(graph))
+ # The true count, not the reporting cap: a workspace with 500 cycles must
+ # not score the same as one with 50.
+ _, cycle_count = detect_cycles(graph)
score = architecture_score(propagation_cost, core_ratio, cycle_count, conformance_violations)
architecture_type = (
ARCH_CORE_PERIPHERY if core_ratio >= CORE_PERIPHERY_MIN_RATIO else ARCH_HIERARCHICAL
diff --git a/packages/core/src/repowise/core/workspace/breaking_change.py b/packages/core/src/repowise/core/workspace/breaking_change.py
index 64782e9da..743a74c4b 100644
--- a/packages/core/src/repowise/core/workspace/breaking_change.py
+++ b/packages/core/src/repowise/core/workspace/breaking_change.py
@@ -31,6 +31,7 @@ import json
import logging
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -177,16 +178,25 @@ class BreakingChange:
@dataclass
class BreakingChangeReport:
- """The full set of breaking changes from one workspace update + rollups."""
+ """The full set of breaking changes from one workspace update + rollups.
+
+ ``generated_at`` is ``None`` until detection actually runs. An empty
+ ``changes`` list means "nothing broke" only when this is stamped.
+ """
version: int = 1
- generated_at: str = ""
+ generated_at: str | None = None
changes: list[BreakingChange] = field(default_factory=list)
@property
def has_changes(self) -> bool:
return bool(self.changes)
+ @property
+ def ran(self) -> bool:
+ """Whether this report is the result of an actual detection pass."""
+ return bool(self.generated_at)
+
@property
def breaking_count(self) -> int:
return sum(1 for c in self.changes if c.severity == SEVERITY_BREAKING)
@@ -232,7 +242,9 @@ class BreakingChangeReport:
def from_dict(cls, data: dict[str, Any]) -> BreakingChangeReport:
return cls(
version=data.get("version", 1),
- generated_at=data.get("generated_at", ""),
+ # Artifacts written before detection was clocked carry ``""``; they
+ # read as never-ran until the next update rewrites them.
+ generated_at=data.get("generated_at") or None,
changes=[BreakingChange.from_dict(c) for c in data.get("changes", [])],
)
@@ -491,13 +503,16 @@ def detect_breaking_changes(
current: ContractStore,
*,
version: int = 1,
- generated_at: str = "",
+ generated_at: str | None = None,
) -> BreakingChangeReport:
"""Diff *previous* vs *current* provider contracts into a report (pure).
Walks every provider contract id seen in either store, dispatches the
contract-level and (when both sides carry a schema) field-level rules, and
attaches each change's direct cross-repo consumers from the matched links.
+
+ Producing a report *is* running detection, so ``generated_at`` defaults to
+ now. An unstamped report is one that was never built.
"""
prev_providers = _index_providers(previous.contracts)
curr_providers = _index_providers(current.contracts)
@@ -545,7 +560,11 @@ def detect_breaking_changes(
# Stable order: breaking before warning, then by contract id + kind.
changes.sort(key=lambda c: (c.severity != SEVERITY_BREAKING, c.contract_id, c.kind))
- return BreakingChangeReport(version=version, generated_at=generated_at, changes=changes)
+ return BreakingChangeReport(
+ version=version,
+ generated_at=generated_at or datetime.now(UTC).isoformat(),
+ changes=changes,
+ )
# ---------------------------------------------------------------------------
@@ -587,7 +606,7 @@ def run_breaking_change_detection(
previous: ContractStore,
current: ContractStore,
*,
- generated_at: str = "",
+ generated_at: str | None = None,
) -> BreakingChangeReport:
"""Diff the previous vs current contract stores and persist the report.
diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.py
index 958b7d9b4..8cfd97ea4 100644
--- a/packages/core/src/repowise/core/workspace/config.py
+++ b/packages/core/src/repowise/core/workspace/config.py
@@ -6,12 +6,15 @@ Pure data module with no CLI or DB dependencies. Handles the
from __future__ import annotations
+import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import yaml
+_log = logging.getLogger("repowise.workspace.config")
+
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
@@ -276,6 +279,7 @@ class WorkspaceConfig:
Returns the path to the written file.
"""
config_path = workspace_root / WORKSPACE_CONFIG_FILENAME
+ self._warn_if_dropping_repos(config_path)
content = yaml.dump(
self.to_dict(),
default_flow_style=False,
@@ -285,6 +289,36 @@ class WorkspaceConfig:
config_path.write_text(content, encoding="utf-8")
return config_path
+ def _warn_if_dropping_repos(self, config_path: Path) -> None:
+ """Log loudly when this write removes repos the file already had.
+
+ Every caller that saves for an unrelated reason (syncing a commit
+ stamp, adding a repo) goes through here, so a partial failure that
+ silently shrank the workspace leaves a trace instead of nothing. This
+ does not block the write — a removal may well be intended.
+ """
+ if not config_path.is_file():
+ return
+ try:
+ existing = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
+ previous = {
+ str(e.get("alias") or e.get("path"))
+ for e in existing.get("repos", [])
+ if isinstance(e, dict)
+ }
+ except Exception:
+ _log.warning("Could not read %s before overwriting it", config_path, exc_info=True)
+ return
+ dropped = previous - {e.alias for e in self.repos}
+ if dropped:
+ _log.warning(
+ "Writing %s with %d repo(s), down from %d — dropping: %s",
+ config_path,
+ len(self.repos),
+ len(previous),
+ ", ".join(sorted(dropped)),
+ )
+
@classmethod
def load(cls, workspace_root: Path) -> WorkspaceConfig:
"""Load from ``workspace_root / .repowise-workspace.yaml``.
diff --git a/packages/core/src/repowise/core/workspace/conformance.py b/packages/core/src/repowise/core/workspace/conformance.py
index 717540029..6a5ad7cc5 100644
--- a/packages/core/src/repowise/core/workspace/conformance.py
+++ b/packages/core/src/repowise/core/workspace/conformance.py
@@ -35,6 +35,7 @@ import json
import logging
from collections.abc import Callable
from dataclasses import dataclass, field
+from datetime import UTC, datetime
from fnmatch import fnmatchcase
from pathlib import Path
from typing import Any
@@ -185,18 +186,30 @@ class ConformanceViolation:
@dataclass
class ConformanceReport:
- """The workspace's architecture governance result: violations + cycles."""
+ """The workspace's architecture governance result: violations + cycles.
+
+ ``generated_at`` is ``None`` until the check actually runs. That is the
+ difference between "no violations were found" and "nothing looked", and a
+ report with zero violations means nothing without it.
+ """
version: int = 1
- generated_at: str = ""
+ generated_at: str | None = None
rules_evaluated: int = 0
violations: list[ConformanceViolation] = field(default_factory=list)
cycles: list[DependencyCycle] = field(default_factory=list)
+ #: True cycle count before :data:`cycles.MAX_CYCLES` capped ``cycles``.
+ total_cycles: int = 0
@property
def has_findings(self) -> bool:
return bool(self.violations or self.cycles)
+ @property
+ def ran(self) -> bool:
+ """Whether this report is the result of an actual check."""
+ return bool(self.generated_at)
+
@property
def violating_repos(self) -> list[str]:
repos: set[str] = set()
@@ -213,18 +226,26 @@ class ConformanceReport:
"violations": [v.to_dict() for v in self.violations],
"cycles": [c.to_dict() for c in self.cycles],
"violation_count": len(self.violations),
+ # ``cycle_count`` is what the report lists; ``total_cycles`` is how
+ # many exist. They differ only when MAX_CYCLES truncated the list.
"cycle_count": len(self.cycles),
+ "total_cycles": self.total_cycles or len(self.cycles),
"violating_repos": self.violating_repos,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ConformanceReport:
+ cycles = [DependencyCycle.from_dict(c) for c in data.get("cycles", [])]
+ # Artifacts written before the check was clocked carry ``""``. There is
+ # no way to tell those from never-ran, so they read as never-ran — the
+ # next update rewrites them with a real stamp.
return cls(
version=data.get("version", 1),
- generated_at=data.get("generated_at", ""),
+ generated_at=data.get("generated_at") or None,
rules_evaluated=data.get("rules_evaluated", 0),
violations=[ConformanceViolation.from_dict(v) for v in data.get("violations", [])],
- cycles=[DependencyCycle.from_dict(c) for c in data.get("cycles", [])],
+ cycles=cycles,
+ total_cycles=data.get("total_cycles", len(cycles)),
)
@@ -311,16 +332,21 @@ def build_conformance_report(
rules: list[ConformanceRule],
tags_by_repo: dict[str, list[str]] | None = None,
*,
- generated_at: str = "",
+ generated_at: str | None = None,
) -> ConformanceReport:
- """Assemble the full governance report: rule violations + dependency cycles."""
+ """Assemble the full governance report: rule violations + dependency cycles.
+
+ Building a report *is* running the check, so ``generated_at`` defaults to
+ now rather than to empty. Only a report nobody built is unstamped.
+ """
violations = check_conformance(graph, rules, tags_by_repo)
- cycles = detect_cycles(graph)
+ cycles, total_cycles = detect_cycles(graph)
return ConformanceReport(
- generated_at=generated_at,
+ generated_at=generated_at or datetime.now(UTC).isoformat(),
rules_evaluated=len(rules),
violations=violations,
cycles=cycles,
+ total_cycles=total_cycles,
)
@@ -368,7 +394,7 @@ def run_conformance_check(
workspace_root: Path,
graph: SystemGraph,
*,
- generated_at: str = "",
+ generated_at: str | None = None,
) -> ConformanceReport:
"""Build and persist the conformance report from the latest system graph.
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index c3ec15a46..82b2d8324 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -140,6 +140,11 @@ class ContractStore:
generated_at: str = ""
contracts: list[Contract] = field(default_factory=list)
contract_links: list[ContractLink] = field(default_factory=list)
+ #: Per-repo-alias counters the extractors filled in as they ran — what was
+ #: located but could not be turned into a contract. Without these the
+ #: contract count has no denominator, and 26 consumers looks like 26
+ #: consumers rather than 26 out of 130.
+ extraction_stats: dict[str, dict[str, int]] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
@@ -147,6 +152,7 @@ class ContractStore:
"generated_at": self.generated_at,
"contracts": [c.to_dict() for c in self.contracts],
"contract_links": [lk.to_dict() for lk in self.contract_links],
+ "extraction_stats": self.extraction_stats,
}
@classmethod
@@ -156,6 +162,7 @@ class ContractStore:
generated_at=data.get("generated_at", ""),
contracts=[Contract.from_dict(c) for c in data.get("contracts", [])],
contract_links=[ContractLink.from_dict(lk) for lk in data.get("contract_links", [])],
+ extraction_stats=data.get("extraction_stats", {}),
)
@@ -726,8 +733,12 @@ async def run_contract_extraction(
if len(repo_paths) < 2:
return ContractStore()
- # Per-repo extraction
- async def _extract_one_repo(alias: str, repo_path: Path) -> list[Contract]:
+ # Per-repo extraction. Returns the contracts plus the counters the
+ # extractors filled in, which are the denominator half of any coverage
+ # figure and so must survive past this function.
+ async def _extract_one_repo(
+ alias: str, repo_path: Path
+ ) -> tuple[list[Contract], dict[str, int]]:
contracts: list[Contract] = []
if boundaries_by_repo is not None:
@@ -748,7 +759,7 @@ async def run_contract_extraction(
if contract_config.detect_data:
extractors.append(DataExtractor())
if not extractors:
- return contracts
+ return contracts, {}
# One walk per repo, shared by every extractor. Each used to walk and
# re-read the tree itself, so a file claimed by N extractors was read N
@@ -801,14 +812,17 @@ async def run_contract_extraction(
alias,
unresolved,
)
- return contracts
+ return contracts, stats
results = await asyncio.gather(
*[_extract_one_repo(alias, path) for alias, path in repo_paths.items()]
)
all_contracts: list[Contract] = []
- for repo_contracts in results:
+ extraction_stats: dict[str, dict[str, int]] = {}
+ for alias, (repo_contracts, repo_stats) in zip(repo_paths, results, strict=True):
all_contracts.extend(repo_contracts)
+ if repo_stats:
+ extraction_stats[alias] = repo_stats
# Resolve each consumer's target service / third-party host, then match.
annotate_consumer_targets(all_contracts, contract_config.service_bases)
@@ -823,6 +837,7 @@ async def run_contract_extraction(
generated_at=datetime.now(UTC).isoformat(),
contracts=all_contracts,
contract_links=links,
+ extraction_stats=extraction_stats,
)
out_path = save_contract_store(store, workspace_root)
diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.py
index 54d4d44a1..c01ee342c 100644
--- a/packages/core/src/repowise/core/workspace/cross_repo.py
+++ b/packages/core/src/repowise/core/workspace/cross_repo.py
@@ -187,6 +187,13 @@ class CrossRepoOverlay:
co_changes: list[CrossRepoCoChange] = field(default_factory=list)
package_deps: list[CrossRepoPackageDep] = field(default_factory=list)
repo_summaries: dict[str, dict] = field(default_factory=dict)
+ #: How many pairs cleared the strength/session thresholds before
+ #: ``_MAX_EDGES`` / ``_MAX_EDGES_PER_REPO_PAIR`` trimmed ``co_changes``.
+ #: Equal to ``len(co_changes)`` when nothing was dropped. Not a count of
+ #: every pair in git history: ``_MAX_FILES_PER_SESSION_SIDE`` bounds each
+ #: session before pairing, so pairs involving an evicted file are in
+ #: neither number.
+ total_co_changes: int = 0
def to_dict(self) -> dict:
return {
@@ -195,16 +202,19 @@ class CrossRepoOverlay:
"co_changes": [asdict(c) for c in self.co_changes],
"package_deps": [asdict(d) for d in self.package_deps],
"repo_summaries": self.repo_summaries,
+ "total_co_changes": self.total_co_changes or len(self.co_changes),
}
@classmethod
def from_dict(cls, data: dict) -> CrossRepoOverlay:
+ co_changes = [CrossRepoCoChange(**c) for c in data.get("co_changes", [])]
return cls(
version=data.get("version", 1),
generated_at=data.get("generated_at", ""),
- co_changes=[CrossRepoCoChange(**c) for c in data.get("co_changes", [])],
+ co_changes=co_changes,
package_deps=[CrossRepoPackageDep(**d) for d in data.get("package_deps", [])],
repo_summaries=data.get("repo_summaries", {}),
+ total_co_changes=data.get("total_co_changes", len(co_changes)),
)
@@ -383,7 +393,7 @@ def detect_cross_repo_co_changes(
commit_limit: int = _DEFAULT_COMMIT_LIMIT,
min_score: float = _MIN_CROSS_REPO_SCORE,
min_sessions: int = _MIN_CO_SESSIONS,
-) -> list[CrossRepoCoChange]:
+) -> tuple[list[CrossRepoCoChange], int]:
"""Find files across repos that the same author changes in the same
work sessions.
@@ -401,9 +411,14 @@ def detect_cross_repo_co_changes(
recent work that also touched the partner"
6. Keep pairs with >= min_sessions co-sessions and strength >= min_score,
cap per repo pair, then globally
+
+ Returns the capped list and the number of pairs that cleared step 6's
+ thresholds before capping, so the caller can say how much it is showing.
+ That total is measured after step 3's per-session file cap, so it bounds
+ what this miner scored, not what git history contains.
"""
if len(repo_paths) < 2:
- return []
+ return [], 0
now_ts = time.time()
window_seconds = time_window_hours * 3600
@@ -429,7 +444,7 @@ def detect_cross_repo_co_changes(
repo_commits = _drop_ubiquitous_files(filtered)
if len(repo_commits) < 2:
- return []
+ return [], 0
# Step 3: Group all commits by author identity, tagged with repo alias
author_commits: dict[str, list[tuple[str, _GitCommit]]] = defaultdict(list)
@@ -543,7 +558,15 @@ def detect_cross_repo_co_changes(
capped.append(r)
if len(capped) >= _MAX_EDGES:
break
- return capped
+ if len(capped) < len(results):
+ _log.info(
+ "Co-change mining kept %d of %d qualifying pairs (caps: %d total, %d per repo pair)",
+ len(capped),
+ len(results),
+ _MAX_EDGES,
+ _MAX_EDGES_PER_REPO_PAIR,
+ )
+ return capped, len(results)
# ---------------------------------------------------------------------------
@@ -565,7 +588,15 @@ def _resolve_target_repo(
):
return alias
except Exception:
- pass
+ # A manifest reference that cannot be resolved to a path is the one
+ # way this returns None without having compared anything, so it is
+ # worth distinguishing from "resolved fine, matched no repo".
+ _log.warning(
+ "Could not resolve manifest reference %r relative to %s",
+ relative_ref,
+ source_repo_path,
+ exc_info=True,
+ )
return None
@@ -1001,7 +1032,9 @@ async def run_cross_repo_analysis(
# Co-change detection (CPU-bound git subprocess calls)
import asyncio
- co_changes = await asyncio.to_thread(detect_cross_repo_co_changes, repo_paths)
+ co_changes, total_co_changes = await asyncio.to_thread(
+ detect_cross_repo_co_changes, repo_paths
+ )
# Package dependency detection (file I/O)
package_deps = await asyncio.to_thread(detect_package_dependencies, repo_paths)
@@ -1015,6 +1048,7 @@ async def run_cross_repo_analysis(
co_changes=co_changes,
package_deps=package_deps,
repo_summaries=repo_summaries,
+ total_co_changes=total_co_changes,
)
# Persist
diff --git a/packages/core/src/repowise/core/workspace/cycles.py b/packages/core/src/repowise/core/workspace/cycles.py
index 43144f052..2996873bb 100644
--- a/packages/core/src/repowise/core/workspace/cycles.py
+++ b/packages/core/src/repowise/core/workspace/cycles.py
@@ -37,7 +37,8 @@ _log = logging.getLogger("repowise.workspace.cycles")
#: Cap on the number of elementary cycles reported. Governance only needs the
#: representative loops, not every elementary cycle of a dense tangle; the true
-#: count is reported separately and truncation is logged (never silent).
+#: count is returned alongside the capped list so no caller can mistake the one
+#: for the other.
MAX_CYCLES = 50
@@ -111,23 +112,25 @@ def _cycle_edges(nodes: list[str], adjacency: dict[tuple[str, str], str]) -> lis
return edge_ids
-def detect_cycles(graph: SystemGraph) -> list[DependencyCycle]:
- """Return the elementary structural dependency cycles in *graph*.
+def detect_cycles(graph: SystemGraph) -> tuple[list[DependencyCycle], int]:
+ """Return the structural dependency cycles in *graph*, and how many exist.
Cycles are ordered shortest-first (the tightest loops are the most
- actionable), then lexicographically for stability. Capped at
- :data:`MAX_CYCLES`; truncation is logged. Returns ``[]`` when the structural
- subgraph is acyclic or NetworkX is unavailable.
+ actionable), then lexicographically for stability. The returned list is
+ capped at :data:`MAX_CYCLES`; the second element is the true count before
+ that cap, so a caller reporting "N cycles" cannot accidentally report the
+ cap instead. Returns ``([], 0)`` when the structural subgraph is acyclic or
+ NetworkX is unavailable.
"""
adjacency = _structural_adjacency(graph.edges)
if not adjacency:
- return []
+ return [], 0
try:
import networkx as nx
except Exception: # pragma: no cover - networkx is a hard dependency
_log.warning("networkx unavailable; skipping cycle detection", exc_info=True)
- return []
+ return [], 0
digraph = nx.DiGraph()
digraph.add_nodes_from(n.id for n in graph.nodes)
@@ -141,14 +144,15 @@ def detect_cycles(graph: SystemGraph) -> list[DependencyCycle]:
cycles.append(DependencyCycle(nodes=list(raw), edge_ids=edge_ids))
except Exception: # pragma: no cover - defensive
_log.warning("cycle enumeration failed", exc_info=True)
- return []
+ return [], 0
cycles.sort(key=lambda c: (c.length, c.nodes))
- if len(cycles) > MAX_CYCLES:
+ total = len(cycles)
+ if total > MAX_CYCLES:
_log.info(
"Cycle detection found %d cycles; reporting the %d shortest.",
- len(cycles),
+ total,
MAX_CYCLES,
)
cycles = cycles[:MAX_CYCLES]
- return cycles
+ return cycles, total
diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.py
index 34f8126a4..25c410d91 100644
--- a/packages/core/src/repowise/core/workspace/diagnostics.py
+++ b/packages/core/src/repowise/core/workspace/diagnostics.py
@@ -26,6 +26,7 @@ from repowise.core.workspace.contracts import (
ContractLink,
normalize_contract_id,
)
+from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX
# ---------------------------------------------------------------------------
# Constants (single source of truth)
@@ -68,6 +69,14 @@ class RepoDiagnostics:
consumers_by_type: dict[str, int] = field(default_factory=dict)
provider_count: int = 0
consumer_count: int = 0
+ #: Contracts by the tier that produced them — ``index`` (the parsed symbol
+ #: table) or ``regex`` (a text dialect). The regex share is where recall is
+ #: least certain, so it is worth seeing per repo.
+ providers_by_layer: dict[str, int] = field(default_factory=dict)
+ consumers_by_layer: dict[str, int] = field(default_factory=dict)
+ #: Calls that reached a confirmed HTTP wrapper but whose path could not be
+ #: resolved statically. Real endpoint calls, located and then not named.
+ http_consumers_unresolved: int = 0
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@@ -112,6 +121,28 @@ class ExtractionDiagnostics:
unmatched_consumers: list[UnmatchedConsumer] = field(default_factory=list)
unmatched_by_reason: dict[str, int] = field(default_factory=dict)
orphan_providers: list[OrphanProvider] = field(default_factory=list)
+ #: Workspace-wide rollups of the per-repo layer split.
+ providers_by_layer: dict[str, int] = field(default_factory=dict)
+ consumers_by_layer: dict[str, int] = field(default_factory=dict)
+ #: HTTP client calls located but not resolvable to an endpoint, workspace
+ #: wide. This is the only miss count extraction can actually observe.
+ http_consumers_unresolved: int = 0
+
+ @property
+ def http_consumer_coverage(self) -> float | None:
+ """Share of located HTTP client calls that became a contract.
+
+ ``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.
+ """
+ http_consumers = sum(
+ r.consumers_by_type.get("http", 0) for r in self.repo_breakdown
+ )
+ denominator = http_consumers + self.http_consumers_unresolved
+ if denominator == 0:
+ return None
+ return http_consumers / denominator
def to_dict(self) -> dict[str, Any]:
return {
@@ -123,6 +154,10 @@ class ExtractionDiagnostics:
"unmatched_consumers": [u.to_dict() for u in self.unmatched_consumers],
"unmatched_by_reason": self.unmatched_by_reason,
"orphan_providers": [o.to_dict() for o in self.orphan_providers],
+ "providers_by_layer": self.providers_by_layer,
+ "consumers_by_layer": self.consumers_by_layer,
+ "http_consumers_unresolved": self.http_consumers_unresolved,
+ "http_consumer_coverage": self.http_consumer_coverage,
}
@classmethod
@@ -139,6 +174,9 @@ class ExtractionDiagnostics:
consumers_by_type=r.get("consumers_by_type", {}),
provider_count=r.get("provider_count", 0),
consumer_count=r.get("consumer_count", 0),
+ providers_by_layer=r.get("providers_by_layer", {}),
+ consumers_by_layer=r.get("consumers_by_layer", {}),
+ http_consumers_unresolved=r.get("http_consumers_unresolved", 0),
)
for r in data.get("repo_breakdown", [])
],
@@ -162,6 +200,9 @@ class ExtractionDiagnostics:
)
for o in data.get("orphan_providers", [])
],
+ providers_by_layer=data.get("providers_by_layer", {}),
+ consumers_by_layer=data.get("consumers_by_layer", {}),
+ http_consumers_unresolved=data.get("http_consumers_unresolved", 0),
)
@@ -196,29 +237,44 @@ def _classify_unmatched(
def build_diagnostics(
contracts: list[Contract],
links: list[ContractLink],
+ extraction_stats: dict[str, dict[str, int]] | None = None,
) -> ExtractionDiagnostics:
"""Compute extraction diagnostics from contracts and matched links.
Pure and O(contracts + links). The reported orphan/unmatched lists let a
workspace owner see exactly which endpoints failed to connect and why,
rather than just a bare link total.
+
+ *extraction_stats* is :attr:`ContractStore.extraction_stats` — the counters
+ the extractors recorded for work they located but could not turn into a
+ contract. Omitting it costs the coverage figures, not the rest.
"""
+ stats_by_repo = extraction_stats or {}
providers = [c for c in contracts if c.role == "provider"]
consumers = [c for c in contracts if c.role == "consumer"]
# Per-repo breakdown ----------------------------------------------------
repos = sorted({c.repo for c in contracts})
breakdown: list[RepoDiagnostics] = []
+ prov_by_layer_all: dict[str, int] = defaultdict(int)
+ cons_by_layer_all: dict[str, int] = defaultdict(int)
for repo in repos:
prov_by_type: dict[str, int] = defaultdict(int)
cons_by_type: dict[str, int] = defaultdict(int)
+ prov_by_layer: dict[str, int] = defaultdict(int)
+ cons_by_layer: dict[str, int] = defaultdict(int)
for c in contracts:
if c.repo != repo:
continue
+ layer = str(c.meta.get(EXTRACTION_LAYER_KEY, LAYER_REGEX))
if c.role == "provider":
prov_by_type[c.contract_type] += 1
+ prov_by_layer[layer] += 1
+ prov_by_layer_all[layer] += 1
elif c.role == "consumer":
cons_by_type[c.contract_type] += 1
+ cons_by_layer[layer] += 1
+ cons_by_layer_all[layer] += 1
breakdown.append(
RepoDiagnostics(
repo=repo,
@@ -226,6 +282,11 @@ def build_diagnostics(
consumers_by_type=dict(sorted(cons_by_type.items())),
provider_count=sum(prov_by_type.values()),
consumer_count=sum(cons_by_type.values()),
+ providers_by_layer=dict(sorted(prov_by_layer.items())),
+ consumers_by_layer=dict(sorted(cons_by_layer.items())),
+ http_consumers_unresolved=stats_by_repo.get(repo, {}).get(
+ "http_consumer_unresolved", 0
+ ),
)
)
@@ -286,4 +347,12 @@ def build_diagnostics(
unmatched_consumers=unmatched,
unmatched_by_reason=dict(sorted(by_reason.items())),
orphan_providers=orphans,
+ providers_by_layer=dict(sorted(prov_by_layer_all.items())),
+ consumers_by_layer=dict(sorted(cons_by_layer_all.items())),
+ # Summed from the stats, not from the per-repo breakdown: a repo whose
+ # every call went unresolved has no contracts and so no breakdown row,
+ # and it is exactly the repo whose misses matter most.
+ http_consumers_unresolved=sum(
+ s.get("http_consumer_unresolved", 0) for s in stats_by_repo.values()
+ ),
)
diff --git a/packages/core/src/repowise/core/workspace/system_graph.py b/packages/core/src/repowise/core/workspace/system_graph.py
index 2b5eeadf0..04381c827 100644
--- a/packages/core/src/repowise/core/workspace/system_graph.py
+++ b/packages/core/src/repowise/core/workspace/system_graph.py
@@ -487,7 +487,9 @@ async def run_system_graph_build(
_detect_boundaries_by_repo, ws_config, workspace_root
)
- diagnostics = build_diagnostics(store.contracts, store.contract_links)
+ diagnostics = build_diagnostics(
+ store.contracts, store.contract_links, store.extraction_stats
+ )
graph = build_system_graph(
store.contracts,
store.contract_links,
diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.py
index af66e7ab6..ad3831450 100644
--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py
@@ -26,6 +26,7 @@ class CrossRepoEnricher:
conformance_path: Path | None = None,
) -> None:
self._co_changes: list[dict] = []
+ self._total_co_changes: int = 0
self._package_deps: list[dict] = []
self._repo_summaries: dict[str, dict] = {}
@@ -94,6 +95,9 @@ class CrossRepoEnricher:
return
self._co_changes = data.get("co_changes", [])
+ # How many pairs the miner found before its own caps trimmed the list
+ # above. Equal to len(self._co_changes) when nothing was dropped.
+ self._total_co_changes = data.get("total_co_changes", len(self._co_changes))
self._package_deps = data.get("package_deps", [])
self._repo_summaries = data.get("repo_summaries", {})
@@ -250,6 +254,7 @@ class CrossRepoEnricher:
"""
# Reset all state
self._co_changes = []
+ self._total_co_changes = 0
self._package_deps = []
self._repo_summaries = {}
self._co_change_index = defaultdict(list)
@@ -303,8 +308,13 @@ class CrossRepoEnricher:
@property
def has_breaking_changes(self) -> bool:
- """True if a breaking-change report has been loaded."""
- return self._breaking_changes is not None
+ """True if a breaking-change report has been loaded *and* it ran.
+
+ A report with no ``generated_at`` was never written a result, so its
+ empty change list is silence rather than an all-clear. Callers that
+ report findings must not present it as one.
+ """
+ return bool(self._breaking_changes) and bool(self._breaking_changes.get("generated_at"))
def get_breaking_changes(self) -> dict | None:
"""Return the raw breaking-change report (changes + rollups)."""
@@ -316,8 +326,12 @@ class CrossRepoEnricher:
@property
def has_conformance(self) -> bool:
- """True if a conformance report has been loaded."""
- return self._conformance is not None
+ """True if a conformance report has been loaded *and* it ran.
+
+ See :attr:`has_breaking_changes`: an unstamped report's zero findings
+ mean nothing looked, not that nothing was found.
+ """
+ return bool(self._conformance) and bool(self._conformance.get("generated_at"))
def get_conformance(self) -> dict | None:
"""Return the raw conformance report (violations + cycles + rollups)."""
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 723957c22..235892421 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_conformance.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
@@ -51,20 +51,38 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:
"_meta": _build_meta(),
}
+ # A report with no timestamp is one nothing ever wrote a result into. Its
+ # zeros are the absence of a check, not the absence of findings, and an
+ # agent told "no violations" would act on that.
+ ran = bool(report.get("generated_at"))
+ if not ran:
+ return {
+ "error": (
+ "The conformance check has not run for this workspace. Its stored "
+ "report has no result in it, so its zero counts mean nothing. Run "
+ "`repowise update --workspace` to produce one."
+ ),
+ "_meta": _build_meta(),
+ }
+
if repo:
scoped = enricher.get_conformance_for_repo(repo)
violations = scoped["violations"]
cycles = scoped["cycles"]
+ # Scoping picks from the already-capped stored list, so the pre-cap
+ # workspace total does not describe this subset.
+ total_cycles = len(cycles)
else:
violations = report.get("violations", [])
cycles = report.get("cycles", [])
+ total_cycles = report.get("total_cycles", len(cycles))
shown_violations = violations[:_MCP_VIOLATION_LIMIT]
shown_cycles = cycles[:_MCP_CYCLE_LIMIT]
if violations or cycles:
summary = (
- f"{len(violations)} architecture rule violation(s) and {len(cycles)} "
+ 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("rules_evaluated", 0):
@@ -81,7 +99,11 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:
"cycles": shown_cycles,
"cycles_truncated": max(0, len(cycles) - len(shown_cycles)),
"violation_count": len(violations),
+ # ``cycle_count`` is what this response lists; ``total_cycles`` is how
+ # many the workspace has, which the stored report may itself have cut.
"cycle_count": len(cycles),
+ "total_cycles": total_cycles,
+ "checked_at": report.get("generated_at"),
"summary": summary,
"_meta": _build_meta(),
}
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 9d99c044f..8cc5cd1da 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -350,9 +350,10 @@ async def get_co_changes(
_require_workspace(ws_config)
if enricher is None:
- return WorkspaceCoChangesResponse(co_changes=[], total=0)
+ return WorkspaceCoChangesResponse(co_changes=[], total=0, total_mined=0)
co_changes = list(getattr(enricher, "_co_changes", []))
+ total_mined = getattr(enricher, "_total_co_changes", len(co_changes))
if repo:
co_changes = [
@@ -383,6 +384,7 @@ async def get_co_changes(
for cc in co_changes
],
total=total,
+ total_mined=total_mined,
)
@@ -624,7 +626,7 @@ async def get_breaking_changes(
)
return WorkspaceBreakingChangesResponse(
version=report.get("version", 1),
- generated_at=report.get("generated_at", ""),
+ generated_at=report.get("generated_at") or None,
changes=changes,
total=len(changes),
breaking_count=sum(1 for c in changes if c.get("severity") == "breaking"),
@@ -664,7 +666,15 @@ async def get_conformance(
return WorkspaceConformanceResponse()
if not repo:
- return WorkspaceConformanceResponse(**report)
+ # An artifact written before cycle totals were recorded has no
+ # total_cycles key; falling back to the listed count is better than
+ # letting the model default report zero cycles alongside a non-zero list.
+ return WorkspaceConformanceResponse(
+ **{
+ **report,
+ "total_cycles": report.get("total_cycles", len(report.get("cycles", []))),
+ }
+ )
# Narrow to findings that involve the repo, recomputing rollups so the
# response stays self-consistent.
@@ -677,12 +687,15 @@ async def get_conformance(
)
return WorkspaceConformanceResponse(
version=report.get("version", 1),
- generated_at=report.get("generated_at", ""),
+ generated_at=report.get("generated_at") or None,
rules_evaluated=report.get("rules_evaluated", 0),
violations=violations,
cycles=cycles,
violation_count=len(violations),
cycle_count=len(cycles),
+ # The unscoped total, not the scoped count: how many cycles the
+ # workspace has does not change because the view was narrowed.
+ total_cycles=report.get("total_cycles", len(report.get("cycles", []))),
violating_repos=violating_repos,
)
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 39ae6af3a..1937ee04d 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -119,7 +119,13 @@ class WorkspaceCoChangeEntry(BaseModel):
class WorkspaceCoChangesResponse(BaseModel):
co_changes: list[WorkspaceCoChangeEntry]
+ #: Pairs matching the query, before ``limit`` paged them.
total: int
+ #: Pairs the miner scored before its edge caps trimmed the stored overlay.
+ #: Larger than ``total`` means the artifact itself is a sample. Not a count
+ #: of every pair in git history — each session's file list is bounded
+ #: before pairing.
+ total_mined: int = 0
class WorkspaceGraphNode(BaseModel):
@@ -183,6 +189,9 @@ class WorkspaceRepoDiagnostics(BaseModel):
consumers_by_type: dict[str, int] = {}
provider_count: int = 0
consumer_count: int = 0
+ providers_by_layer: dict[str, int] = {}
+ consumers_by_layer: dict[str, int] = {}
+ http_consumers_unresolved: int = 0
class WorkspaceUnmatchedConsumer(BaseModel):
@@ -209,6 +218,12 @@ class WorkspaceExtractionDiagnostics(BaseModel):
unmatched_consumers: list[WorkspaceUnmatchedConsumer] = []
unmatched_by_reason: dict[str, int] = {}
orphan_providers: list[WorkspaceOrphanProvider] = []
+ 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%.
+ http_consumer_coverage: float | None = None
class WorkspaceSystemGraphResponse(BaseModel):
@@ -283,7 +298,9 @@ class WorkspaceBreakingChange(BaseModel):
class WorkspaceBreakingChangesResponse(BaseModel):
version: int = 1
- generated_at: str = ""
+ #: ``None`` when detection has not run. An empty ``changes`` list means
+ #: "nothing broke" only when this is set.
+ generated_at: str | None = None
changes: list[WorkspaceBreakingChange] = []
total: int = 0
breaking_count: int = 0
@@ -320,12 +337,17 @@ class WorkspaceDependencyCycle(BaseModel):
class WorkspaceConformanceResponse(BaseModel):
version: int = 1
- generated_at: str = ""
+ #: ``None`` when the check has not run. Zero violations means "clean" only
+ #: when this is set.
+ generated_at: str | None = None
rules_evaluated: int = 0
violations: list[WorkspaceConformanceViolation] = []
cycles: list[WorkspaceDependencyCycle] = []
violation_count: int = 0
+ #: ``cycle_count`` is how many cycles are listed; ``total_cycles`` is how
+ #: many exist. They differ when MAX_CYCLES truncated the list.
cycle_count: int = 0
+ total_cycles: int = 0
violating_repos: list[str] = []
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index a890d4637..033888c4e 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -141,6 +141,11 @@ export interface RepoDiagnostics {
consumers_by_type: Record<string, number>;
provider_count: number;
consumer_count: number;
+ /** Contracts by the tier that produced them: `index` or `regex`. */
+ providers_by_layer: Record<string, number>;
+ consumers_by_layer: Record<string, number>;
+ /** Calls that reached a confirmed HTTP wrapper but resolved to no path. */
+ http_consumers_unresolved: number;
}
export interface UnmatchedConsumer {
@@ -167,6 +172,17 @@ export interface ExtractionDiagnostics {
unmatched_consumers: UnmatchedConsumer[];
unmatched_by_reason: Record<string, number>;
orphan_providers: OrphanProvider[];
+ /** Workspace-wide rollup of the per-repo `index` / `regex` split. */
+ providers_by_layer: Record<string, number>;
+ consumers_by_layer: Record<string, number>;
+ /** 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.
+ */
+ http_consumer_coverage: number | null;
}
// ---------------------------------------------------------------------------
@@ -280,7 +296,11 @@ export interface BreakingChange {
export interface BreakingChangeReport {
version: number;
- generated_at: string;
+ /**
+ * When detection ran, or `null` if it never has. An empty `changes` list
+ * means "nothing broke" only when this is set.
+ */
+ generated_at: string | null;
changes: BreakingChange[];
total: number;
breaking_count: number;
@@ -343,13 +363,20 @@ export interface DependencyCycle {
export interface ConformanceReport {
version: number;
- generated_at: string;
+ /**
+ * When the check ran, or `null` if it never has. Zero violations means
+ * "clean" only when this is set — otherwise nothing looked.
+ */
+ generated_at: string | null;
/** How many rules were declared and evaluated. */
rules_evaluated: number;
violations: ConformanceViolation[];
cycles: DependencyCycle[];
violation_count: number;
+ /** How many cycles `cycles` lists, after the reporting cap. */
cycle_count: number;
+ /** How many cycles exist. Above `cycle_count` when the list was cut. */
+ total_cycles: number;
/** Distinct repos participating in a violation. */
violating_repos: string[];
}
diff --git a/packages/ui/__tests__/workspace/dsm.test.tsx b/packages/ui/__tests__/workspace/dsm.test.tsx
index ac56fb8b2..7252cd21d 100644
--- a/packages/ui/__tests__/workspace/dsm.test.tsx
+++ b/packages/ui/__tests__/workspace/dsm.test.tsx
@@ -88,6 +88,7 @@ function report(over: Partial<ConformanceReport> = {}): ConformanceReport {
cycles,
violation_count: violations.length,
cycle_count: cycles.length,
+ total_cycles: cycles.length,
violating_repos: [],
...over,
};
diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.ts
index e226135f4..c858a4e2d 100644
--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts
+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts
@@ -365,6 +365,7 @@ function conformanceReport(over: Partial<ConformanceReport> = {}): ConformanceRe
cycles,
violation_count: violations.length,
cycle_count: cycles.length,
+ total_cycles: cycles.length,
violating_repos: [],
...over,
};
diff --git a/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx b/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx
index ec79b5935..79b5db046 100644
--- a/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-breaking-panel.tsx
@@ -171,13 +171,19 @@ export function SystemMapBreakingPanel({
<div style={{ color: "var(--color-text-tertiary)", fontSize: 11 }}>
{loading
? "Checking the latest update…"
- : `${report.breaking_count} breaking, ${report.warning_count} warning across ${report.impacted_repos.length} repo(s)`}
+ : !report.generated_at
+ ? "Not yet checked"
+ : `${report.breaking_count} breaking, ${report.warning_count} warning across ${report.impacted_repos.length} repo(s)`}
</div>
</div>
{!loading && report.changes.length === 0 && (
<div style={{ padding: "12px", color: "var(--color-text-tertiary)" }}>
- No breaking changes in the most recent update.
+ {/* No timestamp means detection never wrote a result here, so an
+ empty change list is silence rather than an all-clear. */}
+ {!report.generated_at
+ ? "Breaking-change detection has not run for this workspace. Run a workspace update to produce a result."
+ : "No breaking changes in the most recent update."}
</div>
)}
diff --git a/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx b/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx
index d46200924..02ca165a3 100644
--- a/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx
@@ -172,6 +172,14 @@ export function SystemMapConformancePanel({
}: SystemMapConformancePanelProps) {
if (!report) return null;
+ // The report lists at most MAX_CYCLES; total_cycles is how many exist. Say
+ // so when they differ rather than passing the cap off as the count.
+ const totalCycles = report.total_cycles ?? report.cycle_count;
+ const cycleSummary =
+ totalCycles > report.cycle_count
+ ? `${report.cycle_count} of ${totalCycles} cycle(s)`
+ : `${report.cycle_count} cycle(s)`;
+
return (
<div style={panelStyle}>
<div
@@ -211,7 +219,9 @@ export function SystemMapConformancePanel({
<div style={{ color: "var(--color-text-tertiary)", fontSize: 11 }}>
{loading
? "Checking the latest update…"
- : `${report.violation_count} violation(s), ${report.cycle_count} cycle(s) from ${report.rules_evaluated} rule(s)`}
+ : !report.generated_at
+ ? "Not yet checked"
+ : `${report.violation_count} violation(s), ${cycleSummary} from ${report.rules_evaluated} rule(s)`}
</div>
</div>
@@ -226,9 +236,14 @@ export function SystemMapConformancePanel({
}}
>
<RefreshCw size={12} />
- {report.rules_evaluated > 0
- ? "No rule violations or dependency cycles."
- : "No dependency cycles. Declare conformance rules to enforce allowed dependencies."}
+ {/* An unstamped report is one the checker never wrote a result into.
+ Reporting its zeros as "no violations" is the failure this panel
+ exists to avoid. */}
+ {!report.generated_at
+ ? "This workspace has not been checked. Run a workspace update to produce a result."
+ : report.rules_evaluated > 0
+ ? "No rule violations or dependency cycles."
+ : "No dependency cycles. Declare conformance rules to enforce allowed dependencies."}
</div>
)}
diff --git a/packages/ui/src/workspace/system-map/system-map-inspector.tsx b/packages/ui/src/workspace/system-map/system-map-inspector.tsx
index efb1c9f63..a41ad0d03 100644
--- a/packages/ui/src/workspace/system-map/system-map-inspector.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-inspector.tsx
@@ -211,7 +211,13 @@ function EdgeBody({
{edge.contract_refs.length > 0 && (
<div>
<div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase", color: "var(--color-text-tertiary)", marginBottom: 3 }}>
- Evidence ({edge.contract_refs.length})
+ {/* Back-pointers are capped per edge while `weight` counts every
+ contributor, so the two numbers diverge silently once an edge
+ is busy enough. Name the cap instead of showing two figures
+ the reader has to reconcile. */}
+ {edge.weight > edge.contract_refs.length
+ ? `Evidence (${edge.contract_refs.length} of ${edge.weight})`
+ : `Evidence (${edge.contract_refs.length})`}
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
{edge.contract_refs.map((ref) => (
diff --git a/packages/web/src/app/workspace/co-changes/page.tsx b/packages/web/src/app/workspace/co-changes/page.tsx
index 559cf4bf8..5c20eb19d 100644
--- a/packages/web/src/app/workspace/co-changes/page.tsx
+++ b/packages/web/src/app/workspace/co-changes/page.tsx
@@ -48,6 +48,9 @@ export default async function CoChangesPage({ searchParams }: Props) {
const res = await Promise.allSettled([getWorkspaceCoChanges({ limit: ROW_LIMIT })]);
const data = res[0].status === "fulfilled" ? res[0].value : null;
const coChanges = data?.co_changes ?? [];
+ // What the miner found before its own caps trimmed the artifact. Above
+ // coChanges.length means this page is the top of a longer list.
+ const totalMined = data?.total_mined ?? coChanges.length;
const repoPairs = summarisePairs(coChanges);
const selected = pair && repoPairs.some((p) => p.id === pair) ? pair : null;
@@ -70,7 +73,10 @@ export default async function CoChangesPage({ searchParams }: Props) {
{
label: "File pairs",
value: coChanges.length > 0 ? formatNumber(coChanges.length) : "—",
- sub: "capped per repository pair by the miner",
+ sub:
+ totalMined > coChanges.length
+ ? `of ${formatNumber(totalMined)} found; capped by the miner`
+ : "every pair the miner found",
},
{
label: "Strongest pair",
@@ -132,9 +138,17 @@ export default async function CoChangesPage({ searchParams }: Props) {
<p>
Strength is the share of the less-active file&rsquo;s recent sessions that also touched
its partner. This is a work-pattern signal from git history, not a declared or verified
- dependency, so it is a place to start looking rather than proof of coupling. The miner
- keeps only the strongest file pairs for each repository pair, so this is the top of the
- list rather than all of it.
+ dependency, so it is a place to start looking rather than proof of coupling.
+ {totalMined > coChanges.length ? (
+ <>
+ {" "}
+ The miner found {formatNumber(totalMined)} qualifying file pairs and kept the
+ strongest {formatNumber(coChanges.length)}, so this is the top of the list rather
+ than all of it.
+ </>
+ ) : (
+ " Every pair the miner found is shown."
+ )}
</p>
</PageLede>
diff --git a/packages/web/src/app/workspace/conformance/page.tsx b/packages/web/src/app/workspace/conformance/page.tsx
index bf1877278..32f13dbd2 100644
--- a/packages/web/src/app/workspace/conformance/page.tsx
+++ b/packages/web/src/app/workspace/conformance/page.tsx
@@ -36,17 +36,14 @@ const DSM_DESCRIPTION =
/**
* Whether the conformance analyser has ever produced this report.
*
- * The artifact is written with `generated_at: ""` and every count at zero
- * before anything runs, which is indistinguishable from a clean pass unless
- * this is checked — and a clean pass is what the page used to show. Three
- * states have to stay separate: never ran, ran with no rules to check, and ran
+ * A report with no `generated_at` was never written a result, and its zero
+ * counts are the absence of a check rather than a clean pass. Three states
+ * have to stay separate: never ran, ran with no rules to check, and ran
* against real rules.
*
- * Reads only fields already on the wire. Phase 4 of the workspace overhaul
- * replaces the empty string with a proper null and adds the same distinction
- * to the CLI and the artifact; this is the frontend half, and it should follow
- * that contract when it lands rather than keeping the empty-string check
- * forever.
+ * `generated_at` is now `string | null`, and the checker stamps it whenever it
+ * runs. Artifacts written before that carry `""`, which the loader maps to
+ * null, so the falsy check covers both.
*/
function reportState(
report: ConformanceReport | null,
diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsx
index de44f58bd..76d066a6f 100644
--- a/packages/web/src/app/workspace/contracts/page.tsx
+++ b/packages/web/src/app/workspace/contracts/page.tsx
@@ -92,6 +92,19 @@ export default async function ContractsPage({ searchParams }: Props) {
value: diagnostics ? formatNumber(diagnostics.orphan_providers.length) : "—",
sub: "nothing in the workspace calls them",
},
+ {
+ // Extraction reporting on its own recall. The denominator is calls a
+ // dialect located, so this is honest about what it covers and silent
+ // about calls nothing recognised — it is not total recall.
+ label: "HTTP calls resolved",
+ value:
+ diagnostics?.http_consumer_coverage != null
+ ? `${Math.floor(diagnostics.http_consumer_coverage * 100)}%`
+ : "—",
+ sub: diagnostics?.http_consumers_unresolved
+ ? `${formatNumber(diagnostics.http_consumers_unresolved)} located but not resolvable`
+ : "of the client calls extraction located",
+ },
];
return (
@@ -117,9 +130,17 @@ export default async function ContractsPage({ searchParams }: Props) {
</p>
<p>
{formatNumber(diagnostics.orphan_providers.length)} providers have no caller in
- this workspace. Read that against the consumer count rather than on its own: an
- endpoint looks unused both when nothing calls it and when the call was written in
- a form this analysis could not follow, and those two are not separated yet.
+ this workspace. Read that against extraction&rsquo;s own coverage rather than on
+ its own: an endpoint looks unused both when nothing calls it and when the call
+ was written in a form this analysis could not follow.
+ {diagnostics.http_consumers_unresolved > 0 ? (
+ <>
+ {" "}
+ {formatNumber(diagnostics.http_consumers_unresolved)} HTTP client calls were
+ located here but could not be resolved to an endpoint, so some of those
+ providers are called by code this page cannot yet name.
+ </>
+ ) : null}
</p>
</>
) : (
diff --git a/tests/unit/server/test_mcp_conformance.py b/tests/unit/server/test_mcp_conformance.py
index e82d60b3a..10cd4315f 100644
--- a/tests/unit/server/test_mcp_conformance.py
+++ b/tests/unit/server/test_mcp_conformance.py
@@ -162,3 +162,66 @@ def test_conformance_directive_empty_outside_workspace():
assert _conformance_directive("frontend") == ([], [])
finally:
_state._registry = prev
+
+
+async def test_unstamped_report_is_an_error_not_an_all_clear(tmp_path: Path):
+ """A report nothing wrote a result into has zero violations, and saying so
+ would tell an agent the architecture is clean when nothing checked it."""
+ report = build_conformance_report(_graph(), [], generated_at="t").to_dict()
+ report["generated_at"] = ""
+ report["violations"] = []
+ report["cycles"] = []
+ (tmp_path / "conformance.json").write_text(json.dumps(report), encoding="utf-8")
+
+ prev_registry = _state._registry
+ prev_enricher = _state._cross_repo_enricher
+ _state._registry = object()
+ _state._cross_repo_enricher = CrossRepoEnricher(
+ tmp_path / "cross_repo_edges.json",
+ conformance_path=tmp_path / "conformance.json",
+ )
+ try:
+ result = await get_conformance()
+ finally:
+ _state._registry = prev_registry
+ _state._cross_repo_enricher = prev_enricher
+
+ assert "error" in result
+ assert "has not run" in result["error"]
+ assert "violation_count" not in result
+
+
+async def test_reports_the_true_cycle_total_and_when_it_checked(workspace_state):
+ result = await get_conformance()
+ assert result["total_cycles"] == result["cycle_count"]
+ assert result["checked_at"] == "t"
+
+
+def test_conformance_directive_ignores_an_unstamped_report(tmp_path: Path):
+ """get_risk's PR directive must not report "no violations" from a report
+ nothing ever wrote a result into — it would read as an architecture pass."""
+ from repowise.server.mcp_server.tool_risk import _conformance_directive
+
+ report = build_conformance_report(
+ _graph(), [ConformanceRule(source="frontend", target="db")], generated_at="t"
+ ).to_dict()
+ report["generated_at"] = ""
+ (tmp_path / "conformance.json").write_text(json.dumps(report), encoding="utf-8")
+ enricher = CrossRepoEnricher(
+ tmp_path / "cross_repo_edges.json",
+ conformance_path=tmp_path / "conformance.json",
+ )
+ assert enricher.get_conformance() is not None, "the report is loaded..."
+ assert not enricher.has_conformance, "...but it did not run, so it is not evidence"
+
+ prev_registry = _state._registry
+ prev_enricher = _state._cross_repo_enricher
+ _state._registry = object()
+ _state._cross_repo_enricher = enricher
+ try:
+ assert _conformance_directive("frontend") == ([], [])
+ finally:
+ _state._registry = prev_registry
+ _state._cross_repo_enricher = prev_enricher
diff --git a/tests/unit/workspace/test_breaking_change.py b/tests/unit/workspace/test_breaking_change.py
index 14cf01131..c287cf3ac 100644
--- a/tests/unit/workspace/test_breaking_change.py
+++ b/tests/unit/workspace/test_breaking_change.py
@@ -287,3 +287,30 @@ def test_load_missing_report_returns_none(tmp_path):
def test_save_returns_path(tmp_path):
out = save_breaking_change_report(BreakingChangeReport(), tmp_path)
assert out.name == "breaking_changes.json"
+
+
+# ---------------------------------------------------------------------------
+# Never-ran vs found-nothing
+# ---------------------------------------------------------------------------
+
+
+def test_detection_stamps_its_own_report():
+ """Before this, run_breaking_change_detection never passed a timestamp, so
+ every persisted report claimed to have never run."""
+ report = detect_breaking_changes(ContractStore(), ContractStore())
+ assert report.ran
+ assert report.to_dict()["generated_at"]
+
+
+def test_an_unbuilt_report_is_not_a_clean_one():
+ report = BreakingChangeReport()
+ assert not report.ran
+ assert report.generated_at is None
+ assert not report.has_changes
+ assert report.to_dict()["generated_at"] is None
+
+
+def test_legacy_empty_string_stamp_reads_as_never_ran():
+ restored = BreakingChangeReport.from_dict({"generated_at": "", "changes": []})
+ assert restored.generated_at is None
+ assert not restored.ran
diff --git a/tests/unit/workspace/test_config.py b/tests/unit/workspace/test_config.py
index c2620e83c..cc506846b 100644
--- a/tests/unit/workspace/test_config.py
+++ b/tests/unit/workspace/test_config.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import logging
from pathlib import Path
import pytest
@@ -305,3 +306,41 @@ class TestFindWorkspaceRoot:
deep = ws / "repo" / "src" / "pkg"
deep.mkdir(parents=True)
assert find_workspace_root(deep) == ws.resolve()
+
+
+# ---------------------------------------------------------------------------
+# Losing a repo must leave a trace
+# ---------------------------------------------------------------------------
+
+
+def test_save_warns_when_it_drops_a_repo(tmp_path, caplog):
+ """A config rewrite that shrinks the workspace is exactly what went
+ unexplained once, and it left nothing behind to explain it."""
+ WorkspaceConfig(
+ repos=[RepoEntry(path="a", alias="a"), RepoEntry(path="b", alias="b")]
+ ).save(tmp_path)
+
+ with caplog.at_level(logging.WARNING, logger="repowise.workspace.config"):
+ WorkspaceConfig(repos=[RepoEntry(path="a", alias="a")]).save(tmp_path)
+
+ assert "down from 2" in caplog.text
+ assert "dropping: b" in caplog.text
+ # The write still happens — a removal may be intended.
+ assert WorkspaceConfig.load(tmp_path).repo_aliases() == ["a"]
+
+
+def test_save_is_quiet_when_adding_a_repo(tmp_path, caplog):
+ WorkspaceConfig(repos=[RepoEntry(path="a", alias="a")]).save(tmp_path)
+
+ with caplog.at_level(logging.WARNING, logger="repowise.workspace.config"):
+ WorkspaceConfig(
+ repos=[RepoEntry(path="a", alias="a"), RepoEntry(path="b", alias="b")]
+ ).save(tmp_path)
+
+ assert caplog.text == ""
+
+
+def test_first_save_does_not_warn(tmp_path, caplog):
+ with caplog.at_level(logging.WARNING, logger="repowise.workspace.config"):
+ WorkspaceConfig(repos=[RepoEntry(path="a", alias="a")]).save(tmp_path)
+ assert caplog.text == ""
diff --git a/tests/unit/workspace/test_conformance.py b/tests/unit/workspace/test_conformance.py
index 686e31aaa..d0a3f1a18 100644
--- a/tests/unit/workspace/test_conformance.py
+++ b/tests/unit/workspace/test_conformance.py
@@ -8,6 +8,7 @@ exception must suppress an otherwise-denied edge.
from __future__ import annotations
from pathlib import Path
+from unittest.mock import patch
from repowise.core.workspace.config import (
ConformanceConfig,
@@ -177,8 +178,9 @@ def test_two_node_cycle():
[_node("a"), _node("b")],
[_edge("a", "b"), _edge("b", "a")],
)
- cycles = detect_cycles(g)
+ cycles, total = detect_cycles(g)
assert len(cycles) == 1
+ assert total == 1
assert set(cycles[0].nodes) == {"a", "b"}
assert len(cycles[0].edge_ids) == 2
@@ -188,8 +190,9 @@ def test_longer_cycle():
[_node("a"), _node("b"), _node("c")],
[_edge("a", "b"), _edge("b", "c"), _edge("c", "a")],
)
- cycles = detect_cycles(g)
+ cycles, total = detect_cycles(g)
assert len(cycles) == 1
+ assert total == 1
assert set(cycles[0].nodes) == {"a", "b", "c"}
assert cycles[0].length == 3
@@ -199,7 +202,7 @@ def test_acyclic_graph_has_no_cycles():
[_node("a"), _node("b"), _node("c")],
[_edge("a", "b"), _edge("b", "c")],
)
- assert detect_cycles(g) == []
+ assert detect_cycles(g) == ([], 0)
def test_cycles_ignore_behavioral_edges():
@@ -208,7 +211,7 @@ def test_cycles_ignore_behavioral_edges():
[_node("a"), _node("b")],
[_edge("a", "b"), _edge("b", "a", kind="co_change", structural=False)],
)
- assert detect_cycles(g) == []
+ assert detect_cycles(g) == ([], 0)
# ---------------------------------------------------------------------------
@@ -312,3 +315,50 @@ def test_run_conformance_check_persists(tmp_path: Path):
# persisted
loaded = load_conformance_report(tmp_path)
assert loaded is not None and len(loaded.violations) == 1
+
+
+# ---------------------------------------------------------------------------
+# Never-ran vs found-nothing
+# ---------------------------------------------------------------------------
+
+
+def test_building_a_report_stamps_it():
+ """Producing a report is running the check. Before this, run_conformance_check
+ left generated_at empty on every run, so a real all-clear was
+ indistinguishable from a check that never happened."""
+ g = _graph([_node("a"), _node("b")], [_edge("a", "b")])
+ report = build_conformance_report(g, [])
+ assert report.ran
+ assert report.generated_at
+ assert report.to_dict()["generated_at"]
+
+
+def test_an_unbuilt_report_is_not_a_clean_one():
+ report = ConformanceReport()
+ assert not report.ran
+ assert report.generated_at is None
+ assert not report.has_findings # zero findings...
+ # ...but the zero is meaningless, and the artifact says so.
+ assert report.to_dict()["generated_at"] is None
+
+
+def test_legacy_empty_string_stamp_reads_as_never_ran():
+ """Artifacts written before the check was clocked carry "". They cannot be
+ told apart from never-ran, so they must not read as a pass."""
+ restored = ConformanceReport.from_dict({"generated_at": "", "rules_evaluated": 3})
+ assert restored.generated_at is None
+ assert not restored.ran
+
+
+def test_report_carries_the_true_cycle_count_past_the_cap():
+ import repowise.core.workspace.cycles as cy
+
+ nodes = [_node(n) for n in "abcd"]
+ # Every ordered pair, so there are far more elementary cycles than the cap.
+ edges = [_edge(s, t) for s in "abcd" for t in "abcd" if s != t]
+ g = _graph(nodes, edges)
+ with patch.object(cy, "MAX_CYCLES", 2):
+ report = build_conformance_report(g, [])
+ assert len(report.cycles) == 2
+ assert report.total_cycles > 2
+ assert report.to_dict()["total_cycles"] == report.total_cycles
diff --git a/tests/unit/workspace/test_cross_repo.py b/tests/unit/workspace/test_cross_repo.py
index a63b3d7f7..f4accdfb2 100644
--- a/tests/unit/workspace/test_cross_repo.py
+++ b/tests/unit/workspace/test_cross_repo.py
@@ -112,7 +112,9 @@ class TestCrossRepoCoChanges:
return []
with patch("repowise.core.workspace.cross_repo._parse_git_log", side_effect=fake_parse):
- return detect_cross_repo_co_changes(repo_paths, **kwargs)
+ # [0] is the capped list; the pre-cap total is asserted separately
+ # in TestCoChangeTruncationTotals.
+ return detect_cross_repo_co_changes(repo_paths, **kwargs)[0]
def test_same_author_within_window(self) -> None:
"""Two repos, same author, commits <24h apart → edges found."""
@@ -408,6 +410,67 @@ class TestCrossRepoCoChanges:
assert len(ac_edges) == 1, "weaker pair still present"
+class TestCoChangeTruncationTotals:
+ """The caps must report what they dropped, not just drop it."""
+
+ def _detect(self, repo_commits, **kwargs):
+ repo_paths = {alias: Path(f"/fake/{alias}") for alias in repo_commits}
+
+ def fake_parse(repo_path, commit_limit=500):
+ for alias, path in repo_paths.items():
+ if str(repo_path) == str(path):
+ return repo_commits[alias]
+ return []
+
+ with patch("repowise.core.workspace.cross_repo._parse_git_log", side_effect=fake_parse):
+ return detect_cross_repo_co_changes(repo_paths, **kwargs)
+
+ def test_total_exceeds_returned_list_when_capped(self) -> None:
+ """The pre-cap count survives the per-pair cap that dropped the rest."""
+ now = int(time.time())
+ day = 86400
+ commits_a = [
+ ("[email protected]", now - (i * 2) * day, [f"a{i}.py", f"b{i}.py", f"c{i}.py"])
+ for i in range(6)
+ ]
+ commits_b = [
+ ("[email protected]", now - (i * 2) * day + 60, [f"p{i}.ts", f"q{i}.ts", f"r{i}.ts"])
+ for i in range(6)
+ ]
+ import repowise.core.workspace.cross_repo as cr
+
+ with patch.object(cr, "_MAX_EDGES_PER_REPO_PAIR", 3):
+ results, total = self._detect(
+ {"a": _make_commits("a", commits_a), "b": _make_commits("b", commits_b)},
+ min_score=0.0,
+ min_sessions=1,
+ )
+ assert len(results) == 3, "list is capped"
+ assert total > 3, "the true count survived the cap"
+
+ def test_total_equals_list_when_nothing_dropped(self) -> None:
+ """An uncapped run must not inflate its own total."""
+ now = int(time.time())
+ results, total = self._detect(
+ {
+ "backend": _make_commits(
+ "backend", [("[email protected]", now - 3600, ["src/api.py"])]
+ ),
+ "frontend": _make_commits(
+ "frontend", [("[email protected]", now - 7200, ["src/client.ts"])]
+ ),
+ },
+ min_score=0.0,
+ min_sessions=1,
+ )
+ assert total == len(results)
+
+ def test_single_repo_returns_a_pair_not_a_bare_list(self) -> None:
+ """Every exit returns (list, total) — an early return that forgot the
+ total would raise on unpack, which is how one was found."""
+ assert self._detect({"solo": _make_commits("solo", [])}) == ([], 0)
+
+
# ---------------------------------------------------------------------------
# Noise-file filtering
# ---------------------------------------------------------------------------
@@ -475,7 +538,9 @@ class TestCrossRepoNoiseFiltering:
return []
with patch("repowise.core.workspace.cross_repo._parse_git_log", side_effect=fake_parse):
- return detect_cross_repo_co_changes(repo_paths, **kwargs)
+ # [0] is the capped list; the pre-cap total is asserted separately
+ # in TestCoChangeTruncationTotals.
+ return detect_cross_repo_co_changes(repo_paths, **kwargs)[0]
def test_noise_files_excluded_from_pairs(self) -> None:
"""Workflow/lockfile noise never appears in co-change results."""
diff --git a/tests/unit/workspace/test_diagnostics.py b/tests/unit/workspace/test_diagnostics.py
index a1c9a5c81..1f2291d93 100644
--- a/tests/unit/workspace/test_diagnostics.py
+++ b/tests/unit/workspace/test_diagnostics.py
@@ -8,6 +8,11 @@ from repowise.core.workspace.diagnostics import (
UnmatchedReason,
build_diagnostics,
)
+from repowise.core.workspace.extractors.from_index import (
+ EXTRACTION_LAYER_KEY,
+ LAYER_INDEX,
+ LAYER_REGEX,
+)
def _provider(
@@ -148,3 +153,76 @@ def test_round_trip_serialization():
diag = build_diagnostics(contracts, links)
restored = ExtractionDiagnostics.from_dict(diag.to_dict())
assert restored.to_dict() == diag.to_dict()
+
+
+# ---------------------------------------------------------------------------
+# Extraction coverage — the by-layer split and the unresolved denominator
+# ---------------------------------------------------------------------------
+
+
+def test_layer_split_reads_the_provenance_each_contract_carries():
+ index_provider = _provider("api", "http::GET::/a")
+ index_provider.meta[EXTRACTION_LAYER_KEY] = LAYER_INDEX
+ regex_provider = _provider("api", "http::GET::/b")
+ regex_provider.meta[EXTRACTION_LAYER_KEY] = LAYER_REGEX
+
+ diag = build_diagnostics([index_provider, regex_provider], [])
+
+ assert diag.providers_by_layer == {LAYER_INDEX: 1, LAYER_REGEX: 1}
+ assert diag.repo_breakdown[0].providers_by_layer == {LAYER_INDEX: 1, LAYER_REGEX: 1}
+
+
+def test_contract_with_no_recorded_layer_counts_as_regex():
+ """Absence of provenance must not vanish from the totals."""
+ diag = build_diagnostics([_provider("api", "http::GET::/a")], [])
+ assert diag.providers_by_layer == {LAYER_REGEX: 1}
+
+
+def test_unresolved_calls_reach_the_diagnostics_from_the_extraction_stats():
+ contracts = [_consumer("web", "http::GET::/u")]
+ stats = {"web": {"http_consumer_unresolved": 3}}
+
+ diag = build_diagnostics(contracts, [], stats)
+
+ assert diag.http_consumers_unresolved == 3
+ assert diag.repo_breakdown[0].http_consumers_unresolved == 3
+ # 1 resolved of 4 located.
+ assert diag.http_consumer_coverage == 0.25
+
+
+def test_unresolved_calls_counted_for_a_repo_with_no_contracts():
+ """A repo where every call failed to resolve has no breakdown row, and is
+ exactly the repo whose misses must not disappear."""
+ stats = {"ghost": {"http_consumer_unresolved": 9}}
+ diag = build_diagnostics([_consumer("web", "http::GET::/u")], [], stats)
+ assert diag.http_consumers_unresolved == 9
+ assert [r.repo for r in diag.repo_breakdown] == ["web"]
+
+
+def test_coverage_is_none_rather_than_perfect_when_nothing_was_located():
+ """0/0 is not 100%."""
+ assert build_diagnostics([], []).http_consumer_coverage is None
+ assert build_diagnostics([_provider("api", "http::GET::/a")], []).http_consumer_coverage is None
+
+
+def test_coverage_ignores_non_http_consumers():
+ """The unresolved counter only counts HTTP calls, so the denominator must
+ not be padded with grpc/topic consumers."""
+ contracts = [
+ _consumer("web", "http::GET::/u", ctype="http"),
+ _consumer("web", "grpc::Svc::M", ctype="grpc"),
+ ]
+ diag = build_diagnostics(contracts, [], {"web": {"http_consumer_unresolved": 1}})
+ assert diag.http_consumer_coverage == 0.5
+
+
+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}}
+ )
+ restored = ExtractionDiagnostics.from_dict(diag.to_dict())
+ assert restored.http_consumers_unresolved == 1
+ assert restored.http_consumer_coverage == 0.5
+ assert restored.to_dict() == diag.to_dict()
diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.py
index 9675e2a3e..9141e87e5 100644
--- a/tests/unit/workspace/test_system_graph.py
+++ b/tests/unit/workspace/test_system_graph.py
@@ -307,6 +307,10 @@ def test_system_graph_json_shape_is_locked():
"unmatched_consumers",
"unmatched_by_reason",
"orphan_providers",
+ "providers_by_layer",
+ "consumers_by_layer",
+ "http_consumers_unresolved",
+ "http_consumer_coverage",
}