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(kg): route docs/tooling out of the layer catch-all and add an invariant reviewer gate (#575)

Raghav Chamadiyaa8cb6fc9314b
diff --git a/packages/core/src/repowise/core/analysis/kg_curation.py b/packages/core/src/repowise/core/analysis/kg_curation.py
index 88e770868..648a43329 100644
--- a/packages/core/src/repowise/core/analysis/kg_curation.py
+++ b/packages/core/src/repowise/core/analysis/kg_curation.py
@@ -50,6 +50,7 @@ from repowise.core.generation.tour import (
score_entry_points,
select_hotspot_stop,
)
+from repowise.core.generation.well_known_files import well_known_role
from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
# Closing-stop anchors (conftest, spec_helper, test_helper, …) and
@@ -1625,16 +1626,27 @@ def _cheap_summary(node: dict, parsed_file: Any | None) -> str:
if "barrel" in tags:
return f"Re-export barrel for {parent}/."
+
+ name = PurePosixPath(path).name
+ if node_type in {"pipeline", "service", "schema", "config", "document"} or (
+ tags and ({"ci", "infra", "data", "config"} & set(tags))
+ ):
+ # Recognised scaffolding earns a real role instead of a bare name
+ # restatement; only genuinely opaque support files fall back to the
+ # type template below.
+ role = well_known_role(path)
+ if role is not None:
+ return role
if node_type == "pipeline" or "ci" in tags:
- return f"CI / pipeline definition: {PurePosixPath(path).name}."
+ return f"CI / pipeline definition: {name}."
if node_type == "service" or "infra" in tags:
- return f"Infrastructure definition: {PurePosixPath(path).name}."
+ return f"Infrastructure definition: {name}."
if node_type == "schema" or "data" in tags:
- return f"Data / schema definition: {PurePosixPath(path).name}."
+ return f"Data / schema definition: {name}."
if node_type == "config" or "config" in tags:
- return f"Configuration file: {PurePosixPath(path).name}."
+ return f"Configuration file: {name}."
if node_type == "document":
- return f"Documentation: {PurePosixPath(path).name}."
+ return f"Documentation: {name}."
if "test" in tags:
return f"Tests for {_infer_test_target(path)}."
diff --git a/packages/core/src/repowise/core/generation/kg_reviewer/__init__.py b/packages/core/src/repowise/core/generation/kg_reviewer/__init__.py
new file mode 100644
index 000000000..384f3e923
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/kg_reviewer/__init__.py
@@ -0,0 +1,21 @@
+"""Deterministic invariant reviewer for the generated knowledge graph.
+
+A zero-LLM, zero-DB gate that validates the in-memory KG (layers, tour, node
+summaries) against hard structural invariants and soft quality signals before it
+is persisted. See :mod:`checks` for the individual ``check_*`` functions,
+:mod:`runner` for the gate (:func:`run_review` / :func:`apply_review`), and
+:mod:`findings` for the report types.
+"""
+
+from __future__ import annotations
+
+from .findings import Finding, ReviewReport, Severity
+from .runner import apply_review, run_review
+
+__all__ = [
+ "Finding",
+ "ReviewReport",
+ "Severity",
+ "apply_review",
+ "run_review",
+]
diff --git a/packages/core/src/repowise/core/generation/kg_reviewer/checks.py b/packages/core/src/repowise/core/generation/kg_reviewer/checks.py
new file mode 100644
index 000000000..e5afb744e
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/kg_reviewer/checks.py
@@ -0,0 +1,250 @@
+"""Independent invariant checks for the generated knowledge graph.
+
+Each ``check_*`` is a pure function over in-memory KG objects (plain dicts and
+lists — no DB, no LLM, no I/O) returning a list of :class:`Finding`. They are
+deliberately decoupled: a check never reaches into another's state, so each can
+be unit-tested against a small fixture graph in isolation and the runner simply
+concatenates their output.
+
+Node/layer/tour shapes follow ``analysis.knowledge_graph.KnowledgeGraphResult``:
+a file node is a dict with ``id`` (``"file:<path>"``), ``filePath``, ``summary``,
+``type``, and ``tags``; a layer has ``id``, ``name``, ``nodeIds``; a tour step
+has ``order``, ``title``, ``target_path``/``nodeIds``, and ``reason``.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter, defaultdict
+from pathlib import PurePosixPath
+
+from .findings import Finding, Severity
+
+# Structural / type words that carry no information beyond the file's name and
+# extension. A support-file summary built only from these plus the filename is a
+# restatement, not a description.
+_GENERIC_SUMMARY_WORDS = frozenset({
+ "file", "files", "configuration", "config", "documentation", "document",
+ "definition", "infrastructure", "infra", "data", "schema", "ci", "pipeline",
+ "module", "repository", "the", "a", "an", "for", "of", "and", "to", "in",
+ "on", "with", "this", "is", "as", "or",
+})
+
+# Node types / tags whose summaries are deterministic type templates (the
+# support files). Code-module and test summaries are judged elsewhere; this
+# check targets the config/doc/infra restatements specifically.
+_SUPPORT_TYPES = frozenset({"config", "document", "schema", "service", "pipeline"})
+_SUPPORT_TAGS = frozenset({"ci", "infra", "data", "config"})
+
+# Category words in a layer name that assert a specific runtime role. If none of
+# the layer's files actually live under a directory of that name, the label is a
+# category error (e.g. a plugin/config bucket named "...Middleware").
+_RUNTIME_CATEGORY_WORDS = frozenset({
+ "middleware", "controller", "controllers", "repository", "repositories",
+ "interceptor", "interceptors", "guard", "guards",
+})
+
+_WORD_RE = re.compile(r"[a-z0-9]+")
+
+
+def _is_file_node(node: dict) -> bool:
+ # Matches analysis.kg_curation._file_nodes: only ``file:``-prefixed nodes
+ # are file-level. Symbol nodes (``function:``/``class:``) also carry a
+ # filePath but are not part of the layer partition, so they must not count.
+ nid = node.get("id")
+ return isinstance(nid, str) and nid.startswith("file:") and isinstance(
+ node.get("filePath"), str
+ )
+
+
+def _node_path(node: dict) -> str:
+ return node.get("filePath") or node.get("id", "").removeprefix("file:")
+
+
+def _words(text: str) -> list[str]:
+ return _WORD_RE.findall((text or "").lower())
+
+
+def _normalize_reason(reason: str) -> str:
+ return " ".join(_words(reason))
+
+
+def check_summaries_restate_filename(nodes: list[dict]) -> list[Finding]:
+ """Flag support-file summaries that merely restate the filename / type.
+
+ A summary is a restatement when, after removing the file's own name tokens
+ and generic structural words ("configuration", "file", …), nothing
+ descriptive remains. Scoped to support-file node types so genuine code and
+ test summaries are not penalised. Severity WARNING: the floor guarantees a
+ summary exists, so these are surfaced for suppression, never dropped.
+ """
+ findings: list[Finding] = []
+ for node in nodes:
+ summary = (node.get("summary") or "").strip()
+ if not summary:
+ continue
+ node_type = node.get("type", "file")
+ tags = set(node.get("tags") or [])
+ if node_type not in _SUPPORT_TYPES and not (tags & _SUPPORT_TAGS):
+ continue
+
+ path = _node_path(node)
+ name_tokens = set(_words(PurePosixPath(path).name))
+ content = [
+ w for w in _words(summary)
+ if w not in _GENERIC_SUMMARY_WORDS and w not in name_tokens
+ ]
+ if not content:
+ findings.append(Finding(
+ check="summary_restates_filename",
+ severity=Severity.WARNING,
+ message=f"summary restates the filename: {summary!r}",
+ target=node.get("id", path),
+ ))
+ return findings
+
+
+def check_tour_reasons_distinct(tour: list[dict]) -> list[Finding]:
+ """Flag tour steps that share a near-identical reason.
+
+ Near-identical = the same reason after lowercasing and collapsing
+ whitespace/punctuation. Identical rationales are the structural signature of
+ duplicate/barrel stops, so each shared reason yields one WARNING naming the
+ colliding steps.
+ """
+ findings: list[Finding] = []
+ by_reason: dict[str, list[dict]] = defaultdict(list)
+ for step in tour:
+ norm = _normalize_reason(step.get("reason", ""))
+ if norm:
+ by_reason[norm].append(step)
+ for norm, steps in by_reason.items():
+ if len(steps) > 1:
+ targets = [s.get("target_path") or s.get("title") or "?" for s in steps]
+ findings.append(Finding(
+ check="tour_reasons_distinct",
+ severity=Severity.WARNING,
+ message=f"{len(steps)} tour steps share a near-identical reason",
+ target=", ".join(targets),
+ detail={"reason": norm, "steps": targets},
+ ))
+ return findings
+
+
+def check_layer_partition(layers: list[dict], nodes: list[dict]) -> list[Finding]:
+ """Every file-level node belongs to exactly one layer.
+
+ CRITICAL: a node in two layers, a file with no layer, or a layer referencing
+ an unknown id all break the partition the rest of the UI assumes.
+ """
+ findings: list[Finding] = []
+ file_ids = {n["id"] for n in nodes if _is_file_node(n) and n.get("id")}
+
+ membership: Counter[str] = Counter()
+ unknown: set[str] = set()
+ for layer in layers:
+ for nid in layer.get("nodeIds", []):
+ membership[nid] += 1
+ if nid not in file_ids:
+ unknown.add(nid)
+
+ duplicated = [nid for nid, c in membership.items() if c > 1]
+ if duplicated:
+ findings.append(Finding(
+ check="layer_partition",
+ severity=Severity.CRITICAL,
+ message=f"{len(duplicated)} node(s) appear in more than one layer",
+ detail={"sample": sorted(duplicated)[:10]},
+ ))
+ missing = [nid for nid in file_ids if nid not in membership]
+ if missing:
+ findings.append(Finding(
+ check="layer_partition",
+ severity=Severity.CRITICAL,
+ message=f"{len(missing)} file node(s) belong to no layer",
+ detail={"sample": sorted(missing)[:10]},
+ ))
+ if unknown:
+ findings.append(Finding(
+ check="layer_partition",
+ severity=Severity.CRITICAL,
+ message=f"{len(unknown)} layer member id(s) are not known file nodes",
+ detail={"sample": sorted(unknown)[:10]},
+ ))
+ return findings
+
+
+def check_tour_sequential(tour: list[dict]) -> list[Finding]:
+ """Tour steps are contiguously ordered and each points at a real page.
+
+ CRITICAL: a gap or duplicate in the order sequence, or a step with neither a
+ target nor a title, leaves the rendered tour broken.
+ """
+ findings: list[Finding] = []
+ if not tour:
+ return findings
+
+ orders = [s.get("order") for s in tour]
+ if any(o is None for o in orders):
+ findings.append(Finding(
+ check="tour_sequential",
+ severity=Severity.CRITICAL,
+ message="one or more tour steps have no order",
+ ))
+ else:
+ start = min(orders)
+ expected = set(range(start, start + len(orders)))
+ if set(orders) != expected or len(set(orders)) != len(orders):
+ findings.append(Finding(
+ check="tour_sequential",
+ severity=Severity.CRITICAL,
+ message="tour order is not a contiguous, gap-free sequence",
+ detail={"orders": orders},
+ ))
+
+ for step in tour:
+ target = step.get("target_path") or step.get("nodeIds")
+ title = (step.get("title") or "").strip()
+ if not target and not title:
+ findings.append(Finding(
+ check="tour_sequential",
+ severity=Severity.CRITICAL,
+ message="tour step has neither a target nor a title",
+ target=str(step.get("order", "?")),
+ ))
+ return findings
+
+
+def check_layer_name_category(layers: list[dict], nodes: list[dict]) -> list[Finding]:
+ """A layer name may not assert a runtime category its files do not live in.
+
+ If a layer is named for a category word (middleware, controller, …) but no
+ member file sits under a directory of that name, the label is a category
+ error. WARNING: the name is LLM-generated, so this is surfaced rather than
+ rewritten.
+ """
+ findings: list[Finding] = []
+ path_by_id = {n["id"]: _node_path(n) for n in nodes if n.get("id")}
+ for layer in layers:
+ name_words = set(_words(layer.get("name", "")))
+ claimed = name_words & _RUNTIME_CATEGORY_WORDS
+ if not claimed:
+ continue
+ member_segments: set[str] = set()
+ for nid in layer.get("nodeIds", []):
+ path = path_by_id.get(nid, "")
+ member_segments.update(s.lower() for s in PurePosixPath(path).parts[:-1])
+ for word in sorted(claimed):
+ # "repositories" -> "repository", "controllers" -> "controller".
+ singular = word[:-3] + "y" if word.endswith("ies") else word.rstrip("s")
+ if word not in member_segments and singular not in member_segments:
+ findings.append(Finding(
+ check="layer_name_category",
+ severity=Severity.WARNING,
+ message=(
+ f"layer {layer.get('name')!r} names category {word!r} "
+ "but no member file lives under such a directory"
+ ),
+ target=layer.get("id", ""),
+ ))
+ return findings
diff --git a/packages/core/src/repowise/core/generation/kg_reviewer/findings.py b/packages/core/src/repowise/core/generation/kg_reviewer/findings.py
new file mode 100644
index 000000000..e2ebec00d
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/kg_reviewer/findings.py
@@ -0,0 +1,81 @@
+"""Finding and report types for the KG invariant reviewer.
+
+Plain data, no behaviour: the reviewer's :mod:`checks` return lists of
+:class:`Finding`, and the :mod:`runner` aggregates them into a
+:class:`ReviewReport`. Kept separate from the checks so a consumer can depend on
+the report shape without importing the check logic.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from enum import StrEnum
+from typing import Any
+
+
+class Severity(StrEnum):
+ """How a violated invariant is handled by the gate.
+
+ ``CRITICAL`` invariants are structural guarantees (partition, sequential
+ tour) — a violation means the offending item is dropped/blocked. ``WARNING``
+ invariants are quality signals (low-signal summary, duplicate reason) —
+ logged and surfaced, never silently dropped.
+ """
+
+ CRITICAL = "critical"
+ WARNING = "warning"
+
+
+@dataclass(frozen=True)
+class Finding:
+ """One violated invariant against one item of the generated KG."""
+
+ check: str
+ severity: Severity
+ message: str
+ target: str = "" # node/layer/tour id or path the finding is about
+ detail: dict[str, Any] = field(default_factory=dict)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "check": self.check,
+ "severity": self.severity.value,
+ "message": self.message,
+ "target": self.target,
+ "detail": self.detail,
+ }
+
+
+@dataclass
+class ReviewReport:
+ """Aggregated outcome of a reviewer run."""
+
+ findings: list[Finding] = field(default_factory=list)
+
+ @property
+ def criticals(self) -> list[Finding]:
+ return [f for f in self.findings if f.severity is Severity.CRITICAL]
+
+ @property
+ def warnings(self) -> list[Finding]:
+ return [f for f in self.findings if f.severity is Severity.WARNING]
+
+ @property
+ def ok(self) -> bool:
+ """True when no critical invariant was violated."""
+ return not self.criticals
+
+ def counts_by_check(self) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for f in self.findings:
+ counts[f.check] = counts.get(f.check, 0) + 1
+ return counts
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "ok": self.ok,
+ "critical_count": len(self.criticals),
+ "warning_count": len(self.warnings),
+ "counts_by_check": self.counts_by_check(),
+ "findings": [f.as_dict() for f in self.findings],
+ }
diff --git a/packages/core/src/repowise/core/generation/kg_reviewer/runner.py b/packages/core/src/repowise/core/generation/kg_reviewer/runner.py
new file mode 100644
index 000000000..f3f644d49
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/kg_reviewer/runner.py
@@ -0,0 +1,87 @@
+"""Thin runner that drives the invariant checks and applies the gate.
+
+:func:`run_review` is pure — it runs every check over a KG object and returns a
+:class:`ReviewReport`. :func:`apply_review` is the post-generation gate wired
+into the pipeline: it runs the review, applies the bounded actions (tag
+low-signal summaries for downstream suppression; log a structured summary), and
+returns the report. There is no regeneration loop — the gate validates and
+annotates the already-generated artifact exactly once.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+from . import checks
+from .findings import ReviewReport
+
+logger = structlog.get_logger(__name__)
+
+
+def _kg_parts(kg: Any) -> tuple[list[dict], list[dict], list[dict]]:
+ """Extract (nodes, layers, tour) from a KnowledgeGraphResult-like object."""
+ nodes = list(getattr(kg, "nodes", None) or [])
+ layers = list(getattr(kg, "layers", None) or [])
+ tour = list(getattr(kg, "tour", None) or [])
+ return nodes, layers, tour
+
+
+def run_review(kg: Any) -> ReviewReport:
+ """Run every invariant check over *kg* and aggregate the findings.
+
+ Pure and side-effect free. *kg* is any object exposing ``nodes``,
+ ``layers``, and ``tour`` (the in-memory ``KnowledgeGraphResult``).
+ """
+ nodes, layers, tour = _kg_parts(kg)
+ findings = [
+ *checks.check_summaries_restate_filename(nodes),
+ *checks.check_tour_reasons_distinct(tour),
+ *checks.check_layer_partition(layers, nodes),
+ *checks.check_tour_sequential(tour),
+ *checks.check_layer_name_category(layers, nodes),
+ ]
+ return ReviewReport(findings=findings)
+
+
+def apply_review(kg: Any) -> ReviewReport:
+ """Gate: review *kg*, apply bounded actions, and log a structured summary.
+
+ Actions are deliberately bounded (no regeneration):
+
+ * **WARNING / ``summary_restates_filename``** — tag the node
+ ``low_signal_summary`` (additive) so downstream surfaces can suppress the
+ restatement without violating the never-empty-summary floor.
+ * **CRITICAL** — logged at error level. These are structural guarantees the
+ curator already enforces by construction, so a hit signals a real
+ regression rather than something the gate should silently rewrite.
+ """
+ report = run_review(kg)
+
+ nodes_by_id = {n.get("id"): n for n in getattr(kg, "nodes", None) or []}
+ tagged = 0
+ for finding in report.findings:
+ if finding.check == "summary_restates_filename":
+ node = nodes_by_id.get(finding.target)
+ if node is not None:
+ tags = node.setdefault("tags", [])
+ if "low_signal_summary" not in tags:
+ tags.append("low_signal_summary")
+ tagged += 1
+
+ if report.criticals:
+ logger.error(
+ "kg_reviewer_critical",
+ count=len(report.criticals),
+ findings=[f.message for f in report.criticals],
+ )
+ logger.info(
+ "kg_reviewer_summary",
+ ok=report.ok,
+ critical=len(report.criticals),
+ warning=len(report.warnings),
+ low_signal_summaries_tagged=tagged,
+ counts=report.counts_by_check(),
+ )
+ return report
diff --git a/packages/core/src/repowise/core/generation/knowledge_graph.py b/packages/core/src/repowise/core/generation/knowledge_graph.py
index a6ed626e0..e42386ed4 100644
--- a/packages/core/src/repowise/core/generation/knowledge_graph.py
+++ b/packages/core/src/repowise/core/generation/knowledge_graph.py
@@ -89,6 +89,18 @@ async def enrich_knowledge_graph(
kg_skeleton.layers = enriched_layers
kg_skeleton.tour = tour
+
+ # Post-generation invariant gate: validate the fully-assembled KG (layers,
+ # tour, summaries) against hard invariants and quality signals before it is
+ # persisted. Deterministic, zero-LLM, bounded (no regeneration loop) —
+ # tags low-signal summaries and surfaces any structural regression.
+ try:
+ from repowise.core.generation.kg_reviewer import apply_review
+
+ apply_review(kg_skeleton)
+ except Exception as exc: # pragma: no cover - defensive, never blocks export
+ logger.warning("kg_reviewer_failed", error=str(exc))
+
return kg_skeleton
@@ -177,6 +189,11 @@ def _build_layer_naming_prompt(
lines = [
"Assign a concise semantic name (2-4 words) and a one-sentence description "
"to each code community below.",
+ "The name must describe what the *majority* of the community's files do. "
+ "The heuristic label is only a hint — do not reuse an architectural "
+ "category word (e.g. middleware, service, controller, repository) unless "
+ "it accurately fits the files; a docs/config/tooling group must not be "
+ "named for a runtime category it does not belong to.",
"",
f"Tech stack: {', '.join(tech_names) if tech_names else 'unknown'}",
f"Entry points: {', '.join(entry_points) if entry_points else 'none detected'}",
diff --git a/packages/core/src/repowise/core/generation/layers.py b/packages/core/src/repowise/core/generation/layers.py
index 5084b1be9..e6096d83f 100644
--- a/packages/core/src/repowise/core/generation/layers.py
+++ b/packages/core/src/repowise/core/generation/layers.py
@@ -208,6 +208,24 @@ def is_support_path(path: str) -> bool:
for s in PurePosixPath(path).parts[:-1]
)
+
+# Build / CI / extension tooling directories: scripts, container definitions,
+# and agent/editor plugin trees. Like the doc and example dirs above, these
+# support the project without being part of its runtime architecture, so they
+# must not swell the application catch-all or borrow a runtime category. A
+# top-level ``plugins/`` tree holds editor/agent extension manifests far more
+# often than request-pipeline middleware (genuine middleware lives under
+# ``middleware/``), so it is routed here rather than to the Middleware layer.
+_TOOLING_DIR_TOKENS = frozenset({"scripts", "script", "docker", "plugins"})
+
+# The single non-architectural support bucket. Every doc/example/benchmark and
+# build/CI/extension-tooling file lands here instead of the runtime layers, so
+# the architectural layers describe the system and only the system.
+DOCS_TOOLING_LAYER = "Docs & Tooling"
+
+# Directory-name tokens that route a file to :data:`DOCS_TOOLING_LAYER`.
+_NON_ARCH_DIR_TOKENS = _EXAMPLE_DIR_TOKENS | _DOC_DIR_TOKENS | _TOOLING_DIR_TOKENS
+
# Fallback layer for files whose path matches no hint (root scripts, etc.).
DEFAULT_LAYER = "Application"
@@ -226,9 +244,20 @@ _CANONICAL_RANK: dict[str, int] = {
"Types": 7,
"Config": 8,
"Utility": 9,
- "Test": 10,
+ DOCS_TOOLING_LAYER: 10,
+ "Test": 11,
}
+# Layers pinned after the runtime stack when ordering. Tests (see
+# ADJACENT_LAYERS) and the support bucket both sit outside the runtime
+# dependency race: a script or doc importing core code says nothing about where
+# core sits, and letting them compete would crown the tooling bucket the top
+# "consumer". Distinct from ADJACENT_LAYERS, which also governs entry-point
+# candidacy — a tooling file (scripts/validate.py) may still be a real entry
+# point, so DOCS_TOOLING_LAYER is pinned for ordering only, never excluded from
+# entry points.
+_PINNED_AFTER_RUNTIME: frozenset[str] = ADJACENT_LAYERS | {DOCS_TOOLING_LAYER}
+
def infer_layer(path: str, language: str | None = None) -> str:
"""Return the architectural layer name for *path*.
@@ -280,6 +309,15 @@ def infer_layer(path: str, language: str | None = None) -> str:
if segments and segments[0].startswith("."):
return "Config"
+ # Documentation sites, sample harnesses, and build/CI/extension tooling are
+ # support material, not the runtime architecture. Route the whole subtree
+ # to a single explicit support bucket so docs/scripts/website/plugins never
+ # swell the application catch-all or borrow a runtime category. Checked
+ # before the hint scan: a deeper architectural token inside a tooling tree
+ # (scripts/build/services/…) describes the tooling, not a runtime service.
+ if any(seg in _NON_ARCH_DIR_TOKENS for seg in segments):
+ return DOCS_TOOLING_LAYER
+
lang = (language or "").lower()
token_hints = _LANG_TOKEN_HINTS.get(lang)
path_hints = _LANG_PATH_HINTS.get(lang)
@@ -333,7 +371,7 @@ def layer_order_basis(
ld = file_layers.get(dst)
if not ls or not ld or ls == ld:
continue
- if ls in ADJACENT_LAYERS or ld in ADJACENT_LAYERS:
+ if ls in _PINNED_AFTER_RUNTIME or ld in _PINNED_AFTER_RUNTIME:
continue
return "imports"
return "canonical"
@@ -360,17 +398,18 @@ def compute_layer_order(
the canonical rank so the result is stable on graphs with no clear
direction.
- :data:`ADJACENT_LAYERS` (tests) sit outside the runtime stack: their edges
- are excluded from the race (a test importing a service says nothing about
- where the service sits) and they are appended after the runtime layers in
- canonical-rank order.
+ Layers in :data:`_PINNED_AFTER_RUNTIME` (tests and the Docs & Tooling
+ support bucket) sit outside the runtime stack: their edges are excluded
+ from the race (a test or build script importing a service says nothing
+ about where the service sits) and they are appended after the runtime
+ layers in canonical-rank order.
"""
layers = sorted(set(file_layers.values()))
if len(layers) <= 1:
return layers
- runtime = [layer for layer in layers if layer not in ADJACENT_LAYERS]
- adjacent = [layer for layer in layers if layer in ADJACENT_LAYERS]
+ runtime = [layer for layer in layers if layer not in _PINNED_AFTER_RUNTIME]
+ adjacent = [layer for layer in layers if layer in _PINNED_AFTER_RUNTIME]
out_deg: dict[str, int] = defaultdict(int) # edges leaving the layer
in_deg: dict[str, int] = defaultdict(int) # edges entering the layer
@@ -381,7 +420,7 @@ def compute_layer_order(
ld = file_layers.get(dst)
if not ls or not ld or ls == ld:
continue
- if ls in ADJACENT_LAYERS or ld in ADJACENT_LAYERS:
+ if ls in _PINNED_AFTER_RUNTIME or ld in _PINNED_AFTER_RUNTIME:
continue
out_deg[ls] += 1
in_deg[ld] += 1
diff --git a/packages/core/src/repowise/core/generation/well_known_files.py b/packages/core/src/repowise/core/generation/well_known_files.py
new file mode 100644
index 000000000..f5fb5235d
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/well_known_files.py
@@ -0,0 +1,116 @@
+"""Role descriptions for well-known config/doc/tooling files.
+
+A deterministic, zero-cost lookup that turns a recognised filename into a real
+one-line role ("Python project metadata and build configuration.") instead of a
+bare restatement of its name ("Configuration file: pyproject.toml."). The cheap
+summary floor and any other fallback path consult this first so a reader or
+agent learns what a file *is for* rather than re-reading the name they already
+have.
+
+Pure and side-effect free: a single ``well_known_role(filename)`` lookup keyed
+on the basename, with a small suffix fallback for whole families (lockfiles,
+CI workflow files). Returns ``None`` when the name is not recognised, so callers
+keep their existing fallback for genuinely opaque files.
+"""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+
+# Exact basename (lowercased) -> role sentence. Covers the conventional project
+# scaffolding that shows up in almost every repo, where the filename alone is
+# the whole identity and a "Configuration file: X" summary adds nothing.
+_BY_NAME: dict[str, str] = {
+ # Python packaging / tooling
+ "pyproject.toml": "Python project metadata, dependencies, and build configuration.",
+ "setup.py": "Python package build script (setuptools).",
+ "setup.cfg": "Python packaging and tool configuration.",
+ "requirements.txt": "Pinned Python dependency list.",
+ "tox.ini": "Tox test-automation and environment matrix configuration.",
+ "ruff.toml": "Ruff linter and formatter configuration.",
+ "mypy.ini": "MyPy static type-checking configuration.",
+ "pytest.ini": "Pytest configuration.",
+ "conftest.py": "Shared pytest fixtures and test configuration.",
+ "alembic.ini": "Alembic database-migration configuration.",
+ # Node / JS / TS
+ "package.json": "Node package manifest: dependencies, scripts, and metadata.",
+ "package-lock.json": "Resolved npm dependency lockfile.",
+ "tsconfig.json": "TypeScript compiler configuration.",
+ "vite.config.ts": "Vite build and dev-server configuration.",
+ "vite.config.js": "Vite build and dev-server configuration.",
+ "next.config.js": "Next.js framework configuration.",
+ "next.config.mjs": "Next.js framework configuration.",
+ "tailwind.config.ts": "Tailwind CSS design-token and theme configuration.",
+ "tailwind.config.js": "Tailwind CSS design-token and theme configuration.",
+ "eslint.config.js": "ESLint linting rules.",
+ ".eslintrc.json": "ESLint linting rules.",
+ ".prettierrc": "Prettier formatting configuration.",
+ # Containers / infra
+ "dockerfile": "Container image build definition.",
+ "docker-compose.yml": "Multi-container service orchestration for local development.",
+ "docker-compose.yaml": "Multi-container service orchestration for local development.",
+ ".dockerignore": "Files excluded from the Docker build context.",
+ "makefile": "Build, test, and task automation targets.",
+ # VCS / repo hygiene
+ ".gitignore": "Paths excluded from version control.",
+ ".gitattributes": "Per-path Git behaviour (line endings, diff, linguist).",
+ ".editorconfig": "Editor formatting conventions shared across the team.",
+ ".pre-commit-config.yaml": "Pre-commit hook definitions run before each commit.",
+ # Project docs / governance
+ "readme.md": "Project overview and entry point for new readers.",
+ "contributing.md": "How to contribute: workflow, standards, and review process.",
+ "security.md": "Security policy and vulnerability-reporting process.",
+ "code_of_conduct.md": "Community code of conduct.",
+ "license": "Project license terms.",
+ "license.md": "Project license terms.",
+ "changelog.md": "Release history and notable changes.",
+ "codeowners": "Path-to-reviewer ownership mapping.",
+ "pull_request_template.md": "Template prompting authors for PR description and checklist.",
+ "bug_report.md": "Issue template for reporting bugs.",
+ "feature_request.md": "Issue template for proposing features.",
+ "funding.yml": "Sponsorship and funding links for the repository.",
+ # Agent / editor tooling
+ "marketplace.json": "Plugin marketplace listing and metadata.",
+ "plugin.json": "Plugin manifest: identity, entry points, and capabilities.",
+ "hooks.json": "Plugin lifecycle hook definitions.",
+ "claude.md": "Repository instructions and context for AI coding agents.",
+}
+
+# Whole-family fallbacks keyed on a filename suffix, tried when the exact name
+# is not mapped. Ordered most-specific first.
+_BY_SUFFIX: tuple[tuple[str, str], ...] = (
+ (".lock", "Resolved dependency lockfile pinning exact versions."),
+)
+
+# Directory-context fallbacks: a recognised tooling directory gives every file
+# beneath it a role even when the individual filename is project-specific (CI
+# workflow names vary, but they are all workflow definitions). Keyed on an
+# ordered tuple of path segments that must appear contiguously.
+_BY_DIR: tuple[tuple[tuple[str, ...], str], ...] = (
+ ((".github", "workflows"), "GitHub Actions CI/CD workflow definition."),
+)
+
+
+def well_known_role(path: str) -> str | None:
+ """Return a role sentence for a recognised file at *path*, else ``None``.
+
+ *path* may be a bare name or a full path. The basename is matched first
+ (case-insensitive), then a suffix family, then the enclosing directory
+ convention. Returns ``None`` when nothing is recognised, so callers keep
+ their existing fallback for genuinely opaque files.
+ """
+ name = PurePosixPath(path).name.lower()
+ role = _BY_NAME.get(name)
+ if role is not None:
+ return role
+ for suffix, dir_role in _BY_SUFFIX:
+ if name.endswith(suffix):
+ return dir_role
+ segments = tuple(s.lower() for s in PurePosixPath(path).parts[:-1])
+ for needle, dir_role in _BY_DIR:
+ span = len(needle)
+ if span <= len(segments) and any(
+ segments[i : i + span] == needle for i in range(len(segments) - span + 1)
+ ):
+ return dir_role
+ return None
diff --git a/tests/unit/generation/test_kg_reviewer.py b/tests/unit/generation/test_kg_reviewer.py
new file mode 100644
index 000000000..35d743dde
--- /dev/null
+++ b/tests/unit/generation/test_kg_reviewer.py
@@ -0,0 +1,201 @@
+"""Tests for the deterministic KG invariant reviewer (generation.kg_reviewer)."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.generation.kg_reviewer import Severity, apply_review, checks, run_review
+
+
+def _node(path: str, *, summary: str = "", ntype: str = "file", tags=None) -> dict:
+ return {
+ "id": f"file:{path}",
+ "filePath": path,
+ "summary": summary,
+ "type": ntype,
+ "tags": list(tags or []),
+ }
+
+
+# ---------------------------------------------------------------------------
+# check_summaries_restate_filename
+# ---------------------------------------------------------------------------
+
+
+def test_summary_restatement_flags_bare_template_only():
+ nodes = [
+ _node("pyproject.toml", summary="Configuration file: pyproject.toml.", ntype="config"),
+ _node("a/b.json", summary="Node package manifest: dependencies and scripts.", ntype="config"),
+ _node("src/walker.py", summary="Service module walker defining Walk, Visit.", ntype="file"),
+ ]
+ findings = checks.check_summaries_restate_filename(nodes)
+ targets = {f.target for f in findings}
+ assert targets == {"file:pyproject.toml"}
+ assert all(f.severity is Severity.WARNING for f in findings)
+
+
+def test_summary_restatement_ignores_code_and_test_nodes():
+ # A thin code/test summary is out of scope — only support-file types count.
+ nodes = [
+ _node("src/x.py", summary="x module.", ntype="file"),
+ _node("tests/test_x.py", summary="Tests for x.", ntype="file", tags=["test"]),
+ ]
+ assert checks.check_summaries_restate_filename(nodes) == []
+
+
+# ---------------------------------------------------------------------------
+# check_tour_reasons_distinct
+# ---------------------------------------------------------------------------
+
+
+def test_duplicate_tour_reasons_are_flagged():
+ tour = [
+ {"order": 1, "target_path": "a.ts", "reason": "Re-export hub."},
+ {"order": 2, "target_path": "b.ts", "reason": "Re-export hub."},
+ {"order": 3, "target_path": "c.py", "reason": "The core orchestrator."},
+ ]
+ findings = checks.check_tour_reasons_distinct(tour)
+ assert len(findings) == 1
+ assert findings[0].severity is Severity.WARNING
+ assert "a.ts" in findings[0].target and "b.ts" in findings[0].target
+
+
+def test_distinct_tour_reasons_pass():
+ tour = [
+ {"order": 1, "target_path": "a.ts", "reason": "Entry point."},
+ {"order": 2, "target_path": "b.py", "reason": "Core logic."},
+ ]
+ assert checks.check_tour_reasons_distinct(tour) == []
+
+
+# ---------------------------------------------------------------------------
+# check_layer_partition
+# ---------------------------------------------------------------------------
+
+
+def test_partition_clean_when_each_file_in_one_layer():
+ nodes = [_node("a.py"), _node("b.py")]
+ layers = [
+ {"id": "layer:x", "nodeIds": ["file:a.py"]},
+ {"id": "layer:y", "nodeIds": ["file:b.py"]},
+ ]
+ assert checks.check_layer_partition(layers, nodes) == []
+
+
+def test_partition_ignores_symbol_nodes_with_filepath():
+ # Symbol nodes carry a filePath but are not part of the layer partition —
+ # counting them would false-positive every function/class as "unlayered".
+ nodes = [
+ _node("a.py"),
+ {"id": "function:a.py:foo", "filePath": "a.py", "type": "function"},
+ {"id": "class:a.py:Bar", "filePath": "a.py", "type": "class"},
+ ]
+ layers = [{"id": "layer:x", "nodeIds": ["file:a.py"]}]
+ assert checks.check_layer_partition(layers, nodes) == []
+
+
+def test_partition_detects_duplicate_missing_and_unknown():
+ nodes = [_node("a.py"), _node("b.py"), _node("c.py")]
+ layers = [
+ {"id": "layer:x", "nodeIds": ["file:a.py"]},
+ {"id": "layer:y", "nodeIds": ["file:a.py", "file:zzz.py"]}, # dup + unknown
+ ] # b.py and c.py are unlayered
+ findings = checks.check_layer_partition(layers, nodes)
+ messages = " ".join(f.message for f in findings)
+ assert all(f.severity is Severity.CRITICAL for f in findings)
+ assert "more than one layer" in messages
+ assert "no layer" in messages
+ assert "not known file nodes" in messages
+
+
+# ---------------------------------------------------------------------------
+# check_tour_sequential
+# ---------------------------------------------------------------------------
+
+
+def test_tour_sequential_passes_for_contiguous_orders():
+ tour = [
+ {"order": 1, "title": "A", "target_path": "a"},
+ {"order": 2, "title": "B", "target_path": "b"},
+ ]
+ assert checks.check_tour_sequential(tour) == []
+
+
+def test_tour_sequential_detects_gap_and_empty_step():
+ tour = [
+ {"order": 1, "title": "A", "target_path": "a"},
+ {"order": 3, "title": "C", "target_path": "c"}, # gap
+ {"order": 4, "title": "", "target_path": ""}, # empty
+ ]
+ findings = checks.check_tour_sequential(tour)
+ assert len(findings) == 2
+ assert all(f.severity is Severity.CRITICAL for f in findings)
+
+
+# ---------------------------------------------------------------------------
+# check_layer_name_category
+# ---------------------------------------------------------------------------
+
+
+def test_layer_name_category_flags_unbacked_category_word():
+ nodes = [_node("plugins/claude/plugin.json"), _node("plugins/readme.md")]
+ layers = [{
+ "id": "layer:p",
+ "name": "Claude Plugin Middleware",
+ "nodeIds": ["file:plugins/claude/plugin.json", "file:plugins/readme.md"],
+ }]
+ findings = checks.check_layer_name_category(layers, nodes)
+ assert len(findings) == 1
+ assert findings[0].severity is Severity.WARNING
+ assert "middleware" in findings[0].message.lower()
+
+
+def test_layer_name_category_ok_when_files_back_the_word():
+ nodes = [_node("src/middleware/auth.ts")]
+ layers = [{
+ "id": "layer:m",
+ "name": "Auth Middleware",
+ "nodeIds": ["file:src/middleware/auth.ts"],
+ }]
+ assert checks.check_layer_name_category(layers, nodes) == []
+
+
+def test_layer_name_category_handles_ies_plural_singularization():
+ # "Repositories" must match files under a repository/ dir (ies -> y), not
+ # produce a false category-error finding.
+ nodes = [_node("src/repository/user_repo.py")]
+ layers = [{
+ "id": "layer:r",
+ "name": "Data Repositories",
+ "nodeIds": ["file:src/repository/user_repo.py"],
+ }]
+ assert checks.check_layer_name_category(layers, nodes) == []
+
+
+# ---------------------------------------------------------------------------
+# runner: run_review + apply_review
+# ---------------------------------------------------------------------------
+
+
+def _kg(nodes, layers, tour):
+ return SimpleNamespace(nodes=nodes, layers=layers, tour=tour)
+
+
+def test_run_review_aggregates_and_reports_ok():
+ nodes = [_node("a.py", summary="a module.")]
+ kg = _kg(nodes, [{"id": "layer:x", "nodeIds": ["file:a.py"]}],
+ [{"order": 1, "title": "A", "target_path": "a", "reason": "Entry."}])
+ report = run_review(kg)
+ assert report.ok
+ assert report.criticals == []
+
+
+def test_apply_review_tags_low_signal_summaries():
+ nodes = [_node("pyproject.toml", summary="Configuration file: pyproject.toml.", ntype="config")]
+ kg = _kg(nodes, [{"id": "layer:x", "nodeIds": ["file:pyproject.toml"]}], [])
+ report = apply_review(kg)
+ assert "low_signal_summary" in nodes[0]["tags"]
+ assert any(f.check == "summary_restates_filename" for f in report.warnings)
+ # Idempotent — re-applying does not duplicate the tag.
+ apply_review(kg)
+ assert nodes[0]["tags"].count("low_signal_summary") == 1
diff --git a/tests/unit/generation/test_layers.py b/tests/unit/generation/test_layers.py
index 91d9ee284..c039c340a 100644
--- a/tests/unit/generation/test_layers.py
+++ b/tests/unit/generation/test_layers.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from repowise.core.generation.layers import (
DEFAULT_LAYER,
+ DOCS_TOOLING_LAYER,
compute_layer_order,
infer_layer,
)
@@ -84,6 +85,46 @@ def test_infer_layer_root_dot_dirs_are_tooling_config():
assert infer_layer(".claude/CLAUDE.md") == "Config"
+def test_infer_layer_routes_docs_and_tooling_out_of_catch_all():
+ # Documentation, sample, and build/CI/extension-tooling trees are support
+ # material — they must not swell the Application catch-all.
+ assert infer_layer("docs/architecture.md") == DOCS_TOOLING_LAYER
+ assert infer_layer("website/src/pages/index.tsx") == DOCS_TOOLING_LAYER
+ assert infer_layer("scripts/release/publish.py") == DOCS_TOOLING_LAYER
+ assert infer_layer("docker/entrypoint.sh") == DOCS_TOOLING_LAYER
+ assert infer_layer("examples/quickstart/main.go") == DOCS_TOOLING_LAYER
+ assert infer_layer("benches/throughput.rs") == DOCS_TOOLING_LAYER
+
+
+def test_infer_layer_plugin_tree_is_tooling_not_middleware():
+ # A top-level plugins/ tree holds editor/agent extension manifests, not
+ # request-pipeline middleware — it must not borrow the Middleware category.
+ assert infer_layer("plugins/claude-code/hooks/hooks.json") == DOCS_TOOLING_LAYER
+ assert infer_layer("plugins/codex/.codex-plugin/plugin.json") == DOCS_TOOLING_LAYER
+ # Genuine middleware under a middleware/ dir is unaffected.
+ assert infer_layer("src/middleware/auth.ts") == "Middleware"
+
+
+def test_infer_layer_tooling_root_wins_over_deeper_runtime_hint():
+ # A runtime-looking directory inside a tooling tree describes the tooling,
+ # not a real runtime service.
+ assert infer_layer("scripts/services/deploy.py") == DOCS_TOOLING_LAYER
+ assert infer_layer("docs/api/reference.py") == DOCS_TOOLING_LAYER
+
+
+def test_docs_tooling_pinned_after_runtime_layers():
+ # Support bucket is pinned after the runtime stack even though its files
+ # import core code (it must not be crowned the top consumer).
+ file_layers = {
+ "scripts/run.py": DOCS_TOOLING_LAYER,
+ "src/api/users.py": "API",
+ "src/services/core.py": "Service",
+ }
+ edges = [("scripts/run.py", "src/services/core.py")]
+ order = compute_layer_order(file_layers, edges)
+ assert order[-1] == DOCS_TOOLING_LAYER
+
+
def test_infer_layer_test_root_beats_deeper_hints():
# A fixture under tests/models/ is a test, not Data — the test root wins
# over any deeper directory hint.
diff --git a/tests/unit/generation/test_well_known_files.py b/tests/unit/generation/test_well_known_files.py
new file mode 100644
index 000000000..0bab4f40f
--- /dev/null
+++ b/tests/unit/generation/test_well_known_files.py
@@ -0,0 +1,37 @@
+"""Tests for the well-known-file role map (generation.well_known_files)."""
+
+from __future__ import annotations
+
+from repowise.core.generation.well_known_files import well_known_role
+
+
+def test_recognized_names_get_a_real_role():
+ role = well_known_role("pyproject.toml")
+ assert role is not None
+ # The role describes purpose, not the filename.
+ assert "pyproject" not in role.lower()
+ assert well_known_role("package.json").lower().startswith("node package manifest")
+
+
+def test_lookup_is_case_insensitive_and_path_aware():
+ assert well_known_role("README.md") == well_known_role("docs/sub/readme.md")
+ assert well_known_role("a/b/c/Dockerfile") is not None
+
+
+def test_suffix_family_fallback_for_lockfiles():
+ assert well_known_role("uv.lock") is not None
+ assert well_known_role("Cargo.lock") == well_known_role("poetry.lock")
+
+
+def test_directory_context_roles_project_specific_filenames():
+ # CI workflow filenames vary per repo, but any file under .github/workflows
+ # is a workflow definition.
+ assert well_known_role(".github/workflows/publish-internal.yml") is not None
+ assert "workflow" in well_known_role(".github/workflows/ci.yml").lower()
+ # An unrelated yml outside the convention is not recognised by the dir rule.
+ assert well_known_role("src/config/values.yml") is None
+
+
+def test_unrecognized_name_returns_none():
+ assert well_known_role("some_random_module.py") is None
+ assert well_known_role("internal_widget.tsx") is None