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.

refactor(core): decompose the KG tour into named stages (#2593)

Raghav Chamadiya8e75f93c81dd
diff --git a/packages/core/src/repowise/core/analysis/kg_tour.py b/packages/core/src/repowise/core/analysis/kg_tour.py
index 708b24681..36f34e692 100644
--- a/packages/core/src/repowise/core/analysis/kg_tour.py
+++ b/packages/core/src/repowise/core/analysis/kg_tour.py
@@ -7,6 +7,7 @@ import graph cannot support flow claims.
from __future__ import annotations
from collections import Counter, defaultdict
+from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import PurePosixPath
from typing import Any
@@ -40,16 +41,11 @@ _FIXTURE_CAMEL_RES = _LANG_REGISTRY.camel_fixture_res_by_extension()
# face must come from inside one.
_TEST_PROJECT_DIR_SUFFIXES: tuple[str, ...] = _LANG_REGISTRY.test_dir_suffixes()
-# Honest-degradation thresholds. Density = (imports + tested_by)
-# edges per dominant-language file — the same definition the validation
-# harness uses, calibrated on the 13-repo matrix: express (1.89, broken CJS
-# resolution) and sinatra (1.48, broken require resolution) land in
-# "sparse"; every healthy repo sits at ≥ 2.2. Repos below the file floor
-# skip the density check — density on a 7-file repo is noise, not evidence.
-# Low density alone stops indicting the resolver once the resolution rate
-# (internal targets / all targets) is strong: stdlib filtering makes an
-# honestly-resolved Ruby gem land at ~1.3 edges/file with 0.77 resolution —
-# that graph isn't lying, it's just require-light.
+# Honest-degradation thresholds. Density is import edges per dominant-language
+# file; resolution is internal targets over all targets. Repos below the file
+# floor skip the density check, since density on a tiny repo is noise. Low
+# density indicts the resolver only when resolution is also weak: a
+# require-light but well-resolved graph narrates honestly.
_FLOW_DENSITY_FLOOR = 2.0
_FLOW_RESOLUTION_FLOOR = 0.7
_STRUCTURAL_DENSITY_FLOOR = 0.3
@@ -80,45 +76,53 @@ def _graph_mode(dominant_lang: str, lang_by_path: dict[str, str], graph_builder:
dom_files = {p for p, lang in lang_by_path.items() if lang == dominant_lang}
if not dom_files:
return "structural"
- edge_count = 0
- internal_targets = 0
- external_targets = 0
- try:
- for src, dst, data in graph_builder.graph().edges(data=True):
- # "tested_by" was a second member here; it is a knowledge-graph
- # export label, never a raw edge type, so it never matched.
- if (data or {}).get("edge_type") == "imports" and src in dom_files:
- edge_count += 1
- if isinstance(dst, str) and is_external(dst):
- external_targets += 1
- else:
- internal_targets += 1
- except Exception: # pragma: no cover - defensive
+ counts = _import_target_counts(graph_builder, dom_files)
+ if counts is None: # pragma: no cover - defensive
return "flow" if support == "full" else "sparse"
- total = internal_targets + external_targets
- resolution = (internal_targets / total) if total else 0.0
- if len(dom_files) < _MODE_MIN_FILES:
- # Density is unmeasurable on tiny repos, but resolution is not: a
- # partial-tier repo whose imports resolve cleanly must not have its
- # tour blame "incomplete import resolution" just for being small.
- if support == "full" or (total and resolution >= _FLOW_RESOLUTION_FLOOR):
- return "flow"
- return "sparse"
- density = edge_count / len(dom_files)
+ return _mode_from_imports(support, len(dom_files), *counts)
+
+
+def _mode_from_imports(support: str, file_count: int, internal: int, external: int) -> str:
+ """The graph mode implied by import density and resolution rate."""
+ total = internal + external
+ resolution = (internal / total) if total else 0.0
+ if file_count < _MODE_MIN_FILES:
+ return _small_repo_mode(support, total, resolution)
+ density = total / file_count
if density < _STRUCTURAL_DENSITY_FLOOR:
return "structural"
- # Partial-tier languages run in flow or sparse per their REAL density
- # and resolution, exactly like full-tier ones: a regex-tier resolver
- # that resolves 0.95+ of an Elixir repo's aliases must not have its
- # tour blame "incomplete import resolution" — that would be the lie
- # this mode exists to prevent, inverted.
- # Low density indicts the resolver only when resolution is ALSO
- # weak — a require-light but well-resolved graph narrates honestly.
+ # Partial-tier languages are judged on their real density and resolution,
+ # exactly like full-tier ones.
if density < _FLOW_DENSITY_FLOOR and resolution < _FLOW_RESOLUTION_FLOOR:
return "sparse"
return "flow"
+def _small_repo_mode(support: str, total: int, resolution: float) -> str:
+ # Density is unmeasurable on tiny repos, but resolution is not: a
+ # partial-tier repo whose imports resolve cleanly must not have its
+ # tour blame "incomplete import resolution" just for being small.
+ if support == "full" or (total and resolution >= _FLOW_RESOLUTION_FLOOR):
+ return "flow"
+ return "sparse"
+
+
+def _import_target_counts(graph_builder: Any, sources: set[str]) -> tuple[int, int] | None:
+ """``(internal, external)`` import-target counts from *sources*, or None on error."""
+ internal = external = 0
+ try:
+ for src, dst, data in graph_builder.graph().edges(data=True):
+ if (data or {}).get("edge_type") != "imports" or src not in sources:
+ continue
+ if isinstance(dst, str) and is_external(dst):
+ external += 1
+ else:
+ internal += 1
+ except Exception: # pragma: no cover - defensive
+ return None
+ return internal, external
+
+
def _readme_overview_node(kg: KnowledgeGraphResult) -> dict | None:
"""The best root-level README/overview file node, if one exists."""
best: dict | None = None
@@ -140,12 +144,7 @@ def _best_in_layer(paths: list[str], rank: dict[str, float], pagerank: dict[str,
def _structural_walk(
- universe: list[str],
- type_by_path: dict[str, str],
- dominant_lang: str,
- pagerank: dict[str, float],
- graph_builder: Any,
- project_name: str = "",
+ universe: list[str], ctx: _TourContext, graph_builder: Any, project_name: str = ""
) -> tuple[list[str], dict[str, str]]:
"""Anchor + directory faces for repos with no usable import graph.
@@ -155,66 +154,86 @@ def _structural_walk(
the walk visits the largest top-level code areas, one face each. Every
reason says what the evidence is and what is missing.
"""
- # Manifests (mix.exs, setup.py) are code-shaped but describe the
- # project rather than implement it — never the place to start reading.
- manifests = _LANG_REGISTRY.manifest_filenames()
- code = [
- p
- for p in universe
- if type_by_path.get(p) not in {"config", "document"}
- and PurePosixPath(p).name not in manifests
- ]
+ code = _structural_code(universe, ctx.type_by_path)
if not code:
return [], {}
fan_in: Counter[str] = Counter()
for _src, dst in _file_import_edges(graph_builder):
fan_in[dst] += 1
-
- spec = _LANG_REGISTRY.get(dominant_lang)
- display = spec.display_name if spec else (dominant_lang or "this language")
+ display = _language_display_name(ctx.dominant_lang)
# Conventional names trump raw connectivity: an entry-named file
- # (application.ex, Main.hs) or the project-named module (lib/jason.ex in
- # jason — the library-main convention) is where a reader starts.
+ # (application.ex, Main.hs) or the project-named module (the
+ # library-main convention) is where a reader starts.
entry_names = _LANG_REGISTRY.entry_point_names()
project_stem = (project_name or "").lower()
-
- def conventional(p: str) -> bool:
- pp = PurePosixPath(p)
- return pp.name in entry_names or (
- bool(project_stem) and pp.stem.lower() == project_stem
- )
-
anchor = min(
code,
key=lambda p: (
- not conventional(p),
- -pagerank.get(p, 0.0),
+ not _is_conventional_anchor(p, entry_names, project_stem),
+ -ctx.pagerank.get(p, 0.0),
-fan_in.get(p, 0),
len(PurePosixPath(p).parts),
p,
),
)
+ reasons = {anchor: _structural_anchor_reason(anchor, entry_names, project_stem, display)}
+ walk = [anchor]
+ for face, reason in _directory_faces(code, anchor, ctx.pagerank):
+ reasons[face] = reason
+ walk.append(face)
+ return walk, reasons
+
+
+def _structural_code(universe: list[str], type_by_path: dict[str, str]) -> list[str]:
+ # Manifests (mix.exs, setup.py) are code-shaped but describe the
+ # project rather than implement it — never the place to start reading.
+ manifests = _LANG_REGISTRY.manifest_filenames()
+ return [
+ p
+ for p in universe
+ if type_by_path.get(p) not in {"config", "document"}
+ and PurePosixPath(p).name not in manifests
+ ]
+
+
+def _language_display_name(lang: str) -> str:
+ spec = _LANG_REGISTRY.get(lang)
+ return spec.display_name if spec else (lang or "this language")
+
+
+def _is_conventional_anchor(path: str, entry_names: frozenset[str], project_stem: str) -> bool:
+ pp = PurePosixPath(path)
+ return pp.name in entry_names or (bool(project_stem) and pp.stem.lower() == project_stem)
+
+
+def _structural_anchor_reason(
+ anchor: str, entry_names: frozenset[str], project_stem: str, display: str
+) -> str:
if PurePosixPath(anchor).name in entry_names:
- anchor_reason = (
+ return (
f"Named like an entry file — the conventional place {display} "
"execution starts. Import analysis isn't supported for "
f"{display} yet, so the walk follows the repo's structure."
)
- elif conventional(anchor):
- anchor_reason = (
+ if _is_conventional_anchor(anchor, entry_names, project_stem):
+ return (
"Named after the project — by convention the library's main "
f"module. Import analysis isn't supported for {display} yet, "
"so the walk follows the repo's structure."
)
- else:
- anchor_reason = (
- "The best-connected file by the evidence available (change "
- f"history and references). Import analysis isn't supported for "
- f"{display} yet, so the walk follows the repo's structure."
- )
+ return (
+ "The best-connected file by the evidence available (change "
+ f"history and references). Import analysis isn't supported for "
+ f"{display} yet, so the walk follows the repo's structure."
+ )
+
+def _directory_faces(
+ code: list[str], anchor: str, pagerank: dict[str, float]
+) -> list[tuple[str, str]]:
+ """One ``(face, reason)`` per top-level code area, largest area first."""
groups: dict[str, list[str]] = defaultdict(list)
for p in code:
if p == anchor:
@@ -222,8 +241,7 @@ def _structural_walk(
parts = PurePosixPath(p).parts
groups[parts[0] if len(parts) > 1 else "."].append(p)
- walk = [anchor]
- reasons = {anchor: anchor_reason}
+ faces: list[tuple[str, str]] = []
for d in sorted(groups, key=lambda d: (-len(groups[d]), d)):
face = min(
groups[d],
@@ -232,9 +250,8 @@ def _structural_walk(
n = len(groups[d])
label = "the repository root" if d == "." else f"{d}/"
count = f"{n} code files live here" if n != 1 else "1 code file lives here"
- reasons[face] = f"The face of {label} — {count}."
- walk.append(face)
- return walk, reasons
+ faces.append((face, f"The face of {label} — {count}."))
+ return faces
_FANOUT_GROUP_MIN = 3
@@ -253,15 +270,7 @@ def _import_groups(
"""
keyed: dict[tuple[str, tuple[str, ...]], list[str]] = defaultdict(list)
try:
- for src, dst, data in graph_builder.graph().edges(data=True):
- if not (isinstance(src, str) and isinstance(dst, str)):
- continue
- if data.get("edge_type", "imports") not in edge_types:
- continue
- # Stdlib/external imports say nothing about where a walk can
- # go — only repo-internal relationships count.
- if is_external(src) or is_external(dst):
- continue
+ for src, dst, data in _internal_edges(graph_builder, edge_types):
names = tuple(sorted(data.get("imported_names") or ())) or (dst,)
keyed[(src, names)].append(dst)
except Exception: # pragma: no cover - defensive
@@ -272,12 +281,22 @@ def _import_groups(
return groups
-# The harness signal is "this test file *depends on* that one" — type
-# references and inheritance (a base test class) are exactly that evidence;
-# raw-graph type_use/heritage edges surface as plain imports in the export.
-# Deliberately narrower than FILE_DEPENDENCY_EDGE_TYPES: framework and dynamic
-# wiring is not harness evidence. "heritage" used to be a third member and was
-# never an edge type — inheritance reaches the graph as extends/implements.
+def _internal_edges(graph_builder: Any, edge_types: frozenset[str]) -> Iterator[tuple[str, str, dict]]:
+ """Repo-internal edges of *edge_types*; untyped edges count as imports."""
+ for src, dst, data in graph_builder.graph().edges(data=True):
+ if not (isinstance(src, str) and isinstance(dst, str)):
+ continue
+ if data.get("edge_type", "imports") not in edge_types:
+ continue
+ # Stdlib/external imports say nothing about where a walk can
+ # go; only repo-internal relationships count.
+ if not (is_external(src) or is_external(dst)):
+ yield src, dst, data
+
+
+# The harness signal is "this test file *depends on* that one": imports and
+# type references are that evidence. Deliberately narrower than
+# FILE_DEPENDENCY_EDGE_TYPES, since framework and dynamic wiring is not.
_DEPENDENCY_EDGE_TYPES = frozenset({"imports", "type_use"})
@@ -356,39 +375,13 @@ def _curate_tour(
# consumers (UI, harness) can see the degradation level.
kg.project["graph_mode"] = ctx.graph_mode
- # The README is the overview stop, so it stays out of the walk. Tests and
- # examples are excluded before build_tour spends its step budget on them.
readme = _readme_overview_node(kg)
overview_target = readme["filePath"] if readme is not None else None
- walk_universe = [
- p
- for p in ctx.paths
- if p != overview_target
- and ctx.file_layers.get(p) not in ADJACENT_LAYERS
- and not is_support_path(p)
- and not PurePosixPath(p).parts[0].startswith(".") # dot-dir tooling
- ]
-
+ walk_universe = _walk_universe(ctx, overview_target)
project_name = kg.project.get("name") or "repository"
- # In structural mode the BFS walk is withheld entirely (a fake flow over
- # a near-edgeless graph is a lie); build_tour still selects the overview
- # and infra stops.
- base = build_tour(
- parsed_files,
- ctx.pagerank,
- _file_import_edges(graph_builder),
- file_page_paths=[] if ctx.graph_mode == "structural" else walk_universe,
- # Infra files (Docker/CI/etc.) close the tour; everything else is code.
- infra_paths=[p for p in ctx.paths if ctx.type_by_path.get(p) in {"service", "pipeline"}],
- repo_name=project_name,
- max_stops=DEFAULT_MAX_STOPS,
- graph_mode=ctx.graph_mode,
- anchor_rank=_anchor_fanout_rank(graph_builder),
- )
+ base = _base_tour(ctx, parsed_files, graph_builder, walk_universe, project_name)
- overview = [s for s in base if s.kind == "overview"]
- infra = [s for s in base if s.kind == "infra"]
- base_code = {s.target_path: s for s in base if s.kind == "code"}
+ overview, infra, base_code = _split_base_tour(base)
if not overview:
overview_target = None
@@ -399,18 +392,9 @@ def _curate_tour(
# Structure, not flow: evidence-ranked anchor + one face per
# top-level code area. No layer-coverage swaps — the directory walk
# IS the diversity, and "most depended-on" claims need edges.
- walk, structural_reasons = _structural_walk(
- walk_universe,
- ctx.type_by_path,
- ctx.dominant_lang,
- ctx.pagerank,
- graph_builder,
- project_name=project_name,
- )
- walk = walk[:budget]
- flow = _FlowWalk(walk=walk)
+ walk, reasons = _structural_walk(walk_universe, ctx, graph_builder, project_name)
+ flow = _FlowWalk(walk=walk[:budget], structural_reasons=reasons)
else:
- structural_reasons = {}
flow = _flow_walk(
ctx, base, base_code, walk_universe, overview_target, budget, hotspot_commits
)
@@ -419,21 +403,61 @@ def _curate_tour(
tour: list[dict] = []
if overview:
tour.append(_overview_step(overview[0], readme, ctx.file_layers))
- walk_steps, max_depth = _walk_steps(
- flow, structural_reasons, base_code, ctx, first_order=len(tour) + 1
- )
+ walk_steps, max_depth = _walk_steps(flow, base_code, ctx, first_order=len(tour) + 1)
tour.extend(walk_steps)
tour.extend(
_closing_steps(closing_paths, ctx, first_order=len(tour) + 1, depth_after=max_depth)
)
- for s in infra:
- step = s.as_dict()
- step["order"] = len(tour) + 1
- step["layer_id"] = f"layer:{_slugify(ctx.file_layers.get(s.target_path, 'Config'))}"
- tour.append(step)
+ tour.extend(_infra_steps(infra, ctx, first_order=len(tour) + 1))
return tour
+def _split_base_tour(base: list[Any]) -> tuple[list[Any], list[Any], dict[str, Any]]:
+ """``build_tour``'s overview stops, infra stops, and code stops by path."""
+ overview = [s for s in base if s.kind == "overview"]
+ infra = [s for s in base if s.kind == "infra"]
+ base_code = {s.target_path: s for s in base if s.kind == "code"}
+ return overview, infra, base_code
+
+
+def _walk_universe(ctx: _TourContext, overview_target: str | None) -> list[str]:
+ """Files the walk may visit.
+
+ The README is the overview stop, so it stays out of the walk. Tests and
+ examples are excluded before build_tour spends its step budget on them.
+ """
+ return [
+ p
+ for p in ctx.paths
+ if p != overview_target and not ctx.off_the_walk(p) and not _in_dot_dir(p)
+ ]
+
+
+def _base_tour(
+ ctx: _TourContext,
+ parsed_files: list[Any],
+ graph_builder: Any,
+ walk_universe: list[str],
+ project_name: str,
+) -> list[Any]:
+ """:func:`build_tour`'s overview, execution-ordered code and infra stops."""
+ # In structural mode the BFS walk is withheld entirely (a fake flow over
+ # a near-edgeless graph is a lie); build_tour still selects the overview
+ # and infra stops.
+ return build_tour(
+ parsed_files,
+ ctx.pagerank,
+ _file_import_edges(graph_builder),
+ file_page_paths=[] if ctx.graph_mode == "structural" else walk_universe,
+ # Infra files (Docker/CI/etc.) close the tour; everything else is code.
+ infra_paths=[p for p in ctx.paths if ctx.type_by_path.get(p) in {"service", "pipeline"}],
+ repo_name=project_name,
+ max_stops=DEFAULT_MAX_STOPS,
+ graph_mode=ctx.graph_mode,
+ anchor_rank=_anchor_fanout_rank(graph_builder),
+ )
+
+
@dataclass
class _TourContext:
"""Per-file facts every stage of the tour reads."""
@@ -451,6 +475,10 @@ class _TourContext:
barrels: set[str]
by_layer: dict[str, list[str]]
+ def off_the_walk(self, path: str) -> bool:
+ """Tests and support files (examples, fixtures) never take a walk slot."""
+ return self.file_layers.get(path) in ADJACENT_LAYERS or is_support_path(path)
+
@classmethod
def build(
cls,
@@ -534,6 +562,25 @@ def _suite_face(cands: list[str], ctx: _TourContext, harness_in: Counter[str]) -
)
if anchors:
return anchors[0]
+ code_cands = _suite_code_candidates(cands, ctx, harness_in)
+ if not code_cands:
+ return _best_in_layer(cands, ctx.rank, ctx.pagerank)
+ # Prefer the dominant language, then the shallowest file, then PageRank.
+ return min(
+ code_cands,
+ key=lambda p: (
+ ctx.lang_by_path.get(p, "") != ctx.dominant_lang,
+ len(PurePosixPath(p).parts),
+ -ctx.pagerank.get(p, 0.0),
+ p,
+ ),
+ )
+
+
+def _suite_code_candidates(
+ cands: list[str], ctx: _TourContext, harness_in: Counter[str]
+) -> list[str]:
+ """The suite's code files, narrowed to non-harness and test-project files."""
code_cands = [
p
for p in cands
@@ -549,20 +596,12 @@ def _suite_face(cands: list[str], ctx: _TourContext, harness_in: Counter[str]) -
code_cands = non_harness
# When the repo declares test projects (Foo.Tests/), the suite lives there.
in_test_project = [p for p in code_cands if _in_test_project(p)]
- if in_test_project:
- code_cands = in_test_project
- if not code_cands:
- return _best_in_layer(cands, ctx.rank, ctx.pagerank)
- # Prefer the dominant language, then the shallowest file, then PageRank.
- return min(
- code_cands,
- key=lambda p: (
- ctx.lang_by_path.get(p, "") != ctx.dominant_lang,
- len(PurePosixPath(p).parts),
- -ctx.pagerank.get(p, 0.0),
- p,
- ),
- )
+ return in_test_project or code_cands
+
+
+def _in_dot_dir(path: str) -> bool:
+ """Dot-dir tooling (``.github/``, ``.vscode/``) never stands in the walk."""
+ return PurePosixPath(path).parts[0].startswith(".")
def _in_test_project(path: str) -> bool:
@@ -579,6 +618,7 @@ class _FlowWalk:
walk: list[str]
swapped_depth: dict[str, int] = field(default_factory=dict) # rep -> depth of its slot
hotspot_added: str | None = None # churn hotspot given a reserved slot
+ structural_reasons: dict[str, str] = field(default_factory=dict) # structural-mode stops
def _flow_walk(
@@ -596,29 +636,10 @@ def _flow_walk(
example programs (documentation-by-code, not the system), truncated up
front so later swaps land inside the kept window.
"""
- walk_all = [
- s.target_path
- for s in base
- if s.kind == "code"
- and s.target_path != overview_target
- and ctx.file_layers.get(s.target_path) not in ADJACENT_LAYERS
- and not is_support_path(s.target_path)
- ]
+ code_order = _flow_code_order(ctx, base, overview_target)
# A churn hotspot off the import path earns one reserved slot, picked from
# the whole code universe; without git history the map is empty.
- hotspot_path: str | None = None
- if hotspot_commits:
- hotspot_pool = [
- p
- for p in walk_universe
- if p not in ctx.barrels
- and ctx.file_layers.get(p) not in ADJACENT_LAYERS
- and ctx.type_by_path.get(p) not in {"config", "document"}
- ]
- hotspot_path = select_hotspot_stop(hotspot_pool, hotspot_commits)
- # One re-export barrel earns a stop; the rest are demoted so real code
- # fills the budget instead of a run of identical "public surface" hubs.
- code_order = _drop_extra_barrels(walk_all, ctx.barrels)
+ hotspot_path = _hotspot_stop(ctx, walk_universe, hotspot_commits)
reserve = 1 if (hotspot_path is not None and hotspot_path not in code_order[:budget]) else 0
flow = _FlowWalk(walk=code_order[: max(0, budget - reserve)])
@@ -631,6 +652,34 @@ def _flow_walk(
return flow
+def _flow_code_order(ctx: _TourContext, base: list[Any], overview_target: str | None) -> list[str]:
+ walk_all = [
+ s.target_path
+ for s in base
+ if s.kind == "code"
+ and s.target_path != overview_target
+ and not ctx.off_the_walk(s.target_path)
+ ]
+ # One re-export barrel earns a stop; the rest are demoted so real code
+ # fills the budget instead of a run of identical "public surface" hubs.
+ return _drop_extra_barrels(walk_all, ctx.barrels)
+
+
+def _hotspot_stop(
+ ctx: _TourContext, walk_universe: list[str], hotspot_commits: dict[str, int] | None
+) -> str | None:
+ if not hotspot_commits:
+ return None
+ hotspot_pool = [
+ p
+ for p in walk_universe
+ if p not in ctx.barrels
+ and ctx.file_layers.get(p) not in ADJACENT_LAYERS
+ and ctx.type_by_path.get(p) not in {"config", "document"}
+ ]
+ return select_hotspot_stop(hotspot_pool, hotspot_commits)
+
+
def _diversify_layers(
flow: _FlowWalk,
ctx: _TourContext,
@@ -642,15 +691,7 @@ def _diversify_layers(
Swaps slots, never re-sorts, so the walk keeps its execution order.
"""
walk = flow.walk
- seen_layers: set[str] = set()
- redundant_positions: list[int] = []
- for i, p in enumerate(walk):
- layer = ctx.file_layers.get(p)
- if layer in seen_layers:
- redundant_positions.append(i)
- else:
- seen_layers.add(layer)
-
+ seen_layers, redundant_positions = _layer_repeats(walk, ctx)
uncovered = [
name for name in ctx.order if name not in seen_layers and name not in ADJACENT_LAYERS
]
@@ -667,36 +708,55 @@ def _diversify_layers(
seen_layers.add(layer)
+def _layer_repeats(walk: list[str], ctx: _TourContext) -> tuple[set[str], list[int]]:
+ """The layers *walk* covers, and the positions that repeat a covered layer."""
+ seen_layers: set[str] = set()
+ redundant_positions: list[int] = []
+ for i, p in enumerate(walk):
+ layer = ctx.file_layers.get(p)
+ if layer in seen_layers:
+ redundant_positions.append(i)
+ else:
+ seen_layers.add(layer)
+ return seen_layers, redundant_positions
+
+
def _layer_face(
layer: str, ctx: _TourContext, walk: list[str], overview_target: str | None
) -> str | None:
"""The stop that represents *layer* in the walk, or None if it has no face."""
- # Manifests describe the project rather than implement it: never a face.
manifest_names = _LANG_REGISTRY.manifest_filenames()
+ taken = {*walk, overview_target}
candidates = [
p
for p in ctx.by_layer.get(layer, [])
- if p not in walk
- and p != overview_target
- and not is_support_path(p)
- and p not in ctx.barrels # a re-export shell is never a layer's face
- and not PurePosixPath(p).parts[0].startswith(".") # never a layer face
- and PurePosixPath(p).name not in manifest_names
+ if p not in taken and _may_face_a_layer(p, ctx, manifest_names)
]
if not candidates:
return None
# A face must be code (not config, docs or infra scripts), except for the
# Config layer itself.
+ code_candidates = _code_only(candidates, ctx)
+ if not code_candidates and layer != "Config":
+ return None
+ return _best_in_layer(code_candidates or candidates, ctx.rank, ctx.pagerank)
+
+
+def _code_only(paths: list[str], ctx: _TourContext) -> list[str]:
infra_langs = _LANG_REGISTRY.infra_languages()
- code_candidates = [
+ return [
p
- for p in candidates
+ for p in paths
if ctx.type_by_path.get(p) not in {"config", "document"}
and ctx.lang_by_path.get(p) not in infra_langs
]
- if not code_candidates and layer != "Config":
- return None
- return _best_in_layer(code_candidates or candidates, ctx.rank, ctx.pagerank)
+
+
+def _may_face_a_layer(path: str, ctx: _TourContext, manifest_names: frozenset[str]) -> bool:
+ """Support files, re-export shells, dot-dir tooling and manifests never face a layer."""
+ if is_support_path(path) or path in ctx.barrels or _in_dot_dir(path):
+ return False
+ return PurePosixPath(path).name not in manifest_names
def _overview_step(overview: Any, readme: dict | None, file_layers: dict[str, str]) -> dict:
@@ -713,7 +773,6 @@ def _overview_step(overview: Any, readme: dict | None, file_layers: dict[str, st
def _walk_steps(
flow: _FlowWalk,
- structural_reasons: dict[str, str],
base_code: dict[str, Any],
ctx: _TourContext,
*,
@@ -724,7 +783,7 @@ def _walk_steps(
max_depth = 0
for order_n, p in enumerate(flow.walk, start=first_order):
layer = ctx.file_layers.get(p, "")
- depth, reason = _walk_step_basis(p, layer, flow, structural_reasons, base_code)
+ depth, reason = _walk_step_basis(p, layer, flow, base_code)
if p in ctx.barrels:
# A re-export shell may seed the walk (imports genuinely fan out
# from it), but it must not claim to be an execution entry point.
@@ -749,13 +808,12 @@ def _walk_step_basis(
path: str,
layer: str,
flow: _FlowWalk,
- structural_reasons: dict[str, str],
base_code: dict[str, Any],
) -> tuple[int, str]:
"""``(depth, reason)`` for one walk stop, by how it earned its place."""
- if path in structural_reasons:
+ if path in flow.structural_reasons:
# Import depth is meaningless without an import graph.
- return 0, structural_reasons[path]
+ return 0, flow.structural_reasons[path]
if path in flow.swapped_depth:
return flow.swapped_depth[path], f"The {layer} layer's anchor — its most depended-on file."
if path == flow.hotspot_added:
@@ -789,6 +847,16 @@ def _closing_steps(
]
+def _infra_steps(infra: list[Any], ctx: _TourContext, *, first_order: int) -> list[dict]:
+ steps: list[dict] = []
+ for order_n, s in enumerate(infra, start=first_order):
+ step = s.as_dict()
+ step["order"] = order_n
+ step["layer_id"] = f"layer:{_slugify(ctx.file_layers.get(s.target_path, 'Config'))}"
+ steps.append(step)
+ return steps
+
+
def _closing_reason(ctx: _TourContext) -> str:
"""The closing stops' reason, naming other sizeable languages' suites.
@@ -796,6 +864,19 @@ def _closing_reason(ctx: _TourContext) -> str:
files get named in the closing-stop reason — the stop faces the dominant
suite, but the others must not vanish.
"""
+ other_suites = _other_suite_names(ctx)
+ if not other_suites:
+ return "The test suite — how the system's behavior is verified."
+ return (
+ "The test suite — how the system's behavior is verified "
+ f"(the {' and '.join(other_suites)} test suite"
+ f"{'s' if len(other_suites) > 1 else ''} live"
+ f"{'' if len(other_suites) > 1 else 's'} alongside it)."
+ )
+
+
+def _other_suite_names(ctx: _TourContext) -> list[str]:
+ """Display names of non-dominant languages with >= 20% of the code and tests."""
lang_counts = Counter(ctx.code_langs)
total_code = sum(lang_counts.values()) or 1
test_langs = {
@@ -803,19 +884,13 @@ def _closing_reason(ctx: _TourContext) -> str:
for layer in ADJACENT_LAYERS
for p in ctx.by_layer.get(layer, [])
}
- other_suites = sorted(
- spec.display_name
+ sizeable = [
+ tag
for tag, n in lang_counts.items()
- if tag != ctx.dominant_lang
- and n / total_code >= 0.20
- and tag in test_langs
- and (spec := _LANG_REGISTRY.get(tag)) is not None
- )
- if not other_suites:
- return "The test suite — how the system's behavior is verified."
- return (
- "The test suite — how the system's behavior is verified "
- f"(the {' and '.join(other_suites)} test suite"
- f"{'s' if len(other_suites) > 1 else ''} live"
- f"{'' if len(other_suites) > 1 else 's'} alongside it)."
+ if tag != ctx.dominant_lang and n / total_code >= 0.20
+ ]
+ return sorted(
+ spec.display_name
+ for tag in sizeable
+ if tag in test_langs and (spec := _LANG_REGISTRY.get(tag)) is not None
)