From 2c31c6751a8682603c717066b819533ec40d538b Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:03:43 +0800 Subject: [PATCH 1/2] refactor(semantics): modularize inventory with zero-Any typed reports Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/semantics/development_probe.py | 5 +- loopx/semantics/inventory.py | 430 +++++++----------- loopx/semantics/inventory_reports.py | 398 ++++++++++++++++ scripts/generate_semantic_inventory.py | 4 +- .../test_semantic_development_probe.py | 1 + .../test_semantic_inventory_contract.py | 196 ++++++++ 6 files changed, 757 insertions(+), 277 deletions(-) create mode 100644 loopx/semantics/inventory_reports.py create mode 100644 tests/architecture/test_semantic_inventory_contract.py diff --git a/loopx/semantics/development_probe.py b/loopx/semantics/development_probe.py index 7662babeaa..3238bf927c 100644 --- a/loopx/semantics/development_probe.py +++ b/loopx/semantics/development_probe.py @@ -251,7 +251,10 @@ def _carriers(source: SourceFile | None) -> dict[tuple[str, str], dict[str, Any] inventory = build_inventory(Path("."), sources=[source]) found: dict[tuple[str, str], dict[str, Any]] = {} for kind, section in SUPPORTED_CARRIERS: - for item in inventory[section]: + entries = inventory.get(section) + if not isinstance(entries, list): + continue + for item in entries: found[(kind, item["name"])] = { "kind": kind, "name": item["name"], diff --git a/loopx/semantics/inventory.py b/loopx/semantics/inventory.py index c341a3e056..2eee9ae288 100644 --- a/loopx/semantics/inventory.py +++ b/loopx/semantics/inventory.py @@ -12,12 +12,34 @@ import ast from collections import defaultdict -from dataclasses import dataclass +from collections.abc import Mapping, Sequence from functools import lru_cache from pathlib import Path import re import subprocess -from typing import Any +from typing import TypeVar + +from .inventory_reports import ( + CarrierDefinition, + CarrierEntry, + ConsumerRankingEntry as ConsumerRankingEntry, + DivergentValueSetEntry as DivergentValueSetEntry, + FactEntry, + MergeCandidateGroup as MergeCandidateGroup, + MultiValueDuplicateEntry, + SourceFile as SourceFile, + StringConstantEntry as StringConstantEntry, + StringDefinition, + StringDuplicateEntry, + _str_list, + _word_token, + _word_token_mentions as _word_token_mentions, + consumer_ranking as consumer_ranking, + divergent_value_sets as divergent_value_sets, + merge_candidate_groups as merge_candidate_groups, + registered_owner_symbol_sets as registered_owner_symbol_sets, + render_inventory as render_inventory, +) INVENTORY_SCHEMA_VERSION = "loopx_semantic_inventory_v0" DEFAULT_ROOT = "loopx" @@ -44,13 +66,9 @@ re.MULTILINE, ) QUOTED = re.compile(r'''["']([^"']*)["']''') +_WORD_TOKEN = _word_token - -@dataclass(frozen=True) -class SourceFile: - path: str - suffix: str - text: str +_EntryT = TypeVar("_EntryT", bound=Mapping[str, object]) def load_sources(repo_root: Path, root: str = DEFAULT_ROOT) -> list[SourceFile]: @@ -59,7 +77,9 @@ def load_sources(repo_root: Path, root: str = DEFAULT_ROOT) -> list[SourceFile]: # policy. Untracked work and ignored local notes must never enter the map. tracked = subprocess.run( ["git", "ls-files", "--cached", "-z", "--", root], - cwd=repo_root, check=True, stdout=subprocess.PIPE, + cwd=repo_root, + check=True, + stdout=subprocess.PIPE, ).stdout.decode("utf-8").split("\0") for relative in sorted(set(tracked) - {""}): path = repo_root / relative @@ -82,7 +102,7 @@ def load_sources(repo_root: Path, root: str = DEFAULT_ROOT) -> list[SourceFile]: def _is_enum_class(node: ast.ClassDef) -> bool: for base in node.bases: name = base.id if isinstance(base, ast.Name) else getattr(base, "attr", "") - if name.endswith("Enum"): + if isinstance(name, str) and name.endswith("Enum"): return True return False @@ -128,11 +148,13 @@ def parse_python(source: SourceFile) -> ast.Module: try: return ast.parse(source.text) except SyntaxError as error: - raise ValueError(f"cannot inventory invalid Python source: {source.path}:{error.lineno}") from None + raise ValueError( + f"cannot inventory invalid Python source: {source.path}:{error.lineno}" + ) from None @lru_cache(maxsize=4096) -def python_facts(source: SourceFile) -> dict[str, list[dict[str, Any]]]: +def python_facts(source: SourceFile) -> dict[str, list[FactEntry]]: """Inventory the Python facts of one source file. The cache is keyed by the frozen SourceFile (path, suffix, text), so a @@ -140,7 +162,7 @@ def python_facts(source: SourceFile) -> dict[str, list[dict[str, Any]]]: scans of the same tree (owner_values plus build_inventory in the drift smoke) parse each file once instead of once per caller. """ - facts: dict[str, list[dict[str, Any]]] = { + facts: dict[str, list[FactEntry]] = { "enums": [], "closed_sets": [], "literal_aliases": [], @@ -163,7 +185,9 @@ def python_facts(source: SourceFile) -> dict[str, list[dict[str, Any]]]: else: string_valued = False if values and string_valued: - facts["enums"].append({"name": node.name, "module": source.path, "values": values}) + facts["enums"].append( + {"name": node.name, "module": source.path, "values": values} + ) continue assigned = _assigned_name(node) if assigned is None: @@ -174,12 +198,16 @@ def python_facts(source: SourceFile) -> dict[str, list[dict[str, Any]]]: if elements is None and isinstance(value.slice, ast.Constant) and isinstance(value.slice.value, str): elements = [value.slice.value] if elements: - facts["literal_aliases"].append({"name": name, "module": source.path, "values": elements}) + facts["literal_aliases"].append( + {"name": name, "module": source.path, "values": elements} + ) continue if not UPPER_NAME.match(name): continue if isinstance(value, ast.Constant) and isinstance(value.value, str): - facts["string_constants"].append({"name": name, "module": source.path, "value": value.value}) + facts["string_constants"].append( + {"name": name, "module": source.path, "value": value.value} + ) continue elements = _string_elements(value) if elements is not None and len(elements) >= 2: @@ -194,8 +222,8 @@ def python_facts(source: SourceFile) -> dict[str, list[dict[str, Any]]]: return facts -def typescript_facts(source: SourceFile) -> dict[str, list[dict[str, Any]]]: - facts: dict[str, list[dict[str, Any]]] = {"const_arrays": [], "string_constants": []} +def typescript_facts(source: SourceFile) -> dict[str, list[FactEntry]]: + facts: dict[str, list[FactEntry]] = {"const_arrays": [], "string_constants": []} for match in TS_CONST_ARRAY.finditer(source.text): values = QUOTED.findall(match.group("body")) if values: @@ -204,7 +232,11 @@ def typescript_facts(source: SourceFile) -> dict[str, list[dict[str, Any]]]: ) for match in TS_STRING_CONST.finditer(source.text): facts["string_constants"].append( - {"name": match.group("name"), "module": source.path, "value": match.group("value")} + { + "name": match.group("name"), + "module": source.path, + "value": match.group("value"), + } ) return facts @@ -217,19 +249,28 @@ def _duplicate_kind(modules: list[str]) -> str: def multi_value_carriers( *, - enums: list[dict[str, Any]], - closed_sets: list[dict[str, Any]], - literal_aliases: list[dict[str, Any]], - const_arrays: list[dict[str, Any]], -) -> list[dict[str, Any]]: + enums: Sequence[FactEntry], + closed_sets: Sequence[FactEntry], + literal_aliases: Sequence[FactEntry], + const_arrays: Sequence[FactEntry], +) -> list[CarrierEntry]: """Tag each scan section with the carrier kind the collision report prints.""" - carriers: list[dict[str, Any]] = [] + carriers: list[CarrierEntry] = [] for kind, entries in zip( ("python_enum", "python_closed_set", "python_literal_alias", "typescript_const_array"), (enums, closed_sets, literal_aliases, const_arrays), strict=True, ): - carriers.extend({**entry, "kind": kind} for entry in entries) + for entry in entries: + tagged: CarrierEntry = { + "kind": kind, + "name": entry["name"], + "module": entry["module"], + "values": list(entry.get("values") or []), + } + if "container" in entry: + tagged["container"] = entry["container"] + carriers.append(tagged) return carriers @@ -242,7 +283,9 @@ def multi_value_carriers( UNORDERED_CONTAINERS = frozenset({"set", "frozenset"}) -def _collision_keys(carriers_for_name: list[dict[str, Any]]) -> set[tuple[str, ...]]: +def _collision_keys( + carriers_for_name: Sequence[Mapping[str, object]], +) -> set[tuple[str, ...]]: """The distinct value sets one name carries; one key means the name agrees. Membership decides identity only when *every* definition of the name is an @@ -257,13 +300,16 @@ def _collision_keys(carriers_for_name: list[dict[str, Any]]) -> set[tuple[str, . semantics are unestablished here. """ if all(item.get("container") in UNORDERED_CONTAINERS for item in carriers_for_name): - return {tuple(sorted(set(item["values"]))) for item in carriers_for_name} - return {tuple(item["values"]) for item in carriers_for_name} + return { + tuple(sorted(set(_str_list(item["values"])))) + for item in carriers_for_name + } + return {tuple(_str_list(item["values"])) for item in carriers_for_name} def multi_value_name_collisions( - carriers: list[dict[str, Any]], -) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + carriers: Sequence[Mapping[str, object]], +) -> tuple[list[MultiValueDuplicateEntry], list[MultiValueDuplicateEntry]]: """Group multi-value carriers by name to find collisions between modules. A string constant is ``NAME = "value"``; a multi-value carrier is an enum, a @@ -273,22 +319,26 @@ def multi_value_name_collisions( fork. Each entry keeps every defining module and its value set, so a reviewer sees the divergence rather than a count. """ - by_name: dict[str, list[dict[str, Any]]] = defaultdict(list) + by_name: dict[str, list[Mapping[str, object]]] = defaultdict(list) for carrier in carriers: - by_name[carrier["name"]].append(carrier) - twins: list[dict[str, Any]] = [] - forks: list[dict[str, Any]] = [] + by_name[str(carrier["name"])].append(carrier) + twins: list[MultiValueDuplicateEntry] = [] + forks: list[MultiValueDuplicateEntry] = [] for name, carriers_for_name in sorted(by_name.items()): if len(carriers_for_name) < 2: continue - definitions = sorted( + definitions: list[CarrierDefinition] = sorted( ( - {"kind": item["kind"], "module": item["module"], "values": list(item["values"])} + { + "kind": str(item["kind"]), + "module": str(item["module"]), + "values": _str_list(item["values"]), + } for item in carriers_for_name ), key=lambda item: item["module"], ) - entry: dict[str, Any] = {"name": name, "definitions": definitions} + entry: MultiValueDuplicateEntry = {"name": name, "definitions": definitions} # Keyed off the raw carriers, which still carry ``container``; the # ``definitions`` entries keep their source order for review. if len(_collision_keys(carriers_for_name)) == 1: @@ -300,21 +350,25 @@ def multi_value_name_collisions( return twins, forks -def _sorted_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]]: - return sorted(entries, key=lambda entry: (entry["module"], entry["name"])) +def _sorted_entries(entries: Sequence[_EntryT]) -> list[_EntryT]: + return sorted( + entries, + key=lambda entry: (str(entry["module"]), str(entry["name"])), + ) def build_inventory( - repo_root: Path, root: str = DEFAULT_ROOT, sources: list[SourceFile] | None = None -) -> dict[str, Any]: - if sources is None: - sources = load_sources(repo_root, root) - enums: list[dict[str, Any]] = [] - closed_sets: list[dict[str, Any]] = [] - literal_aliases: list[dict[str, Any]] = [] - const_arrays: list[dict[str, Any]] = [] - string_constants: list[dict[str, Any]] = [] - for source in sources: + repo_root: Path, + root: str = DEFAULT_ROOT, + sources: Sequence[SourceFile] | None = None, +) -> dict[str, object]: + resolved_sources = load_sources(repo_root, root) if sources is None else list(sources) + enums: list[FactEntry] = [] + closed_sets: list[FactEntry] = [] + literal_aliases: list[FactEntry] = [] + const_arrays: list[FactEntry] = [] + string_constants: list[FactEntry] = [] + for source in resolved_sources: if source.suffix == ".py": facts = python_facts(source) enums.extend(facts["enums"]) @@ -335,17 +389,23 @@ def build_inventory( multi_twins, multi_forks = multi_value_name_collisions(multi_value) definitions = string_constant_definitions(string_constants) - twins: list[dict[str, Any]] = [] - forks: list[dict[str, Any]] = [] - conflicting: list[dict[str, Any]] = [] + twins: list[StringDuplicateEntry] = [] + forks: list[StringDuplicateEntry] = [] + conflicting: list[StringDuplicateEntry] = [] for name, defs in sorted(definitions.items()): if len(defs) < 2: continue modules = [item["module"] for item in defs] - entry: dict[str, Any] = {"name": name, "is_schema_version": bool(SCHEMA_VERSION_NAME.search(name))} + entry: StringDuplicateEntry = { + "name": name, + "is_schema_version": bool(SCHEMA_VERSION_NAME.search(name)), + } if len({item["value"] for item in defs}) == 1: - entry.update({"value": defs[0]["value"], "modules": modules}) - (twins if _duplicate_kind(modules) == "cross_runtime_twin" else forks).append(entry) + entry["value"] = defs[0]["value"] + entry["modules"] = modules + (twins if _duplicate_kind(modules) == "cross_runtime_twin" else forks).append( + entry + ) else: entry["definitions"] = defs conflicting.append(entry) @@ -370,249 +430,71 @@ def build_inventory( "multi_value_forks": multi_forks, }, "summary": { - "source_files": len(sources), + "source_files": len(resolved_sources), "python_enums": len(enums), "python_closed_sets": len(closed_sets), "python_literal_aliases": len(literal_aliases), "typescript_const_arrays": len(const_arrays), "named_string_constants": len(string_constants), - "schema_version_names": sum(1 for name in definitions if SCHEMA_VERSION_NAME.search(name)), - "schema_version_same_runtime_forks": sum(1 for item in forks if item["is_schema_version"]), + "schema_version_names": sum( + 1 for name in definitions if SCHEMA_VERSION_NAME.search(name) + ), + "schema_version_same_runtime_forks": sum( + 1 for item in forks if item["is_schema_version"] + ), "cross_runtime_twins": len(twins), "same_runtime_forks": len(forks), - "same_runtime_fork_definitions": sum(len(item["modules"]) for item in forks), + "same_runtime_fork_definitions": sum( + len(item.get("modules") or []) for item in forks + ), "conflicting_values": len(conflicting), - "conflicting_definitions": sum(len(item["definitions"]) for item in conflicting), + "conflicting_definitions": sum( + len(item.get("definitions") or []) for item in conflicting + ), "multi_value_twins": len(multi_twins), "multi_value_forks": len(multi_forks), - "multi_value_fork_definitions": sum(len(item["definitions"]) for item in multi_forks), + "multi_value_fork_definitions": sum( + len(item["definitions"]) for item in multi_forks + ), "same_runtime_forks_semantic": sum( 1 for item in forks if not MODULE_LOCAL_CONVENTION.match(item["name"]) ), "conflicting_values_semantic": sum( - 1 for item in conflicting if not MODULE_LOCAL_CONVENTION.match(item["name"]) + 1 + for item in conflicting + if not MODULE_LOCAL_CONVENTION.match(item["name"]) ), }, } -def string_constant_definitions(string_constants: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]: +def string_constant_definitions( + string_constants: Sequence[Mapping[str, object]], +) -> dict[str, list[StringDefinition]]: """Group ``NAME = "value"`` definitions by constant name, modules sorted.""" - by_name: dict[str, list[dict[str, Any]]] = defaultdict(list) + by_name: dict[str, list[StringDefinition]] = defaultdict(list) for entry in string_constants: - by_name[entry["name"]].append({"module": entry["module"], "value": entry["value"]}) - return {name: sorted(defs, key=lambda item: item["module"]) for name, defs in by_name.items()} + by_name[str(entry["name"])].append( + {"module": str(entry["module"]), "value": str(entry["value"])} + ) + return { + name: sorted(defs, key=lambda item: item["module"]) + for name, defs in by_name.items() + } -def collect_string_constants(sources: list[SourceFile]) -> list[dict[str, Any]]: - constants: list[dict[str, Any]] = [] +def collect_string_constants( + sources: Sequence[SourceFile], +) -> list[StringConstantEntry]: + constants: list[StringConstantEntry] = [] for source in sources: facts = python_facts(source) if source.suffix == ".py" else typescript_facts(source) - constants.extend(facts["string_constants"]) - return constants - - -def render_inventory(inventory: dict[str, Any]) -> str: - """Two-space indented JSON with one line per inventory entry for readable diffs.""" - import json - - def one_line(value: Any) -> str: - return json.dumps(value, ensure_ascii=False, separators=(", ", ": ")) - - lines = ["{"] - keys = list(inventory) - for index, key in enumerate(keys): - value = inventory[key] - comma = "," if index < len(keys) - 1 else "" - if isinstance(value, list): - if not value: - lines.append(f' "{key}": []{comma}') - continue - lines.append(f' "{key}": [') - for position, entry in enumerate(value): - lines.append(" " + one_line(entry) + ("," if position < len(value) - 1 else "")) - lines.append(f" ]{comma}") - elif isinstance(value, dict) and value and all(isinstance(item, list) for item in value.values()): - lines.append(f' "{key}": {{') - inner_keys = list(value) - for inner_index, inner_key in enumerate(inner_keys): - entries = value[inner_key] - inner_comma = "," if inner_index < len(inner_keys) - 1 else "" - if not entries: - lines.append(f' "{inner_key}": []{inner_comma}') - continue - lines.append(f' "{inner_key}": [') - for position, entry in enumerate(entries): - lines.append(" " + one_line(entry) + ("," if position < len(entries) - 1 else "")) - lines.append(f" ]{inner_comma}") - lines.append(f" }}{comma}") - else: - rendered = json.dumps(value, ensure_ascii=False, indent=2) - rendered = "\n".join((" " + line) if i else line for i, line in enumerate(rendered.splitlines())) - lines.append(f' "{key}": {rendered}{comma}') - lines.append("}") - return "\n".join(lines) + "\n" - - -def registered_owner_symbol_sets(registry: dict[str, Any]) -> set[frozenset[str]]: - """Symbol sets that one registered vocabulary already binds into one concept. - - A cross-runtime vocabulary names its owner twice because the runtimes spell - it differently: ``EffectiveAction`` in Python and ``EFFECTIVE_ACTIONS`` in - TypeScript are the registered owners of ``effective_action``. The registry - entry is the decision that the two spellings are one vocabulary, so their - equal value sets carry no review question. Only sets with more than one - distinct symbol are returned; a vocabulary with a single owner, or with the - same symbol on both sides, explains nothing. - """ - sets: set[frozenset[str]] = set() - for vocabulary in registry["vocabularies"].values(): - symbols = frozenset( - owner.split("::")[-1] for owner in (vocabulary.get("owners") or {}).values() if owner - ) - if len(symbols) > 1: - sets.add(symbols) - return sets - - -def merge_candidate_groups( - inventory: dict[str, Any], registry: dict[str, Any] | None = None -) -> list[dict[str, Any]]: - """Advisory: distinct names carrying an identical multi-value set. - - Value-set equality is a candidate signal, not proof of one concept: - ``CONFIDENCE_LEVELS`` and ``EDGE_CASE_COMPLEXITIES`` share ``high/low/medium`` - while meaning different things. Each group is for review, never auto-merged, - and is printed on demand rather than committed so it cannot be mistaken for a - ratified decision. - - ``registry`` drops the groups whose names are exactly the owner symbols of - one registered vocabulary. Those are a naming convention, not duplication: - the registry has already ruled the two spellings one concept, and leaving - them in the list buries the groups that nobody has ruled on. Passing - ``None`` keeps the unfiltered list, which is what an audit of the raw - value-set collisions wants. Filtering removes noise from a review list; it - retires nothing and settles no group that stays. - - ``cross_runtime`` marks a group whose modules span both runtimes. Such a - group is a registry gap by construction, because a value set living in - Python and TypeScript with no vocabulary binding them is exactly what the - registry exists to record. - """ - explained = registered_owner_symbol_sets(registry) if registry is not None else set() - by_values: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list) - for section in ("python_enums", "python_closed_sets", "python_literal_aliases", "typescript_const_arrays"): - for entry in inventory[section]: - if len(entry["values"]) >= 2: - by_values[tuple(sorted(entry["values"]))].append(entry) - groups: list[dict[str, Any]] = [] - for values, entries in by_values.items(): - names = sorted({entry["name"] for entry in entries}) - if len(names) < 2 or frozenset(names) in explained: - continue - modules = sorted({entry["module"] for entry in entries}) - groups.append( - { - "names": names, - "values": list(values), - "modules": modules, - "cross_runtime": any(module.endswith(".py") for module in modules) - and any(module.endswith(".ts") for module in modules), - } - ) - return sorted(groups, key=lambda group: (-len(group["names"]), group["names"])) - - -def divergent_value_sets(inventory: dict[str, Any]) -> list[dict[str, Any]]: - """Advisory: forks, keyed by name, with how many value sets each carries. - - Complements ``merge_candidate_groups``, which groups *different* names with - *identical* value sets and therefore never lists a fork at all: a fork is - *one* name whose modules disagree, so the two reports answer different - questions and the merge-candidate grouping cannot substitute for this one. - - What this does **not** do is detect a rename. Renaming one side of a fork - leaves that name with a single definition, so it stops being a fork and - drops out of this report exactly as it drops out of the budget -- measured, - not assumed. The RFC Section 9 limit therefore stands unclosed; this report - only makes the *surviving* forks visible by name, with the count of - disagreeing value sets, where before they were visible only as a number. - A rename of one side is still caught when the name is declared, because the - declaration names every defining module and the renamed side no longer - matches. - - Nothing here is a second authority: advisory output over the same computed - inventory, never committed, never a budget input. - """ - entries: list[dict[str, Any]] = [] - for entry in inventory["duplicate_definitions"]["multi_value_forks"]: - value_sets = {tuple(sorted(item["values"])) for item in entry["definitions"]} - if len(value_sets) < 2: - continue - entries.append( - { - "name": entry["name"], - "value_sets": len(value_sets), - "definition_modules": sorted({item["module"] for item in entry["definitions"]}), - } - ) - return sorted(entries, key=lambda item: (-item["value_sets"], item["name"])) - - -_WORD_TOKEN = re.compile(r"\w+") - - -def _word_token_mentions(sources: list[SourceFile]) -> dict[str, set[int]]: - """Map each word token to the source positions whose text contains it. - - Tokenising is deliberately lexical, over the raw text: comments and string - contents counted as mentions before and still do. The value is a set of - positions in ``sources`` so a repeated occurrence inside one file counts - once, exactly as a single ``search`` did. - """ - mentions: dict[str, set[int]] = {} - for position, source in enumerate(sources): - for token in set(_WORD_TOKEN.findall(source.text)): - mentions.setdefault(token, set()).add(position) - return mentions - - -def consumer_ranking(inventory: dict[str, Any], sources: list[SourceFile]) -> list[dict[str, Any]]: - """Advisory ranking: modules outside the definer that mention each symbol. - - Not stored in the committed inventory because it changes with every consumer - edit; the generator prints it on demand so retirement work can be ordered. - """ - # One lexical pass over the corpus instead of one search per symbol. A name - # made only of word characters matches ``\bNAME\b`` exactly when it appears - # as a whole ``\w+`` token, so the index answers the same question the - # per-symbol regex did. Anything else -- a name carrying a non-word - # character, where the boundary assertions no longer line up with token - # edges -- keeps the original search rather than assume the equivalence. - mentions = _word_token_mentions(sources) - ranking: list[dict[str, Any]] = [] - for section in ("python_enums", "typescript_const_arrays", "python_closed_sets", "python_literal_aliases"): - for entry in inventory[section]: - name = entry["name"] - if _WORD_TOKEN.fullmatch(name): - # Positions, not paths: a corpus that lists the same path twice - # still contributes twice, as the per-source search did. - consumers = sum( - 1 for position in mentions.get(name, ()) - if sources[position].path != entry["module"] - ) - else: - token = re.compile(rf"\b{re.escape(name)}\b") - consumers = sum( - 1 for source in sources if source.path != entry["module"] and token.search(source.text) - ) - ranking.append( + for item in facts["string_constants"]: + constants.append( { - "kind": section, - "name": entry["name"], - "module": entry["module"], - "values": len(entry["values"]), - "external_consumer_modules": consumers, + "name": item["name"], + "module": item["module"], + "value": item["value"], } ) - return sorted(ranking, key=lambda item: (-item["external_consumer_modules"], item["module"], item["name"])) + return constants diff --git a/loopx/semantics/inventory_reports.py b/loopx/semantics/inventory_reports.py new file mode 100644 index 0000000000..0cdd4c0931 --- /dev/null +++ b/loopx/semantics/inventory_reports.py @@ -0,0 +1,398 @@ +"""Reporting, rendering, and typed record definitions for semantic inventories.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import json +import re +from typing import NotRequired, TypedDict, cast + + +@dataclass(frozen=True) +class SourceFile: + """Tracked repository source file eligible for semantic inventory.""" + + path: str + suffix: str + text: str + + +class FactEntry(TypedDict): + """Typed structural inventory entry produced by Python/TS AST scanners.""" + + name: str + module: str + values: NotRequired[list[str]] + value: NotRequired[str] + container: NotRequired[str] + + +class CarrierEntry(TypedDict): + """Multi-value carrier tagged with its carrier kind.""" + + kind: str + name: str + module: str + values: list[str] + container: NotRequired[str] + + +class CarrierDefinition(TypedDict): + """Source-ordered definition entry preserved in collision diagnostics.""" + + kind: str + module: str + values: list[str] + + +class MultiValueDuplicateEntry(TypedDict): + """Twin or fork grouping across multi-value semantic carriers.""" + + name: str + definitions: list[CarrierDefinition] + values: NotRequired[list[str]] + modules: NotRequired[list[str]] + + +class StringConstantEntry(TypedDict): + """Single named string constant emitted by Python or TypeScript scans.""" + + name: str + module: str + value: str + + +class StringDefinition(TypedDict): + """Single module/value pair under a named string constant.""" + + module: str + value: str + + +class StringDuplicateEntry(TypedDict): + """Duplicate named string constant entry in the computed inventory.""" + + name: str + is_schema_version: bool + value: NotRequired[str] + modules: NotRequired[list[str]] + definitions: NotRequired[list[StringDefinition]] + + +class MergeCandidateGroup(TypedDict): + """Advisory group of distinct symbol names carrying identical value sets.""" + + names: list[str] + values: list[str] + modules: list[str] + cross_runtime: bool + + +class DivergentValueSetEntry(TypedDict): + """Advisory summary of a forked symbol and its disagreeing value sets.""" + + name: str + value_sets: int + definition_modules: list[str] + + +class ConsumerRankingEntry(TypedDict): + """Advisory external consumer-mention ranking for one inventory symbol.""" + + kind: str + name: str + module: str + values: int + external_consumer_modules: int + + +def _str_list(value: object) -> list[str]: + if not isinstance(value, (list, tuple)): + return [] + return [item if isinstance(item, str) else str(item) for item in value] + + +def render_inventory(inventory: Mapping[str, object]) -> str: + """Two-space indented JSON with one line per inventory entry for readable diffs.""" + + def one_line(value: object) -> str: + return json.dumps(value, ensure_ascii=False, separators=(", ", ": ")) + + lines = ["{"] + keys = list(inventory) + for index, key in enumerate(keys): + value = inventory[key] + comma = "," if index < len(keys) - 1 else "" + if isinstance(value, list): + if not value: + lines.append(f' "{key}": []{comma}') + continue + lines.append(f' "{key}": [') + for position, entry in enumerate(value): + lines.append( + " " + one_line(entry) + ("," if position < len(value) - 1 else "") + ) + lines.append(f" ]{comma}") + elif ( + isinstance(value, dict) + and value + and all(isinstance(item, list) for item in value.values()) + ): + lines.append(f' "{key}": {{') + inner_keys = list(value) + for inner_index, inner_key in enumerate(inner_keys): + entries = value[inner_key] + inner_comma = "," if inner_index < len(inner_keys) - 1 else "" + if not entries: + lines.append(f' "{inner_key}": []{inner_comma}') + continue + lines.append(f' "{inner_key}": [') + for position, entry in enumerate(entries): + lines.append( + " " + + one_line(entry) + + ("," if position < len(entries) - 1 else "") + ) + lines.append(f" ]{inner_comma}") + lines.append(f" }}{comma}") + else: + rendered = json.dumps(value, ensure_ascii=False, indent=2) + rendered = "\n".join( + (" " + line) if i else line + for i, line in enumerate(rendered.splitlines()) + ) + lines.append(f' "{key}": {rendered}{comma}') + lines.append("}") + return "\n".join(lines) + "\n" + + +def registered_owner_symbol_sets(registry: Mapping[str, object]) -> set[frozenset[str]]: + """Symbol sets that one registered vocabulary already binds into one concept. + + A cross-runtime vocabulary names its owner twice because the runtimes spell + it differently: ``EffectiveAction`` in Python and ``EFFECTIVE_ACTIONS`` in + TypeScript are the registered owners of ``effective_action``. The registry + entry is the decision that the two spellings are one vocabulary, so their + equal value sets carry no review question. Only sets with more than one + distinct symbol are returned; a vocabulary with a single owner, or with the + same symbol on both sides, explains nothing. + """ + sets: set[frozenset[str]] = set() + vocabularies = registry["vocabularies"] + if not isinstance(vocabularies, Mapping): + return sets + for vocabulary in vocabularies.values(): + if not isinstance(vocabulary, Mapping): + continue + owners_obj = vocabulary.get("owners") + owners = owners_obj if isinstance(owners_obj, Mapping) else {} + symbols = frozenset( + str(owner).split("::")[-1] for owner in owners.values() if owner + ) + if len(symbols) > 1: + sets.add(symbols) + return sets + + +def merge_candidate_groups( + inventory: Mapping[str, object], + registry: Mapping[str, object] | None = None, +) -> list[MergeCandidateGroup]: + """Advisory: distinct names carrying an identical multi-value set. + + Value-set equality is a candidate signal, not proof of one concept: + ``CONFIDENCE_LEVELS`` and ``EDGE_CASE_COMPLEXITIES`` share ``high/low/medium`` + while meaning different things. Each group is for review, never auto-merged, + and is printed on demand rather than committed so it cannot be mistaken for a + ratified decision. + + ``registry`` drops the groups whose names are exactly the owner symbols of + one registered vocabulary. Those are a naming convention, not duplication: + the registry has already ruled the two spellings one concept, and leaving + them in the list buries the groups that nobody has ruled on. Passing + ``None`` keeps the unfiltered list, which is what an audit of the raw + value-set collisions wants. Filtering removes noise from a review list; it + retires nothing and settles no group that stays. + + ``cross_runtime`` marks a group whose modules span both runtimes. Such a + group is a registry gap by construction, because a value set living in + Python and TypeScript with no vocabulary binding them is exactly what the + registry exists to record. + """ + explained = ( + registered_owner_symbol_sets(registry) if registry is not None else set() + ) + by_values: dict[tuple[str, ...], list[Mapping[str, object]]] = defaultdict(list) + for section in ( + "python_enums", + "python_closed_sets", + "python_literal_aliases", + "typescript_const_arrays", + ): + raw_section = inventory[section] + if not isinstance(raw_section, list): + continue + for entry in raw_section: + if not isinstance(entry, Mapping): + continue + entry_values = _str_list(entry.get("values")) + if len(entry_values) >= 2: + by_values[tuple(sorted(entry_values))].append(entry) + groups: list[MergeCandidateGroup] = [] + for values, entries in by_values.items(): + names = sorted({str(entry["name"]) for entry in entries}) + if len(names) < 2 or frozenset(names) in explained: + continue + modules = sorted({str(entry["module"]) for entry in entries}) + groups.append( + { + "names": names, + "values": list(values), + "modules": modules, + "cross_runtime": any(module.endswith(".py") for module in modules) + and any(module.endswith(".ts") for module in modules), + } + ) + return sorted(groups, key=lambda group: (-len(group["names"]), group["names"])) + + +def divergent_value_sets( + inventory: Mapping[str, object], +) -> list[DivergentValueSetEntry]: + """Advisory: forks, keyed by name, with how many value sets each carries. + + Complements ``merge_candidate_groups``, which groups *different* names with + *identical* value sets and therefore never lists a fork at all: a fork is + *one* name whose modules disagree, so the two reports answer different + questions and the merge-candidate grouping cannot substitute for this one. + + What this does **not** do is detect a rename. Renaming one side of a fork + leaves that name with a single definition, so it stops being a fork and + drops out of this report exactly as it drops out of the budget -- measured, + not assumed. The RFC Section 9 limit therefore stands unclosed; this report + only makes the *surviving* forks visible by name, with the count of + disagreeing value sets, where before they were visible only as a number. + A rename of one side is still caught when the name is declared, because the + declaration names every defining module and the renamed side no longer + matches. + + Nothing here is a second authority: advisory output over the same computed + inventory, never committed, never a budget input. + """ + entries: list[DivergentValueSetEntry] = [] + duplicates = inventory["duplicate_definitions"] + if not isinstance(duplicates, Mapping): + return entries + raw_forks = duplicates["multi_value_forks"] + if not isinstance(raw_forks, list): + return entries + for entry in raw_forks: + if not isinstance(entry, Mapping): + continue + raw_definitions = entry["definitions"] + if not isinstance(raw_definitions, list): + continue + definitions = [ + cast(Mapping[str, object], item) + for item in raw_definitions + if isinstance(item, Mapping) + ] + value_sets = {tuple(sorted(_str_list(item["values"]))) for item in definitions} + if len(value_sets) < 2: + continue + entries.append( + { + "name": str(entry["name"]), + "value_sets": len(value_sets), + "definition_modules": sorted( + {str(item["module"]) for item in definitions} + ), + } + ) + return sorted(entries, key=lambda item: (-item["value_sets"], item["name"])) + + +_word_token = re.compile(r"\w+") + + +def _word_token_mentions(sources: Sequence[SourceFile]) -> dict[str, set[int]]: + """Map each word token to the source positions whose text contains it. + + Tokenising is deliberately lexical, over the raw text: comments and string + contents counted as mentions before and still do. The value is a set of + positions in ``sources`` so a repeated occurrence inside one file counts + once, exactly as a single ``search`` did. + """ + mentions: dict[str, set[int]] = {} + for position, source in enumerate(sources): + for token in set(_word_token.findall(source.text)): + mentions.setdefault(token, set()).add(position) + return mentions + + +def consumer_ranking( + inventory: Mapping[str, object], + sources: Sequence[SourceFile], +) -> list[ConsumerRankingEntry]: + """Advisory ranking: modules outside the definer that mention each symbol. + + Not stored in the committed inventory because it changes with every consumer + edit; the generator prints it on demand so retirement work can be ordered. + """ + # One lexical pass over the corpus instead of one search per symbol. A name + # made only of word characters matches ``\bNAME\b`` exactly when it appears + # as a whole ``\w+`` token, so the index answers the same question the + # per-symbol regex did. Anything else -- a name carrying a non-word + # character, where the boundary assertions no longer line up with token + # edges -- keeps the original search rather than assume the equivalence. + mentions = _word_token_mentions(sources) + ranking: list[ConsumerRankingEntry] = [] + for section in ( + "python_enums", + "typescript_const_arrays", + "python_closed_sets", + "python_literal_aliases", + ): + raw_section = inventory[section] + if not isinstance(raw_section, list): + continue + for entry in raw_section: + if not isinstance(entry, Mapping): + continue + name = str(entry["name"]) + module = str(entry["module"]) + entry_values = _str_list(entry.get("values")) + if _word_token.fullmatch(name): + # Positions, not paths: a corpus that lists the same path twice + # still contributes twice, as the per-source search did. + consumers = sum( + 1 + for position in mentions.get(name, ()) + if sources[position].path != module + ) + else: + token = re.compile(rf"\b{re.escape(name)}\b") + consumers = sum( + 1 + for source in sources + if source.path != module and token.search(source.text) + ) + ranking.append( + { + "kind": section, + "name": name, + "module": module, + "values": len(entry_values), + "external_consumer_modules": consumers, + } + ) + return sorted( + ranking, + key=lambda item: ( + -item["external_consumer_modules"], + item["module"], + item["name"], + ), + ) diff --git a/scripts/generate_semantic_inventory.py b/scripts/generate_semantic_inventory.py index 39f622da7d..038a25b705 100755 --- a/scripts/generate_semantic_inventory.py +++ b/scripts/generate_semantic_inventory.py @@ -145,8 +145,8 @@ def main() -> int: divergent = divergent_value_sets(inventory)[: args.top] print() print("value_sets name definition_modules") - for row in divergent: - print(f"{row['value_sets']:>10} {row['name']} {', '.join(row['definition_modules'])}") + for entry in divergent: + print(f"{entry['value_sets']:>10} {entry['name']} {', '.join(entry['definition_modules'])}") print() print_merge_candidates(inventory) if args.consumer_evidence: diff --git a/tests/architecture/test_semantic_development_probe.py b/tests/architecture/test_semantic_development_probe.py index fd671a76af..02a78232ee 100644 --- a/tests/architecture/test_semantic_development_probe.py +++ b/tests/architecture/test_semantic_development_probe.py @@ -328,6 +328,7 @@ def test_missing_baseline_is_a_tool_error(repository: Path) -> None: "loopx/__init__.py", "loopx/semantics/__init__.py", "loopx/semantics/inventory.py", + "loopx/semantics/inventory_reports.py", "loopx/semantics/development_probe.py", "loopx/semantics/consumer_report.py", "loopx/semantics/field_use.py", diff --git a/tests/architecture/test_semantic_inventory_contract.py b/tests/architecture/test_semantic_inventory_contract.py new file mode 100644 index 0000000000..8b6d17e936 --- /dev/null +++ b/tests/architecture/test_semantic_inventory_contract.py @@ -0,0 +1,196 @@ +"""Contract, zero-Any, and malformed-input tests for semantic inventory modules.""" + +from __future__ import annotations + +import ast +import io +import json +from pathlib import Path +import subprocess +import tokenize + +import pytest + +from loopx.canary.maintainability_ratchet import ( + DECISION_POINT_LIMIT, + DECISION_STATEMENT_LIMIT, + _FunctionMetrics, + _iter_functions, +) +from loopx.semantics import inventory, inventory_reports + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _ast_any_count(source: str) -> int: + tree = ast.parse(source) + return sum( + 1 + for node in ast.walk(tree) + if (isinstance(node, ast.Name) and node.id == "Any") + or (isinstance(node, ast.Attribute) and node.attr == "Any") + or ( + isinstance(node, ast.ImportFrom) + and any(alias.name == "Any" for alias in node.names) + ) + ) + + +def _comment_ignore_or_noqa_count(source: str) -> int: + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + return sum( + 1 + for tok in tokens + if tok.type == tokenize.COMMENT + and ("type: ignore" in tok.string or "noqa" in tok.string) + ) + + +def test_inventory_modules_meet_zero_any_size_and_reexport_contracts() -> None: + inv_path = REPO_ROOT / "loopx" / "semantics" / "inventory.py" + rep_path = REPO_ROOT / "loopx" / "semantics" / "inventory_reports.py" + for path in (inv_path, rep_path, Path(__file__)): + source = path.read_text(encoding="utf-8") + assert _ast_any_count(source) == 0, path + assert _comment_ignore_or_noqa_count(source) == 0, path + + assert len(inv_path.read_text(encoding="utf-8").splitlines()) <= 600 + assert len(rep_path.read_text(encoding="utf-8").splitlines()) < 750 + + for path in (inv_path, rep_path): + tree = ast.parse(path.read_text(encoding="utf-8")) + for qname, fn in _iter_functions(tree.body): + metrics = _FunctionMetrics(fn) + metrics.visit(fn) + assert metrics.statement_count <= DECISION_STATEMENT_LIMIT, (path, qname) + assert metrics.decision_points <= DECISION_POINT_LIMIT, (path, qname) + + for symbol in ( + "SourceFile", + "_word_token_mentions", + "consumer_ranking", + "divergent_value_sets", + "merge_candidate_groups", + "registered_owner_symbol_sets", + "render_inventory", + ): + assert getattr(inventory, symbol) is getattr(inventory_reports, symbol), symbol + + +def test_load_sources_rejects_tracked_symlinks(tmp_path: Path) -> None: + loopx_dir = tmp_path / "loopx" + loopx_dir.mkdir() + target = loopx_dir / "real.py" + target.write_text('NAME = "ok"\n', encoding="utf-8") + link = loopx_dir / "linked.py" + link.symlink_to(target) + + subprocess.run(["git", "init", "--quiet"], cwd=tmp_path, check=True) + subprocess.run(["git", "add", "loopx/real.py", "loopx/linked.py"], cwd=tmp_path, check=True) + + with pytest.raises(ValueError, match="tracked source must not be a symlink: loopx/linked.py"): + inventory.load_sources(tmp_path) + + +def test_python_and_typescript_facts_handle_boundaries_and_invalid_syntax() -> None: + single_literal = inventory.SourceFile( + path="loopx/single_literal.py", + suffix=".py", + text=( + "from enum import Enum\n" + "from typing import Literal\n" + "class CustomEnum(str, Enum):\n" + " _IGNORED = 'priv'\n" + " A = 'alpha'\n" + "class BrokenEnum(Enum):\n" + " A = 'alpha'\n" + " B = 42\n" + "SoloLit = Literal['only_one']\n" + "MixedLit = Literal['a', 1]\n" + "SINGLE_SET = {'only'}\n" + "PAIR_FROZEN = frozenset({'b', 'a'})\n" + "lower_case = ('a', 'b')\n" + ), + ) + facts = inventory.python_facts(single_literal) + assert facts["enums"] == [{"name": "CustomEnum", "module": "loopx/single_literal.py", "values": ["alpha"]}] + assert facts["literal_aliases"] == [ + {"name": "SoloLit", "module": "loopx/single_literal.py", "values": ["only_one"]} + ] + assert facts["closed_sets"] == [ + { + "name": "PAIR_FROZEN", + "module": "loopx/single_literal.py", + "container": "frozenset", + "values": ["b", "a"], + } + ] + + ts_src = inventory.SourceFile( + path="loopx/sample.ts", + suffix=".ts", + text=( + 'export const ACTIONS = ["run", "wait"] as const;\n' + 'export const EMPTY_LIST = [] as const;\n' + 'export const SAMPLE_SCHEMA_VERSION: string = "sample_v1";\n' + ), + ) + collected = inventory.collect_string_constants([single_literal, ts_src]) + assert collected == [ + {"name": "SAMPLE_SCHEMA_VERSION", "module": "loopx/sample.ts", "value": "sample_v1"} + ] + + broken = inventory.SourceFile(path="loopx/broken.py", suffix=".py", text="X = (\n") + with pytest.raises(ValueError, match="cannot inventory invalid Python source: loopx/broken.py:1"): + inventory.parse_python(broken) + + +def test_reports_handle_malformed_containers_non_word_tokens_and_roundtrip() -> None: + assert inventory.registered_owner_symbol_sets({"vocabularies": "not-a-map"}) == set() + with pytest.raises(KeyError): + inventory.registered_owner_symbol_sets({}) + + empty_duplicates = { + "duplicate_definitions": "malformed", + } + assert inventory.divergent_value_sets(empty_duplicates) == [] + + inv: dict[str, object] = { + "python_enums": [ + {"name": "FOO-BAR", "module": "loopx/a.py", "values": ["x", "y"]}, + {"name": "TOO_SHORT", "module": "loopx/a.py", "values": ["only"]}, + ], + "python_closed_sets": [], + "python_literal_aliases": [], + "typescript_const_arrays": [ + {"name": "TS_KIND", "module": "loopx/b.ts", "values": ["y", "x"]}, + ], + "duplicate_definitions": { + "cross_runtime_twins": [], + "multi_value_forks": [], + }, + "summary": {"source_files": 2}, + } + sources = [ + inventory.SourceFile(path="loopx/a.py", suffix=".py", text="FOO-BAR"), + inventory.SourceFile(path="loopx/c.py", suffix=".py", text="# mentions FOO-BAR"), + inventory.SourceFile(path="loopx/c.py", suffix=".py", text="TS_KIND"), + ] + ranking = inventory.consumer_ranking(inv, sources) + assert [row["name"] for row in ranking] == ["FOO-BAR", "TS_KIND", "TOO_SHORT"] + assert ranking[0]["external_consumer_modules"] == 1 + assert ranking[1]["external_consumer_modules"] == 1 + + groups = inventory.merge_candidate_groups(inv) + assert groups == [ + { + "names": ["FOO-BAR", "TS_KIND"], + "values": ["x", "y"], + "modules": ["loopx/a.py", "loopx/b.ts"], + "cross_runtime": True, + } + ] + + rendered = inventory.render_inventory(inv) + assert json.loads(rendered) == inv + assert rendered.endswith("\n") From f03e8977252d02f003f433549b1a5bf0cca647c4 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:36:37 +0800 Subject: [PATCH 2/2] fix(semantics): fail closed on malformed registry in report and owner filter Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/semantics/inventory_reports.py | 8 +- scripts/generate_semantic_inventory.py | 79 +++++++++++------ .../test_semantic_inventory_contract.py | 86 ++++++++++++++++++- 3 files changed, 145 insertions(+), 28 deletions(-) diff --git a/loopx/semantics/inventory_reports.py b/loopx/semantics/inventory_reports.py index 0cdd4c0931..c0b7fd63b3 100644 --- a/loopx/semantics/inventory_reports.py +++ b/loopx/semantics/inventory_reports.py @@ -182,12 +182,14 @@ def registered_owner_symbol_sets(registry: Mapping[str, object]) -> set[frozense sets: set[frozenset[str]] = set() vocabularies = registry["vocabularies"] if not isinstance(vocabularies, Mapping): - return sets + raise ValueError("semantic registry vocabularies must be a mapping") for vocabulary in vocabularies.values(): if not isinstance(vocabulary, Mapping): - continue + raise ValueError("semantic registry vocabulary entry must be a mapping") owners_obj = vocabulary.get("owners") - owners = owners_obj if isinstance(owners_obj, Mapping) else {} + owners = {} if owners_obj is None else owners_obj + if not isinstance(owners, Mapping): + raise ValueError("semantic registry vocabulary owners must be a mapping") symbols = frozenset( str(owner).split("::")[-1] for owner in owners.values() if owner ) diff --git a/scripts/generate_semantic_inventory.py b/scripts/generate_semantic_inventory.py index 038a25b705..fc46a4a2ef 100755 --- a/scripts/generate_semantic_inventory.py +++ b/scripts/generate_semantic_inventory.py @@ -14,6 +14,7 @@ from __future__ import annotations import argparse +from collections.abc import Mapping import json from pathlib import Path import sys @@ -54,7 +55,34 @@ def load_semantic_registry(path: Path) -> dict: return payload -def print_merge_candidates(inventory: dict) -> None: +def format_merge_candidates( + inventory: Mapping[str, object], + registry: Mapping[str, object] | None = None, +) -> list[str]: + active_registry = ( + load_semantic_registry(ROOT / REGISTRY_RELATIVE) + if registry is None + else registry + ) + groups = merge_candidate_groups(inventory, active_registry) + raw = len(merge_candidate_groups(inventory)) + lines = [ + f"merge candidates (advisory, never auto-merged): {len(groups)} to review, " + f"{raw - len(groups)} explained by a registered vocabulary's own owner symbols, " + f"{raw} raw groups" + ] + for group in sorted(groups, key=lambda item: (not item["cross_runtime"], item["names"])): + scope = "cross-runtime" if group["cross_runtime"] else "python-only" + lines.append(f" [{scope}] {', '.join(group['names'])}") + lines.append(f" values: {', '.join(group['values'])}") + lines.append(f" modules: {', '.join(group['modules'])}") + return lines + + +def print_merge_candidates( + inventory: dict, + registry: Mapping[str, object] | None = None, +) -> None: """Print the merge candidates the registry does not already explain. Advisory, like the ranking above it: an equal value set is a question for a @@ -65,19 +93,8 @@ def print_merge_candidates(inventory: dict) -> None: whose modules span both runtimes is a registry gap: the same value set lives in two runtimes with no vocabulary binding them. """ - registry = json.loads((ROOT / REGISTRY_RELATIVE).read_text(encoding="utf-8")) - groups = merge_candidate_groups(inventory, registry) - raw = len(merge_candidate_groups(inventory)) - print( - f"merge candidates (advisory, never auto-merged): {len(groups)} to review, " - f"{raw - len(groups)} explained by a registered vocabulary's own owner symbols, " - f"{raw} raw groups" - ) - for group in sorted(groups, key=lambda item: (not item["cross_runtime"], item["names"])): - scope = "cross-runtime" if group["cross_runtime"] else "python-only" - print(f" [{scope}] {', '.join(group['names'])}") - print(f" values: {', '.join(group['values'])}") - print(f" modules: {', '.join(group['modules'])}") + for line in format_merge_candidates(inventory, registry): + print(line) def main() -> int: @@ -137,26 +154,40 @@ def main() -> int: inventory = build_inventory(ROOT) content = render_inventory(inventory) if args.report: - rows = consumer_ranking(inventory, load_sources(ROOT))[: args.top] + try: + registry = load_semantic_registry(ROOT / REGISTRY_RELATIVE) + sources = load_sources(ROOT) + rows = consumer_ranking(inventory, sources)[: args.top] + divergent = divergent_value_sets(inventory)[: args.top] + merge_lines = format_merge_candidates(inventory, registry) + evidence_lines = ( + # Off by default: the per-site scan costs seconds on the full tree, + # and the ranking above answers the cheaper question. Nothing here + # gates anything, so a reviewer opts in when they want the roles. + render_consumer_evidence( + collect_consumer_evidence(ROOT, registry, sources), + top=args.top, + ) + if args.consumer_evidence + else None + ) + except (DevelopmentProbeError, ValueError) as error: + print(f"semantic report failed: {error}", file=sys.stderr) + return 1 width = max((len(row["name"]) for row in rows), default=0) print("external_consumer_modules values name module") for row in rows: print(f"{row['external_consumer_modules']:>25} {row['values']:>6} {row['name']:<{width}} {row['module']}") - divergent = divergent_value_sets(inventory)[: args.top] print() print("value_sets name definition_modules") for entry in divergent: print(f"{entry['value_sets']:>10} {entry['name']} {', '.join(entry['definition_modules'])}") print() - print_merge_candidates(inventory) - if args.consumer_evidence: - # Off by default: the per-site scan costs seconds on the full tree, - # and the ranking above answers the cheaper question. Nothing here - # gates anything, so a reviewer opts in when they want the roles. + for line in merge_lines: + print(line) + if evidence_lines is not None: print() - registry = json.loads((ROOT / REGISTRY_RELATIVE).read_text(encoding="utf-8")) - evidence = collect_consumer_evidence(ROOT, registry, load_sources(ROOT)) - print("\n".join(render_consumer_evidence(evidence, top=args.top))) + print("\n".join(evidence_lines)) return 0 if args.output is None: print(content, end="") diff --git a/tests/architecture/test_semantic_inventory_contract.py b/tests/architecture/test_semantic_inventory_contract.py index 8b6d17e936..4c368e424f 100644 --- a/tests/architecture/test_semantic_inventory_contract.py +++ b/tests/architecture/test_semantic_inventory_contract.py @@ -5,8 +5,10 @@ import ast import io import json +import os from pathlib import Path import subprocess +import sys import tokenize import pytest @@ -146,7 +148,19 @@ def test_python_and_typescript_facts_handle_boundaries_and_invalid_syntax() -> N def test_reports_handle_malformed_containers_non_word_tokens_and_roundtrip() -> None: - assert inventory.registered_owner_symbol_sets({"vocabularies": "not-a-map"}) == set() + with pytest.raises(ValueError, match="vocabularies must be a mapping"): + inventory.registered_owner_symbol_sets({"vocabularies": "not-a-map"}) + with pytest.raises(ValueError, match="vocabulary entry must be a mapping"): + inventory.registered_owner_symbol_sets({"vocabularies": {"broken": "not-a-map"}}) + with pytest.raises(ValueError, match="owners must be a mapping"): + inventory.registered_owner_symbol_sets( + {"vocabularies": {"broken": {"owners": "not-a-map"}}} + ) + assert inventory.registered_owner_symbol_sets({"vocabularies": {"no_owners": {}}}) == set() + assert ( + inventory.registered_owner_symbol_sets({"vocabularies": {"none_owners": {"owners": None}}}) + == set() + ) with pytest.raises(KeyError): inventory.registered_owner_symbol_sets({}) @@ -194,3 +208,73 @@ def test_reports_handle_malformed_containers_non_word_tokens_and_roundtrip() -> rendered = inventory.render_inventory(inv) assert json.loads(rendered) == inv assert rendered.endswith("\n") + + +_REPORT_CLI_FILES = ( + "scripts/generate_semantic_inventory.py", + "loopx/__init__.py", + "loopx/semantics/__init__.py", + "loopx/semantics/inventory.py", + "loopx/semantics/inventory_reports.py", + "loopx/semantics/development_probe.py", + "loopx/semantics/consumer_report.py", + "loopx/semantics/field_use.py", + "loopx/semantics/production.py", + "loopx/semantics/python_production.py", +) + + +def _run_report_cli(repo_root: Path) -> subprocess.CompletedProcess[str]: + env = { + key: value + for key, value in os.environ.items() + if not key.startswith(("COV_CORE_", "COVERAGE_")) + } + return subprocess.run( + [sys.executable, "scripts/generate_semantic_inventory.py", "--report"], + cwd=repo_root, + env=env, + capture_output=True, + text=True, + check=False, + ) + + +def test_report_cli_fails_closed_on_malformed_registry(tmp_path: Path) -> None: + for relative in _REPORT_CLI_FILES: + target = tmp_path / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes((REPO_ROOT / relative).read_bytes()) + + sample = tmp_path / "loopx" / "sample_vocab.py" + sample.write_text('SAMPLE_STATES = ("alpha", "beta")\n', encoding="utf-8") + registry_path = tmp_path / "loopx" / "semantics" / "vocabulary_v0.json" + registry_path.write_text( + json.dumps( + { + "vocabularies": { + "sample_state": { + "owners": {"python": "loopx/sample_vocab.py::SAMPLE_STATES"} + } + } + } + ), + encoding="utf-8", + ) + subprocess.run(["git", "init", "--quiet"], cwd=tmp_path, check=True) + subprocess.run(["git", "add", "."], cwd=tmp_path, check=True) + + valid = _run_report_cli(tmp_path) + assert valid.returncode == 0, valid.stderr + assert "merge candidates (advisory, never auto-merged):" in valid.stdout + + for payload, expected_diagnostic in ( + ({"vocabularies": "not-a-map"}, "vocabularies map"), + ({"vocabularies": {"broken": "not-a-map"}}, "vocabulary entry must be a mapping"), + ({"vocabularies": {"broken": {"owners": "not-a-map"}}}, "owners must be a mapping"), + ): + registry_path.write_text(json.dumps(payload), encoding="utf-8") + failed = _run_report_cli(tmp_path) + assert failed.returncode != 0 + assert "0 explained" not in failed.stdout + assert expected_diagnostic in failed.stderr