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): bound cycle enumeration and report "at least N" when the cap stops it (#4657)

Raghav Chamadiya7cc040020e41
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.md
index bb8ebfe33..968c46891 100644
--- a/docs/architecture/workspace.md
+++ b/docs/architecture/workspace.md
@@ -180,7 +180,7 @@ both ways).
| Consumer | Reads | Output |
|----------|-------|--------|
-| `cycles.detect_cycles` | `adjacency()` | Cycles with `leg_kinds` per leg and `async_legs`; an event leg still closes a cycle; capped at `MAX_CYCLES` |
+| `cycles.detect_cycles` | `adjacency()` | Cycles with `leg_kinds` per leg and `async_legs`; an event leg still closes a cycle; capped at `MAX_CYCLES`; enumeration stops at `MAX_ENUMERATED_CYCLES`, then the total is a floor (`total_capped`) and the listed cycles come from a length-bounded pass (up to `MAX_CYCLE_LENGTH`) |
| `architecture_metrics.compute_architecture_metrics` | `adjacency()`, `detect_cycles` | Propagation cost, core, roles, 1-10 score |
| `conformance.build_conformance_report` | Structural edges, declared rules | Violations, cycles, `cycles_determined` |
| `blast_radius.cross_repo_blast_radius` | `adjacency(impact=True)`, co-change at `BEHAVIORAL_EDGE_WEIGHT` | Impacted services by distance, `undetermined_targets` |
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 2aa96f5fd..8f7d01be6 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -727,7 +727,7 @@ Impacted services with `score` (0 to 1 relative path weight, uncalibrated), `dis
### `get_architecture`
-`score` (1 to 10; higher is lower coupling, smaller core), `architecture_type` (`core-periphery`, `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size`, `core_ratio`, `core_members`, `cycle_count`, `conformance_violations`, `role_breakdown` (Core, Shared, Control, Peripheral), `evidence`, `http_calls`, `summary`.
+`score` (1 to 10; higher is lower coupling, smaller core), `architecture_type` (`core-periphery`, `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size`, `core_ratio`, `core_members`, `cycle_count`, `cycle_count_capped` (true when the enumeration budget stopped the count, so `cycle_count` is a floor), `conformance_violations`, `role_breakdown` (Core, Shared, Control, Peripheral), `evidence`, `http_calls`, `summary`.
### Cross-repo link rows
@@ -737,7 +737,7 @@ A contract link row carries `strategy`, the rule that matched it (`exact_id`, `u
### `get_conformance`
-`violations` (`source`, `target`, `rule_source` / `rule_target`, `edge_kind`), `cycles` (`nodes`, `length`), `violation_count`, `cycle_count`, `rules_evaluated`. A report that never ran says so, not zero counts.
+`violations` (`source`, `target`, `rule_source` / `rule_target`, `edge_kind`), `cycles` (`nodes`, `length`), `violation_count`, `cycle_count`, `total_cycles`, `total_capped` (true when `total_cycles` is "at least"), `rules_evaluated`. A report that never ran says so, not zero counts.
### `get_dependency_path`
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 defe5f607..b2eeac0d6 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/check.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/check.py
@@ -96,7 +96,7 @@ def workspace_check(path: str | None, breaking: bool, fmt: str, as_json: bool) -
tail = f", {len(breaking_changes)} breaking contract change(s)" if bc_ran else ""
console.print(
f"\n[red]Architecture check failed:[/red] {len(report.violations)} violation(s), "
- f"{len(report.cycles)} cycle(s){tail}."
+ f"{_cycle_count(report)} cycle(s){tail}."
)
sys.exit(1)
@@ -188,7 +188,12 @@ def _print_violations(report: ConformanceReport) -> None:
def _print_cycles(report: ConformanceReport) -> None:
if not report.cycles:
return
- console.print(f"\n[red]✗ {len(report.cycles)} dependency cycle(s):[/red]")
+ shown = (
+ f" (the {len(report.cycles)} shortest listed)"
+ if report.total_cycles > len(report.cycles)
+ else ""
+ )
+ console.print(f"\n[red]✗ {_cycle_count(report)} dependency cycle(s){shown}:[/red]")
console.print(
" [dim]a -\\[kind]-> b: a depends on b (a subscriber depends on its publisher).[/dim]"
)
@@ -201,6 +206,13 @@ def _print_cycles(report: ConformanceReport) -> None:
)
+def _cycle_count(report: ConformanceReport) -> str:
+ """How many cycles exist, past the listed cap; "at least N" when the budget stopped it."""
+ from repowise.core.workspace.cycles import cycle_total
+
+ return cycle_total(max(report.total_cycles, len(report.cycles)), report.total_capped)
+
+
def _cycle_path(cycle: DependencyCycle) -> str:
"""``a -[http]-> b -[event]-> a``, each leg labelled with its edge kinds."""
if not cycle.nodes:
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 ed3b2132d..de579cd11 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/metrics.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/metrics.py
@@ -30,9 +30,10 @@ def workspace_metrics(path: str | None, fmt: str, as_json: bool) -> None:
check_conformance,
tags_by_repo_from_config,
)
+ from repowise.core.workspace.cycles import cycle_total
from repowise.core.workspace.system_graph import load_system_graph
- fmt = resolve_format(fmt, as_json)
+ fmt =resolve_format(fmt, as_json)
start = resolve_repo_path(path)
ws_root, ws_config = _require_workspace(start)
@@ -105,7 +106,10 @@ def workspace_metrics(path: str | None, fmt: str, as_json: bool) -> None:
f" Cyclic core [green]none[/green]"
f" [dim]({metrics.node_count} services, acyclic structure)[/dim]"
)
- console.print(f" Dependency cycles [bold]{metrics.cycle_count}[/bold]")
+ console.print(
+ " Dependency cycles [bold]"
+ f"{cycle_total(metrics.cycle_count or 0, metrics.cycle_count_capped)}[/bold]"
+ )
if metrics.conformance_violations:
console.print(
f" Rule violations [red]{metrics.conformance_violations}[/red]"
diff --git a/packages/core/src/repowise/core/report/sections/estate_map.py b/packages/core/src/repowise/core/report/sections/estate_map.py
index f78a09301..65c99ae27 100644
--- a/packages/core/src/repowise/core/report/sections/estate_map.py
+++ b/packages/core/src/repowise/core/report/sections/estate_map.py
@@ -55,7 +55,7 @@ def _dependencies(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:
def _architecture(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:
from repowise.core.workspace.architecture_metrics import compute_architecture_metrics
from repowise.core.workspace.conformance import check_conformance, tags_by_repo_from_config
- from repowise.core.workspace.cycles import detect_cycles
+ from repowise.core.workspace.cycles import cycle_total, detect_cycles
config = ctx.config()
violations = check_conformance(
@@ -73,14 +73,14 @@ def _architecture(ctx: WorkspaceReportContext, graph: Any) -> dict[str, Any]:
basis="unresolved",
data=data,
)
- cycles, _total = detect_cycles(graph)
+ cycles, _total, _capped = detect_cycles(graph)
roles = metrics.role_breakdown()
details = [
f"propagation cost {metrics.propagation_cost_pct:.1f}%: the average share of other "
"services one service can reach",
f"cyclic core: {', '.join(metrics.core_members)}" if metrics.core_members
else "cyclic core: none",
- f"{metrics.cycle_count} dependency cycle(s)",
+ f"{cycle_total(metrics.cycle_count or 0, metrics.cycle_count_capped)} dependency cycle(s)",
*capped(
[
" -> ".join([*c.nodes, c.nodes[0]])
diff --git a/packages/core/src/repowise/core/workspace/architecture_metrics.py b/packages/core/src/repowise/core/workspace/architecture_metrics.py
index 35a70c60c..bc6c42f4f 100644
--- a/packages/core/src/repowise/core/workspace/architecture_metrics.py
+++ b/packages/core/src/repowise/core/workspace/architecture_metrics.py
@@ -159,6 +159,9 @@ class ArchitectureMetrics:
roles: list[NodeArchitectureRole] = field(default_factory=list)
generated_at: str = ""
evidence: GraphEvidence | None = None
+ #: True when the cycle enumeration budget stopped the count, so
+ #: ``cycle_count`` is "at least" that many.
+ cycle_count_capped: bool = False
def role_breakdown(self) -> dict[str, int]:
"""Count of services per role, in canonical role order."""
@@ -177,6 +180,7 @@ class ArchitectureMetrics:
"core_ratio": self.core_ratio,
"core_members": self.core_members,
"cycle_count": self.cycle_count,
+ "cycle_count_capped": self.cycle_count_capped,
"conformance_violations": self.conformance_violations,
"architecture_type": self.architecture_type,
"score": self.score,
@@ -429,7 +433,7 @@ def compute_architecture_metrics(
# 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)
+ _, cycle_count, cycle_count_capped = 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
@@ -444,6 +448,7 @@ def compute_architecture_metrics(
core_ratio=round(core_ratio, 4),
core_members=core_members,
cycle_count=cycle_count,
+ cycle_count_capped=cycle_count_capped,
conformance_violations=conformance_violations,
architecture_type=architecture_type,
score=score,
diff --git a/packages/core/src/repowise/core/workspace/conformance.py b/packages/core/src/repowise/core/workspace/conformance.py
index 0ea56e9cd..c7fc0abbb 100644
--- a/packages/core/src/repowise/core/workspace/conformance.py
+++ b/packages/core/src/repowise/core/workspace/conformance.py
@@ -202,6 +202,9 @@ class ConformanceReport:
cycles: list[DependencyCycle] = field(default_factory=list)
#: True cycle count before :data:`cycles.MAX_CYCLES` capped ``cycles``.
total_cycles: int = 0
+ #: True when the enumeration budget stopped the count: ``total_cycles`` is
+ #: then a lower bound ("at least N"), not the exact total.
+ total_capped: bool = False
#: :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
@@ -243,6 +246,7 @@ class ConformanceReport:
# 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),
+ "total_capped": self.total_capped,
"violating_repos": self.violating_repos,
"cycles_determined": self.cycles_determined,
"evidence": self.evidence,
@@ -261,6 +265,7 @@ class ConformanceReport:
violations=[ConformanceViolation.from_dict(v) for v in data.get("violations", [])],
cycles=cycles,
total_cycles=data.get("total_cycles", len(cycles)),
+ total_capped=bool(data.get("total_capped", False)),
evidence=data.get("evidence"),
)
@@ -356,13 +361,14 @@ def build_conformance_report(
now rather than to empty. Only a report nobody built is unstamped.
"""
violations = check_conformance(graph, rules, tags_by_repo)
- cycles, total_cycles = detect_cycles(graph)
+ cycles, total_cycles, total_capped = detect_cycles(graph)
return ConformanceReport(
generated_at=generated_at or datetime.now(UTC).isoformat(),
rules_evaluated=len(rules),
violations=violations,
cycles=cycles,
total_cycles=total_cycles,
+ total_capped=total_capped,
evidence=graph_evidence(graph).to_dict(),
)
diff --git a/packages/core/src/repowise/core/workspace/cycles.py b/packages/core/src/repowise/core/workspace/cycles.py
index 57ec80879..c947ea4cc 100644
--- a/packages/core/src/repowise/core/workspace/cycles.py
+++ b/packages/core/src/repowise/core/workspace/cycles.py
@@ -18,11 +18,16 @@ which legs are asynchronous (:data:`ASYNC_EDGE_KINDS`) instead of hiding them.
**Reuse, not reinvention.** Cycle finding is delegated to NetworkX
(``simple_cycles`` / ``strongly_connected_components``) — the same library the
-single-repo graph metrics use — rather than a hand-rolled DFS. The graph is
-service-granular (tens of nodes), so enumeration is cheap; we still cap the
+single-repo graph metrics use — rather than a hand-rolled DFS. We cap the
reported set (:data:`MAX_CYCLES`) and log truncation so a pathological graph
never bloats the artifact silently.
+**Bounded enumeration.** Cycle count grows exponentially with the largest
+strongly connected component (an 18-service tangle has millions), so the
+enumeration stops after :data:`MAX_ENUMERATED_CYCLES`. Under that budget the
+total is exact; past it the total is a lower bound (``total_capped``) and the
+listed cycles come from a length-bounded pass, so they are still the shortest.
+
Pure and I/O-free: it consumes a ``SystemGraph`` and returns dataclasses.
"""
@@ -46,6 +51,15 @@ _log = logging.getLogger("repowise.workspace.cycles")
#: for the other.
MAX_CYCLES = 50
+#: Enumeration budget. A graph with more cycles than this reports the total as
+#: "at least" this many instead of enumerating every one (which is exponential
+#: in the largest cyclic group and hangs on a dense tangle).
+MAX_ENUMERATED_CYCLES = 20_000
+
+#: Longest cycle the bounded pass looks for once the budget is hit. The short
+#: loops are the actionable ones, and length-bounded enumeration stays cheap.
+MAX_CYCLE_LENGTH = 6
+
# ---------------------------------------------------------------------------
# Data model
@@ -100,6 +114,11 @@ class DependencyCycle:
# ---------------------------------------------------------------------------
+def cycle_total(total: int, capped: bool) -> str:
+ """``total`` as a reader should see it: "at least N" when the budget stopped the count."""
+ return f"at least {total}" if capped else str(total)
+
+
def _cycle(
nodes: list[str], adjacency: dict[str, dict[str, list[SystemEdge]]]
) -> DependencyCycle:
@@ -134,49 +153,89 @@ def _canonical_rotation(nodes: list[str]) -> list[str]:
return nodes[start:] + nodes[:start]
-def detect_cycles(graph: SystemGraph) -> tuple[list[DependencyCycle], int]:
- """Return the structural dependency cycles in *graph*, and how many exist.
+def _enumerate(digraph: Any, length_bound: int | None) -> tuple[list[list[str]], bool]:
+ """Up to :data:`MAX_ENUMERATED_CYCLES` rotated cycles, and whether that is all of them."""
+ import networkx as nx
+
+ found: list[list[str]] = []
+ for raw in nx.simple_cycles(digraph, length_bound=length_bound):
+ if len(found) == MAX_ENUMERATED_CYCLES:
+ return found, False
+ found.append(_canonical_rotation(raw))
+ return found, True
+
+
+def _shortest_cycles(digraph: Any) -> list[list[str]]:
+ """Every cycle up to the longest length whose bounded pass fits the budget.
+
+ Raises the bound one length at a time and stops once the pass holds
+ :data:`MAX_CYCLES` cycles (the shortest ones are then all in it) or the
+ budget cuts it. The previous complete pass is then kept, even with fewer
+ than :data:`MAX_CYCLES`: a cut pass is an arbitrary subset, and listing
+ fewer cycles beats listing ones that change from run to run.
+ """
+ best: list[list[str]] = []
+ for bound in range(1, MAX_CYCLE_LENGTH + 1):
+ found, complete = _enumerate(digraph, bound)
+ if not complete:
+ return best or found
+ best = found
+ if len(best) >= MAX_CYCLES:
+ break
+ return best
+
+
+def detect_cycles(graph: SystemGraph) -> tuple[list[DependencyCycle], int, bool]:
+ """Return the structural dependency cycles in *graph*, how many, and whether that is a floor.
Cycles are ordered shortest-first (the tightest loops are the most
actionable), then lexicographically for stability. Every cycle is rotated
to start at its smallest node id, so the same graph always produces the
same cycles regardless of hash seed. 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.
+ :data:`MAX_CYCLES`; the second element is the count before that cap, so a
+ caller reporting "N cycles" cannot accidentally report the cap instead.
+ The third is True when the enumeration budget stopped the count: the total
+ is then "at least N". Returns ``([], 0, False)`` when the structural
+ subgraph is acyclic or NetworkX is unavailable.
"""
adjacency = graph.adjacency()
if not adjacency:
- return [], 0
+ return [], 0, False
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 [], 0
+ return [], 0, False
digraph = nx.DiGraph()
digraph.add_nodes_from(n.id for n in graph.nodes)
digraph.add_edges_from((src, tgt) for src, targets in adjacency.items() for tgt in targets)
- cycles: list[DependencyCycle] = []
try:
- for raw in nx.simple_cycles(digraph):
- cycle = _cycle(_canonical_rotation(raw), adjacency)
- if cycle.edge_ids:
- cycles.append(cycle)
+ raw_cycles, complete = _enumerate(digraph, None)
+ total = len(raw_cycles)
+ if not complete:
+ # No cycle within MAX_CYCLE_LENGTH: list some from the cut full pass
+ # rather than none beside "at least N" (which ones then follows
+ # networkx iteration order).
+ raw_cycles = _shortest_cycles(digraph) or raw_cycles
except Exception: # pragma: no cover - defensive
_log.warning("cycle enumeration failed", exc_info=True)
- return [], 0
+ return [], 0, False
- cycles.sort(key=lambda c: (c.length, c.nodes))
- total = len(cycles)
- if total > MAX_CYCLES:
+ raw_cycles.sort(key=lambda nodes: (len(nodes), nodes))
+ if not complete:
+ _log.info(
+ "Cycle detection stopped at %d cycles; reporting the %d shortest.",
+ total,
+ min(total, MAX_CYCLES),
+ )
+ elif total > MAX_CYCLES:
_log.info(
"Cycle detection found %d cycles; reporting the %d shortest.",
total,
MAX_CYCLES,
)
- cycles = cycles[:MAX_CYCLES]
- return cycles, total
+ cycles = [_cycle(nodes, adjacency) for nodes in raw_cycles[:MAX_CYCLES]]
+ return cycles, total, not complete
diff --git a/packages/core/src/repowise/core/workspace/reads.py b/packages/core/src/repowise/core/workspace/reads.py
index 56a83cf60..b30a7ec43 100644
--- a/packages/core/src/repowise/core/workspace/reads.py
+++ b/packages/core/src/repowise/core/workspace/reads.py
@@ -447,6 +447,7 @@ 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,
+ "total_capped": bool(report.get("total_capped", False)),
"cycles_determined": report.get("cycles_determined"),
"evidence": report.get("evidence"),
"violating_repos": sorted(
diff --git a/packages/core/src/repowise/core/workspace/update/phases.py b/packages/core/src/repowise/core/workspace/update/phases.py
index 2c587004f..9eac6907c 100644
--- a/packages/core/src/repowise/core/workspace/update/phases.py
+++ b/packages/core/src/repowise/core/workspace/update/phases.py
@@ -447,4 +447,5 @@ def _conformance_phase(
# The true total, not the capped list — a workspace with 500 cycles
# must not report the same number as one with 50.
cycles=conformance.total_cycles if conformance else 0,
+ cycles_capped=conformance.total_capped if conformance else False,
)
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 47416cfa6..3cc6e24a5 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -460,6 +460,7 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
"violation_count",
"cycle_count",
"total_cycles",
+ "total_capped",
"cycles_determined",
"error",
),
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 0fd37d9ba..bad0f03d2 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_architecture.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
@@ -87,6 +87,8 @@ def architecture_payload(metrics: dict[str, Any]) -> dict[str, Any]:
"core_members": shown_core,
"core_members_truncated": max(0, len(core_members) - len(shown_core)),
"cycle_count": metrics.get("cycle_count", 0),
+ # True when the enumeration budget stopped the count: "at least" cycle_count.
+ "cycle_count_capped": bool(metrics.get("cycle_count_capped", False)),
"conformance_violations": metrics.get("conformance_violations", 0),
"role_breakdown": breakdown,
"evidence": evidence or None,
@@ -98,6 +100,8 @@ def architecture_payload(metrics: dict[str, Any]) -> dict[str, Any]:
def _summary(metrics: dict[str, Any], evidence: dict[str, Any]) -> str:
"""One sentence, which says "not determined" rather than score an unseen graph."""
+ from repowise.core.workspace.cycles import cycle_total
+
if metrics.get("score") is None:
return (
f"Architecture not determined for {metrics.get('node_count', 0)} service(s): "
@@ -115,7 +119,8 @@ def _summary(metrics: dict[str, Any], evidence: dict[str, Any]) -> str:
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)."
+ f"{cycle_total(metrics.get('cycle_count') or 0, bool(metrics.get('cycle_count_capped')))}"
+ " dependency cycle(s)."
)
if evidence.get("state") == "partial":
summary += f" Partial evidence: {evidence.get('summary')}."
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 661ea0af8..6ac0f14b2 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_conformance.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
@@ -86,6 +86,7 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:
def conformance_payload(report: dict[str, Any], repo: str | None = None) -> dict[str, Any]:
"""The ``get_conformance`` answer over a *report* that ran, without ``_meta``."""
+ from repowise.core.workspace.cycles import cycle_total
from repowise.core.workspace.reads import conformance_for_repo
if repo:
@@ -95,10 +96,12 @@ def conformance_payload(report: dict[str, Any], repo: str | None = None) -> dict
# Scoping picks from the already-capped stored list, so the pre-cap
# workspace total does not describe this subset.
total_cycles = len(cycles)
+ total_capped = False
else:
violations = report.get("violations", [])
cycles = report.get("cycles", [])
total_cycles = report.get("total_cycles", len(cycles))
+ total_capped = bool(report.get("total_capped", False))
shown_violations = violations[:_MCP_VIOLATION_LIMIT]
shown_cycles = cycles[:_MCP_CYCLE_LIMIT]
@@ -106,7 +109,8 @@ def conformance_payload(report: dict[str, Any], repo: str | None = None) -> dict
evidence = report.get("evidence") or {}
if violations or cycles:
summary = (
- f"{len(violations)} architecture rule violation(s) and {total_cycles} "
+ f"{len(violations)} architecture rule violation(s) and "
+ f"{cycle_total(total_cycles, total_capped)} "
f"dependency cycle(s) from {report.get('rules_evaluated', 0)} declared rule(s)."
)
elif report.get("cycles_determined") is False:
@@ -132,6 +136,8 @@ def conformance_payload(report: dict[str, Any], repo: str | None = None) -> dict
# many the workspace has, which the stored report may itself have cut.
"cycle_count": len(cycles),
"total_cycles": total_cycles,
+ # True when the enumeration budget stopped the count: "at least" total_cycles.
+ "total_capped": total_capped,
"checked_at": report.get("generated_at"),
"cycles_determined": report.get("cycles_determined"),
"evidence": evidence or None,
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index be706b840..6e777f5c1 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -658,6 +658,9 @@ class WorkspaceConformanceResponse(BaseModel):
#: many exist. They differ when MAX_CYCLES truncated the list.
cycle_count: int = 0
total_cycles: int = 0
+ #: True when the enumeration budget stopped the count, so ``total_cycles``
+ #: is a lower bound ("at least N").
+ total_capped: bool = False
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.
@@ -689,6 +692,8 @@ class WorkspaceArchitectureResponse(BaseModel):
core_ratio: float | None = None
core_members: list[str] = []
cycle_count: int | None = None
+ #: True when the enumeration budget stopped the count ("at least N").
+ cycle_count_capped: bool = False
conformance_violations: int = 0
architecture_type: str = "undetermined"
score: float | None = None
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index f88574a37..2fd30cfb8 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4443,6 +4443,7 @@ export interface WorkspaceArchitectureResponse {
core_ratio?: number | null;
core_members?: string[];
cycle_count?: number | null;
+ cycle_count_capped?: boolean;
conformance_violations?: number;
architecture_type?: string;
score?: number | null;
@@ -4547,6 +4548,7 @@ export interface WorkspaceConformanceResponse {
violation_count?: number;
cycle_count?: number;
total_cycles?: number;
+ total_capped?: boolean;
violating_repos?: string[];
cycles_determined?: boolean | null;
evidence?: WorkspaceGraphEvidence | null;
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index c6272c76e..5d178bc92 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -622,6 +622,8 @@ export interface ConformanceReport {
cycle_count: number;
/** How many cycles exist. Above `cycle_count` when the list was cut. */
total_cycles: number;
+ /** True when the enumeration budget stopped the count: `total_cycles` is "at least". */
+ total_capped?: boolean;
/** Distinct repos participating in a violation. */
violating_repos: string[];
/** False when the graph had too little evidence for "no cycles" to mean anything. */
@@ -706,6 +708,8 @@ export interface ArchitectureMetrics {
core_members: string[];
/** Elementary dependency cycles (matches the conformance report's count). */
cycle_count: number | null;
+ /** True when the enumeration budget stopped the count: `cycle_count` is "at least". */
+ cycle_count_capped?: boolean;
/** Declared-rule violations folded into the score (0 when no rules). */
conformance_violations: number;
architecture_type: ArchitectureType;
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 3c75c10be..ef170c950 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
@@ -127,7 +127,7 @@ export function SystemMapConformancePanel({
const totalCycles = report.total_cycles ?? report.cycle_count;
const cycleSummary =
totalCycles > report.cycle_count
- ? `${report.cycle_count} of ${totalCycles} cycles`
+ ? `${report.cycle_count} of ${report.total_capped ? "at least " : ""}${totalCycles} cycles`
: `${report.cycle_count} ${report.cycle_count === 1 ? "cycle" : "cycles"}`;
const violations = `${report.violation_count} ${
report.violation_count === 1 ? "violation" : "violations"
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 4bdfb58d5..494dfed60 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
@@ -249,7 +249,7 @@ function ConformanceResults({ conformance, graph, onSelect, onPrompt, conformanc
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.`
+ ? `${conformance.cycle_count} of ${conformance.total_capped ? "at least " : ""}${plural(total, "dependency cycle", "dependency cycles")} listed.`
: `${plural(conformance.cycle_count, "dependency cycle", "dependency cycles")}.`;
return (
diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.json
index 33cde31ae..2a1476052 100644
--- a/tests/fixtures/mcp/tool_response_shapes.json
+++ b/tests/fixtures/mcp/tool_response_shapes.json
@@ -68,6 +68,7 @@
"core_ratio": null,
"core_size": null,
"cycle_count": null,
+ "cycle_count_capped": null,
"node_count": null,
"propagation_cost_pct": null,
"role_breakdown": {
@@ -291,6 +292,7 @@
"rules_evaluated": null,
"summary": null,
"total_cycles": null,
+ "total_capped": null,
"violation_count": null,
"violations": [],
"violations_truncated": null
diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.py
index ea19b63fd..ddc003a8e 100644
--- a/tests/unit/cli/test_workspace_cmd.py
+++ b/tests/unit/cli/test_workspace_cmd.py
@@ -806,6 +806,20 @@ class TestWorkspaceCheck:
assert "cycle" in result.output.lower()
assert "frontend !-> db" in result.output
+ def test_a_tangle_past_the_budget_reads_at_least(self, runner, tmp_path, monkeypatch):
+ import repowise.core.workspace.cycles as cy
+
+ self._write_config_with_rule(tmp_path, [])
+ names = [f"s{i}" for i in range(5)]
+ self._save_graph(tmp_path, [(s, t) for s in names for t in names if s != t])
+ monkeypatch.setattr(cy, "MAX_ENUMERATED_CYCLES", 60)
+ check = runner.invoke(cli, ["workspace", "check", str(tmp_path)])
+ metrics = runner.invoke(cli, ["workspace", "metrics", str(tmp_path)])
+ assert check.exit_code == 1, check.output
+ assert "at least 60 dependency cycle(s) (the 50 shortest listed)" in check.output
+ assert "at least 60 cycle(s)" in check.output
+ assert "at least 60" in metrics.output, metrics.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,
diff --git a/tests/unit/server/test_mcp_conformance.py b/tests/unit/server/test_mcp_conformance.py
index afc8099a0..0ef8a6c95 100644
--- a/tests/unit/server/test_mcp_conformance.py
+++ b/tests/unit/server/test_mcp_conformance.py
@@ -266,3 +266,46 @@ def test_an_unseen_graph_reads_not_determined_to_an_agent():
report = conformance_payload(build_conformance_report(graph, []).to_dict())
assert report["cycles_determined"] is False
assert "cycles not determined" in report["summary"]
+
+
+def test_a_capped_cycle_count_reads_at_least_to_an_agent():
+ """When the enumeration budget stopped the count, both tools say "at least"."""
+ from unittest.mock import patch
+
+ import repowise.core.workspace.cycles as cy
+ 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
+
+ names = [f"s{i}" for i in range(5)]
+ graph = SystemGraph(
+ nodes=[SystemNode(id=n, repo=n, service_path=None, name=n) for n in names],
+ edges=[
+ SystemEdge(
+ id=f"{s}->{t}:http",
+ source=s,
+ target=t,
+ kind="http",
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ )
+ for s in names
+ for t in names
+ if s != t
+ ],
+ )
+ with patch.object(cy, "MAX_ENUMERATED_CYCLES", 30):
+ report = build_conformance_report(graph, [], generated_at="t").to_dict()
+ metrics = compute_architecture_metrics(graph).to_dict()
+
+ payload = conformance_payload(report)
+ assert (payload["total_cycles"], payload["total_capped"]) == (30, True)
+ assert "at least 30 dependency cycle(s)" in payload["summary"]
+ # A repo-scoped answer counts only what it lists, so it is exact.
+ assert conformance_payload(report, "s0")["total_capped"] is False
+
+ arch = architecture_payload(metrics)
+ assert (arch["cycle_count"], arch["cycle_count_capped"]) == (30, True)
+ assert "at least 30 dependency cycle(s)" in arch["summary"]
diff --git a/tests/unit/workspace/test_architecture_metrics.py b/tests/unit/workspace/test_architecture_metrics.py
index 45c20ca7e..284b7baf6 100644
--- a/tests/unit/workspace/test_architecture_metrics.py
+++ b/tests/unit/workspace/test_architecture_metrics.py
@@ -212,6 +212,7 @@ def test_snapshot_shape_and_score_are_locked():
"core_ratio",
"core_members",
"cycle_count",
+ "cycle_count_capped",
"conformance_violations",
"architecture_type",
"score",
diff --git a/tests/unit/workspace/test_conformance.py b/tests/unit/workspace/test_conformance.py
index 044a60468..aae9171be 100644
--- a/tests/unit/workspace/test_conformance.py
+++ b/tests/unit/workspace/test_conformance.py
@@ -178,7 +178,7 @@ def test_two_node_cycle():
[_node("a"), _node("b")],
[_edge("a", "b"), _edge("b", "a")],
)
- cycles, total = detect_cycles(g)
+ cycles, total, _capped = detect_cycles(g)
assert len(cycles) == 1
assert total == 1
assert set(cycles[0].nodes) == {"a", "b"}
@@ -190,7 +190,7 @@ def test_longer_cycle():
[_node("a"), _node("b"), _node("c")],
[_edge("a", "b"), _edge("b", "c"), _edge("c", "a")],
)
- cycles, total = detect_cycles(g)
+ cycles, total, _capped = detect_cycles(g)
assert len(cycles) == 1
assert total == 1
assert set(cycles[0].nodes) == {"a", "b", "c"}
@@ -211,7 +211,7 @@ def test_cycles_start_at_smallest_node_id():
)
for rotation in (["a", "b", "c"], ["b", "c", "a"], ["c", "a", "b"]):
with patch.object(nx, "simple_cycles", return_value=[rotation]):
- (cycle,), total = detect_cycles(g)
+ (cycle,), total, _capped = detect_cycles(g)
assert cycle.nodes == ["a", "b", "c"]
assert cycle.edge_ids == ["a->b:http", "b->c:http", "c->a:http"]
assert cycle.leg_kinds == [["http"], ["http"], ["http"]]
@@ -223,7 +223,7 @@ def test_acyclic_graph_has_no_cycles():
[_node("a"), _node("b"), _node("c")],
[_edge("a", "b"), _edge("b", "c")],
)
- assert detect_cycles(g) == ([], 0)
+ assert detect_cycles(g) == ([], 0, False)
def test_a_cycle_closed_by_an_event_counts_and_names_each_legs_kinds():
@@ -231,7 +231,7 @@ def test_a_cycle_closed_by_an_event_counts_and_names_each_legs_kinds():
[_node("a"), _node("b")],
[_edge("a", "b", kind="event"), _edge("b", "a"), _edge("b", "a", kind="db")],
)
- [cycle], total = detect_cycles(g)
+ [cycle], total, _capped = detect_cycles(g)
assert total == 1
legs = dict(zip(cycle.nodes, cycle.leg_kinds, strict=True))
assert legs == {"a": ["event"], "b": ["db", "http"]}
@@ -246,7 +246,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) == ([], 0)
+ assert detect_cycles(g) == ([], 0, False)
# ---------------------------------------------------------------------------
@@ -397,3 +397,62 @@ def test_report_carries_the_true_cycle_count_past_the_cap():
assert len(report.cycles) == 2
assert report.total_cycles > 2
assert report.to_dict()["total_cycles"] == report.total_cycles
+ assert report.total_capped is False
+
+
+def _complete_graph(n: int):
+ names = [f"s{i:02d}" for i in range(n)]
+ return _graph(
+ [_node(x) for x in names], [_edge(s, t) for s in names for t in names if s != t]
+ )
+
+
+def test_a_dense_tangle_stops_at_the_budget_and_lists_the_shortest_cycles():
+ import repowise.core.workspace.cycles as cy
+
+ # K6 has 409 elementary cycles; a budget of 100 stops the count.
+ g = _complete_graph(6)
+ with patch.object(cy, "MAX_ENUMERATED_CYCLES", 100):
+ cycles, total, capped = detect_cycles(g)
+ report = build_conformance_report(g, [])
+ assert capped is True
+ assert total == 100
+ # The bounded pass lists the 15 two-service loops and then the triangles.
+ assert [c.length for c in cycles] == sorted(c.length for c in cycles)
+ assert cycles[0].length == 2
+ assert sum(1 for c in cycles if c.length == 2) == 15
+ assert len(cycles) == cy.MAX_CYCLES
+ assert report.total_capped is True
+ restored = type(report).from_dict(report.to_dict())
+ assert restored.total_capped is True
+ assert restored.total_cycles == 100
+
+
+def test_cycles_under_the_budget_keep_the_exact_count():
+ import repowise.core.workspace.cycles as cy
+
+ g = _complete_graph(6)
+ with patch.object(cy, "MAX_ENUMERATED_CYCLES", 409):
+ _, total, capped = detect_cycles(g)
+ assert (total, capped) == (409, False)
+
+
+def test_cycle_total_says_at_least_when_capped():
+ from repowise.core.workspace.cycles import cycle_total
+
+ assert cycle_total(7, False) == "7"
+ assert cycle_total(20000, True) == "at least 20000"
+
+
+def test_a_capped_count_with_only_long_cycles_still_lists_one():
+ import repowise.core.workspace.cycles as cy
+
+ # Two 7-service rings through "a": no cycle within MAX_CYCLE_LENGTH.
+ rings = [list("abcdefg"), ["a", *"hijklm"]]
+ names = sorted({n for ring in rings for n in ring})
+ edges = [_edge(r[i], r[(i + 1) % len(r)]) for r in rings for i in range(len(r))]
+ g = _graph([_node(n) for n in names], edges)
+ with patch.object(cy, "MAX_ENUMERATED_CYCLES", 1):
+ cycles, total, capped = detect_cycles(g)
+ assert (total, capped) == (1, True)
+ assert [c.length for c in cycles] == [7]