diff --git a/examples/semantic-vocabulary-drift-smoke.py b/examples/semantic-vocabulary-drift-smoke.py index 651fe2ca62..1042c8cbd9 100755 --- a/examples/semantic-vocabulary-drift-smoke.py +++ b/examples/semantic-vocabulary-drift-smoke.py @@ -32,7 +32,9 @@ build_inventory, collect_string_constants, load_sources, + parse_python, python_facts, + python_facts_from_tree, render_inventory as render_inventory, string_constant_definitions, typescript_facts, @@ -40,13 +42,22 @@ from loopx.semantics.production import ( # noqa: E402 collect_production, validate_production, INPUT_WITNESSES, quota_action_domain, collect_literal_uses, - PRODUCER_FILES, PRODUCER_ROOTS, + PRODUCER_FILES, PRODUCER_ROOTS, submit_typescript_batch_scan, +) +from loopx.semantics.python_production import ( # noqa: E402 + _TREES as _PYTHON_PRODUCTION_TREES, + python_literal_uses, + scan_python_production, ) -from loopx.semantics.python_production import scan_python_production # noqa: E402 from loopx.semantics.field_use import ( # noqa: E402 - FACTS, ROLES, field_use_summary, lexical_module_count, render_field_uses, scan_field_uses, + FACTS, ROLES, field_use_summary, lexical_module_count, + python_module_scan_with_mention, render_field_uses, scan_field_uses, ) from loopx.semantics.project_registry_io import ( # noqa: E402 + _excluded as _excluded_registry_io, + load_registry_io_sources_from_base, + registry_io_javascript_request, + scan_python_registry_io, validate_project_registry_io_manifest, ) from scripts.generate_semantic_bindings import build_artifacts # noqa: E402 @@ -579,9 +590,7 @@ def check_invariant_domain(invariant: dict[str, Any], registry: dict[str, Any]) RETIRED_LEASE_INPUT_SYMBOLS = frozenset({"LeaseAction", "LeaseModeGateCommand", "CoordinationCommand"}) -def check_retired_lease_input(registry: dict[str, Any], sources: list[SourceFile]) -> None: - from importlib.util import resolve_name - +def _check_retired_lease_registry(registry: dict[str, Any]) -> None: require("lease_action" not in registry["vocabularies"], "retired lease input must not return to the registry") lifecycle = registry["vocabularies"].get("task_lease_lifecycle_operation", {}) @@ -589,28 +598,53 @@ def check_retired_lease_input(registry: dict[str, Any], sources: list[SourceFile "python": None, "typescript": "loopx/control_plane/work_items/task_lease_lifecycle_request.ts::TASK_LEASE_LIFECYCLE_OPERATIONS", }, "native lease lifecycle coverage must retain its actual owner") + + +def _check_retired_lease_source_tree( + source: SourceFile, tree: ast.Module, resolve_name_fn: Callable[[str, str], str], +) -> None: + module = source.path.removesuffix(".py").replace("/", ".") + if ( + module != RETIRED_LEASE_INPUT_MODULE + and "authority_core" not in source.text + and source.text.isascii() + ): + return + package = module.rpartition(".")[0] + for node in ast.walk(tree): + if module == RETIRED_LEASE_INPUT_MODULE: + names = set() + if isinstance(node, (ast.ClassDef, ast.FunctionDef)): + names.add(node.name) + elif isinstance(node, ast.Assign): + names.update(target.id for target in node.targets if isinstance(target, ast.Name)) + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.add(node.target.id) + retired = sorted(names & RETIRED_LEASE_INPUT_SYMBOLS) + if retired: + raise Drift(f"{source.path}:{node.lineno}: retired lease input definition {retired}") + if isinstance(node, ast.ImportFrom): + target = resolve_name_fn("." * node.level + (node.module or ""), package) if node.level else node.module + if target == RETIRED_LEASE_INPUT_MODULE: + retired = sorted({alias.name for alias in node.names} & RETIRED_LEASE_INPUT_SYMBOLS) + require(not retired, f"{source.path}:{node.lineno}: retired lease input import {retired}") + + +def check_retired_lease_input(registry: dict[str, Any], sources: list[SourceFile]) -> None: + from importlib.util import resolve_name + + _check_retired_lease_registry(registry) for source in sources: if source.suffix != ".py": continue module = source.path.removesuffix(".py").replace("/", ".") - package = module.rpartition(".")[0] - for node in ast.walk(ast.parse(source.text)): - if module == RETIRED_LEASE_INPUT_MODULE: - names = set() - if isinstance(node, (ast.ClassDef, ast.FunctionDef)): - names.add(node.name) - elif isinstance(node, ast.Assign): - names.update(target.id for target in node.targets if isinstance(target, ast.Name)) - elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): - names.add(node.target.id) - retired = sorted(names & RETIRED_LEASE_INPUT_SYMBOLS) - if retired: - raise Drift(f"{source.path}:{node.lineno}: retired lease input definition {retired}") - if isinstance(node, ast.ImportFrom): - target = resolve_name("." * node.level + (node.module or ""), package) if node.level else node.module - if target == RETIRED_LEASE_INPUT_MODULE: - retired = sorted({alias.name for alias in node.names} & RETIRED_LEASE_INPUT_SYMBOLS) - require(not retired, f"{source.path}:{node.lineno}: retired lease input import {retired}") + if ( + module != RETIRED_LEASE_INPUT_MODULE + and source.text.isascii() + and "authority_core" not in source.text + ): + continue + _check_retired_lease_source_tree(source, ast.parse(source.text), resolve_name) def check_coverage_floor(registry: dict[str, Any]) -> str: @@ -710,18 +744,135 @@ def check_owned_vocabularies(registry: dict[str, Any], inventory: dict[str, Any] # --- literal scan ------------------------------------------------------------------- -def scan_literals(field: str, roots: list[str], suffixes: list[str], sources: list[SourceFile]) -> dict[str, set[str]]: +def scan_literals( + field: str, + roots: list[str], + suffixes: list[str], + sources: list[SourceFile], + *, + ts_rows: list[dict[str, Any]] | None = None, + py_observed: dict[str, set[str]] | None = None, +) -> dict[str, set[str]]: selected = [source for source in sources if source.suffix in suffixes and any(source.path.startswith(root.rstrip('/') + '/') for root in roots)] - return collect_literal_uses(REPO_ROOT, field, selected) + if py_observed is None: + return collect_literal_uses(REPO_ROOT, field, selected, ts_rows=ts_rows) + observed: dict[str, set[str]] = { + value: set(paths) for value, paths in py_observed.items() + } + ts_only = [source for source in selected if source.suffix == ".ts"] + for value, paths in collect_literal_uses(REPO_ROOT, field, ts_only, ts_rows=ts_rows).items(): + observed.setdefault(value, set()).update(paths) + return observed -def check_literal_vocabularies(registry: dict[str, Any], sources: list[SourceFile]) -> None: +def _ts_literal_batch_requests( + registry: dict[str, Any], ts_sources: list[SourceFile] +) -> list[dict[str, Any]]: + requests: list[dict[str, Any]] = [] + for name, vocabulary in registry["vocabularies"].items(): + scan = vocabulary.get("literal_scan") + if not scan or ".ts" not in scan["suffixes"]: + continue + roots = tuple(root.rstrip("/") + "/" for root in scan["roots"]) + requests.append( + { + "id": f"literal:{name}", + "mode": "literal_uses", + "field": scan["field"], + "return_functions": [], + "paths": [ + s.path for s in ts_sources if any(s.path.startswith(root) for root in roots) + ], + } + ) + return requests + + +def _ts_producer_batch_requests( + registry: dict[str, Any], ts_sources: list[SourceFile] +) -> list[dict[str, Any]]: + producer_ts_paths = [ + s.path + for s in ts_sources + if ( + s.path in PRODUCER_FILES + or any(s.path.startswith(prefix + "/") for prefix in PRODUCER_ROOTS) + ) + ] + if not producer_ts_paths: + return [] + requests: list[dict[str, Any]] = [] + for name, vocabulary in registry["vocabularies"].items(): + if "producers" not in vocabulary: + continue + field = vocabulary.get("literal_scan", {}).get("field") + returns = vocabulary.get("return_producers", []) + if field or returns: + item: dict[str, Any] = { + "id": f"producer:{name}", + "mode": "production", + "return_functions": returns, + "paths": producer_ts_paths, + } + if field: + item["field"] = field + requests.append(item) + return requests + + +def check_literal_vocabularies( + registry: dict[str, Any], + sources: list[SourceFile], + *, + ts_rows_by_vocab: dict[str, list[dict[str, Any]]] | None = None, + py_uses_by_vocab: dict[str, dict[str, set[str]]] | None = None, +) -> None: + if ts_rows_by_vocab is None: + ts_sources = [s for s in sources if s.suffix == ".ts"] + requests = _ts_literal_batch_requests(registry, ts_sources) + if requests: + batch = submit_typescript_batch_scan(REPO_ROOT, ts_sources, requests)() + ts_rows_by_vocab = { + req["id"].removeprefix("literal:"): batch.get(req["id"], []) + for req in requests + } + else: + ts_rows_by_vocab = {} + if py_uses_by_vocab is None: + py_targets: list[tuple[str, str, tuple[str, ...]]] = [] + for name, vocabulary in registry["vocabularies"].items(): + scan = vocabulary.get("literal_scan") + if scan and ".py" in scan["suffixes"]: + roots = tuple(root.rstrip("/") + "/" for root in scan["roots"]) + py_targets.append((name, scan["field"], roots)) + py_uses_by_vocab = {name: {} for name, _, _ in py_targets} + for source in sources: + if source.suffix != ".py": + continue + matching = [ + (name, field) + for name, field, roots in py_targets + if any(source.path.startswith(root) for root in roots) + ] + if not matching: + continue + tree = ast.parse(source.text, filename=source.path) + for name, field in matching: + for value in python_literal_uses(source, field, tree=tree): + py_uses_by_vocab[name].setdefault(value, set()).add(source.path) for name, vocabulary in registry["vocabularies"].items(): scan = vocabulary.get("literal_scan") if not scan: continue - observed = scan_literals(scan["field"], scan["roots"], scan["suffixes"], sources) + observed = scan_literals( + scan["field"], + scan["roots"], + scan["suffixes"], + sources, + ts_rows=ts_rows_by_vocab.get(name) if ts_rows_by_vocab is not None else None, + py_observed=py_uses_by_vocab.get(name) if py_uses_by_vocab is not None else None, + ) expected = quota_action_domain(registry) if name == 'effective_action' else set(vocabulary["values"]) unregistered = {value: sorted(files) for value, files in observed.items() if value not in expected} require(not unregistered, f"{name}: literals not in the registry (register them or use a registered value): {unregistered}") @@ -845,21 +996,71 @@ def summarise_formal_domains(registry: dict[str, Any], sources: list[SourceFile] ) -def check_producers(registry: dict[str, Any], sources: list[SourceFile]) -> list[str]: - unknown: list[str] = [] - for name, vocabulary in registry['vocabularies'].items(): - if 'producers' not in vocabulary: - # Skipped: a vocabulary that declares no producers. That is every - # cross_runtime vocabulary except the ones carrying an executed - # witness. F1/F2 therefore hold over the walked set the registry's - # formal_model names Producers(V) -- not an unconditional claim. - continue +def check_producers( + registry: dict[str, Any], + sources: list[SourceFile], + *, + ts_rows_by_vocab: dict[str, list[dict[str, Any]]] | None = None, +) -> list[str]: + added_trees: list[SourceFile] = [] + if ts_rows_by_vocab is None: + ts_sources = [s for s in sources if s.suffix == ".ts"] + requests = _ts_producer_batch_requests(registry, ts_sources) try: - rows = collect_production(REPO_ROOT, vocabulary, sources) - field_domain = quota_action_domain(registry) if name == 'effective_action' else None - unknown.extend(validate_production(name, vocabulary, rows, field_domain=field_domain)) + finish_ts = ( + submit_typescript_batch_scan(REPO_ROOT, ts_sources, requests) + if requests + else None + ) + for source in sources: + if ( + source.suffix == ".py" + and source not in _PYTHON_PRODUCTION_TREES + and ( + source.path in PRODUCER_FILES + or any(source.path.startswith(prefix + "/") for prefix in PRODUCER_ROOTS) + ) + ): + try: + _PYTHON_PRODUCTION_TREES[source] = ast.parse( + source.text, filename=source.path + ) + except SyntaxError: + pass + else: + added_trees.append(source) + batch = finish_ts() if finish_ts is not None else {} except ValueError as error: + for source in added_trees: + _PYTHON_PRODUCTION_TREES.pop(source, None) raise Drift(str(error)) from error + ts_rows_by_vocab = { + req["id"].removeprefix("producer:"): batch.get(req["id"], []) + for req in requests + } + unknown: list[str] = [] + try: + for name, vocabulary in registry["vocabularies"].items(): + if "producers" not in vocabulary: + # Skipped: a vocabulary that declares no producers. That is every + # cross_runtime vocabulary except the ones carrying an executed + # witness. F1/F2 therefore hold over the walked set the registry's + # formal_model names Producers(V) -- not an unconditional claim. + continue + try: + rows = collect_production( + REPO_ROOT, + vocabulary, + sources, + ts_rows=ts_rows_by_vocab.get(name), + ) + field_domain = quota_action_domain(registry) if name == "effective_action" else None + unknown.extend(validate_production(name, vocabulary, rows, field_domain=field_domain)) + except ValueError as error: + raise Drift(str(error)) from error + finally: + for source in added_trees: + _PYTHON_PRODUCTION_TREES.pop(source, None) return sorted(set(unknown)) @@ -924,8 +1125,15 @@ def check_projections(registry: dict[str, Any]) -> None: require(actual is LoopDisposition(expected), f"route {route} projects {actual.value}, registry says {expected}") -def check_schema_version_owners(registry: dict[str, Any], sources: list[SourceFile]) -> None: - definitions = string_constant_definitions(collect_string_constants(sources)) +def check_schema_version_owners( + registry: dict[str, Any], + sources: list[SourceFile], + *, + python_facts_map: dict[SourceFile, dict[str, list[Any]]] | None = None, +) -> None: + definitions = string_constant_definitions( + collect_string_constants(sources, python_facts_map=python_facts_map) + ) for name, entry in registry["schema_versions"].items(): defining = definitions.get(entry["constant"], []) modules = sorted(item["module"] for item in defining) @@ -1013,7 +1221,13 @@ def count_identifier_modules(field: str, suffix: str, sources: list[SourceFile]) return lexical_module_count(field, suffix, sources) -def check_reader_metric(registry: dict[str, Any], sources: list[SourceFile]) -> tuple[list[str], list[str]]: +def check_reader_metric( + registry: dict[str, Any], + sources: list[SourceFile], + *, + ts_rows_override: dict[str, dict[str, Any]] | None = None, + python_scan_override: dict[str, tuple[dict[str, set[str]], int]] | None = None, +) -> tuple[list[str], list[str]]: """Check the B3 syntactic metric against the ledger, and report its roles. Four obligations, all measured rather than assumed: @@ -1040,7 +1254,12 @@ def check_reader_metric(registry: dict[str, Any], sources: list[SourceFile]) -> is not thereby proven dead. The smoke says so in its own output. """ ledger = registry["retirement_ledger"]["should_run_legacy_decision_fields"]["fields"] - summary = field_use_summary(ledger, sources) + summary = field_use_summary( + ledger, + sources, + ts_rows_override=ts_rows_override, + python_scan_override=python_scan_override, + ) report: list[str] = [] detail: list[str] = [] for field in sorted(ledger): @@ -1136,8 +1355,13 @@ def evaluate_inventory_budget_findings( ) -def check_inventory(registry: dict[str, Any], sources: list[SourceFile]) -> tuple[dict[str, Any], str]: - inventory = build_inventory(REPO_ROOT, sources=sources) +def check_inventory( + registry: dict[str, Any], + sources: list[SourceFile], + *, + python_facts_map: dict[SourceFile, dict[str, list[Any]]] | None = None, +) -> tuple[dict[str, Any], str]: + inventory = build_inventory(REPO_ROOT, sources=sources, python_facts_map=python_facts_map) require(inventory["schema_version"] == INVENTORY_SCHEMA_VERSION, "inventory schema drift") semantic_multi_value_forks = check_scope_declarations(registry, inventory) ratchets = registry["inventory_ratchets"] @@ -1169,16 +1393,191 @@ def check_inventory(registry: dict[str, Any], sources: list[SourceFile]) -> tupl return inventory, " ".join(parts) +_DEFAULT_VALIDATE_PROJECT_REGISTRY_IO_MANIFEST = validate_project_registry_io_manifest +_DEFAULT_CHECK_RETIRED_LEASE_INPUT = check_retired_lease_input + + +def _collect_single_pass_scans( + registry: dict[str, Any], + sources: list[SourceFile], + reg_sources: list[SourceFile], + *, + check_retired_lease: bool = False, +) -> tuple[ + dict[SourceFile, dict[str, list[Any]]], + list[Any], + dict[str, dict[str, set[str]]], + dict[str, tuple[dict[str, set[str]], int]], + dict[str, Any], + dict[SourceFile, ast.Module], +]: + """Run one streaming Python AST pass concurrently with one batched Node TS AST pass.""" + from importlib.util import resolve_name + + literal_targets: list[tuple[str, str, tuple[str, ...], bool]] = [] + for name, vocabulary in registry["vocabularies"].items(): + scan = vocabulary.get("literal_scan") + if scan: + roots = tuple(root.rstrip("/") + "/" for root in scan["roots"]) + suffixes = scan["suffixes"] + literal_targets.append((name, scan["field"], roots, ".py" in suffixes)) + py_uses_by_vocab: dict[str, dict[str, set[str]]] = { + name: {} for name, *_ in literal_targets + } + ledger_fields = frozenset( + registry["retirement_ledger"]["should_run_legacy_decision_fields"]["fields"] + ) + ts_by_path: dict[str, SourceFile] = {} + for source in reg_sources: + if source.suffix in {".ts", ".tsx", ".js", ".mjs"}: + ts_by_path[source.path] = source + for source in sources: + if source.suffix == ".ts": + ts_by_path.setdefault(source.path, source) + + ts_sources = [s for s in sources if s.suffix == ".ts"] + batch_requests: list[dict[str, Any]] = [ + { + "id": "registry_io", + "paths": [ + s.path + for s in reg_sources + if s.suffix in {".ts", ".tsx", ".js", ".mjs"} + ], + **registry_io_javascript_request(), + }, + { + "id": "field_uses", + "mode": "field_uses", + "fields": sorted(ledger_fields), + "paths": [s.path for s in ts_sources], + }, + *_ts_literal_batch_requests(registry, ts_sources), + *_ts_producer_batch_requests(registry, ts_sources), + ] + + all_ts_sources = [ts_by_path[path] for path in sorted(ts_by_path)] + try: + finish_ts = submit_typescript_batch_scan(REPO_ROOT, all_ts_sources, batch_requests) + except ValueError as error: + raise Drift(str(error)) from error + + python_facts_map: dict[SourceFile, dict[str, list[Any]]] = {} + py_registry_obs: list[Any] = [] + py_field_scan: dict[str, tuple[dict[str, set[str]], int]] = {} + producer_trees: dict[SourceFile, ast.Module] = {} + single_literal_target = ( + literal_targets[0] + if len(literal_targets) == 1 and literal_targets[0][3] + else None + ) + + try: + if check_retired_lease: + _check_retired_lease_registry(registry) + for source in sources: + if source.suffix != ".py": + continue + try: + tree = parse_python(source) + except ValueError as error: + if not _excluded_registry_io(source.path): + message = str(error).replace("cannot inventory invalid Python source:", "cannot scan invalid Python source:", 1) + raise ValueError(message) from None + raise + if check_retired_lease: + _check_retired_lease_source_tree(source, tree, resolve_name) + python_facts_map[source] = python_facts_from_tree(source, tree) + if not _excluded_registry_io(source.path): + py_registry_obs.extend(scan_python_registry_io(source, tree=tree)) + present = frozenset(field for field in ledger_fields if field in source.text) + if single_literal_target is not None: + lit_name, lit_field, lit_roots, _ = single_literal_target + wants_lit = any(source.path.startswith(root) for root in lit_roots) + forms, dynamic_sites, mentioned = python_module_scan_with_mention( + tree, present, lit_field if wants_lit else None + ) + py_field_scan[source.path] = (forms, dynamic_sites) + if wants_lit and mentioned: + for value in python_literal_uses(source, lit_field, tree=tree): + py_uses_by_vocab[lit_name].setdefault(value, set()).add(source.path) + else: + forms, dynamic_sites, _ = python_module_scan_with_mention(tree, present) + py_field_scan[source.path] = (forms, dynamic_sites) + for name, field, roots, wants_py in literal_targets: + if wants_py and any(source.path.startswith(root) for root in roots): + for value in python_literal_uses(source, field, tree=tree): + py_uses_by_vocab[name].setdefault(value, set()).add(source.path) + if ( + source.path in PRODUCER_FILES + or any(source.path.startswith(prefix + "/") for prefix in PRODUCER_ROOTS) + ): + producer_trees[source] = tree + batch_results = finish_ts() + except Exception as error: + if isinstance(error, ValueError): + # Ensure background TS future settles before propagating or raising Drift. + try: + finish_ts() + except ValueError as ts_error: + raise Drift(str(ts_error)) from ts_error + raise + if isinstance(error, Drift): + try: + finish_ts() + except Exception: + pass + raise + try: + finish_ts() + except Exception: + pass + raise + return python_facts_map, py_registry_obs, py_uses_by_vocab, py_field_scan, batch_results, producer_trees + + def main() -> int: registry = load_registry() coverage = check_coverage_floor(registry) sources = load_sources(REPO_ROOT) - check_retired_lease_input(registry, sources) - registry_io_errors = validate_project_registry_io_manifest(REPO_ROOT) - require(not registry_io_errors, "; ".join(registry_io_errors) - + "; inspect with uv run python scripts/generate_project_registry_io_manifest.py " - "and review direct-I/O classifications in project_registry_io_classifications_v1.json") - inventory, ratchets = check_inventory(registry, sources) + custom_retired_check = ( + check_retired_lease_input is not _DEFAULT_CHECK_RETIRED_LEASE_INPUT + ) + if custom_retired_check: + check_retired_lease_input(registry, sources) + custom_registry_io_check = ( + validate_project_registry_io_manifest is not _DEFAULT_VALIDATE_PROJECT_REGISTRY_IO_MANIFEST + ) + if custom_registry_io_check: + registry_io_errors = validate_project_registry_io_manifest(REPO_ROOT) + require(not registry_io_errors, "; ".join(registry_io_errors) + + "; inspect with uv run python scripts/generate_project_registry_io_manifest.py " + "and review direct-I/O classifications in project_registry_io_classifications_v1.json") + reg_sources = load_registry_io_sources_from_base(REPO_ROOT, sources) + ( + python_facts_map, + py_registry_obs, + py_uses_by_vocab, + py_field_scan, + batch_results, + producer_trees, + ) = _collect_single_pass_scans( + registry, + sources, + reg_sources, + check_retired_lease=not custom_retired_check, + ) + if not custom_registry_io_check: + registry_io_errors = validate_project_registry_io_manifest( + REPO_ROOT, + sources=reg_sources, + precomputed_python_observations=py_registry_obs, + precomputed_js_rows=batch_results.get("registry_io", []), + ) + require(not registry_io_errors, "; ".join(registry_io_errors) + + "; inspect with uv run python scripts/generate_project_registry_io_manifest.py " + "and review direct-I/O classifications in project_registry_io_classifications_v1.json") + inventory, ratchets = check_inventory(registry, sources, python_facts_map=python_facts_map) check_owned_vocabularies(registry, inventory) for path, expected in build_artifacts().items(): require( @@ -1186,13 +1585,43 @@ def main() -> int: f"{path.relative_to(REPO_ROOT)} is stale; " "run uv run python scripts/generate_semantic_bindings.py and commit the result", ) - check_literal_vocabularies(registry, sources) - unknown_producers = check_producers(registry, sources) + ts_literal_rows = { + name: batch_results.get(f"literal:{name}", []) + for name, vocabulary in registry["vocabularies"].items() + if vocabulary.get("literal_scan") and ".ts" in vocabulary["literal_scan"]["suffixes"] + } + check_literal_vocabularies( + registry, + sources, + ts_rows_by_vocab=ts_literal_rows, + py_uses_by_vocab=py_uses_by_vocab, + ) + ts_producer_rows = { + name: batch_results.get(f"producer:{name}", []) + for name, vocabulary in registry["vocabularies"].items() + if "producers" in vocabulary + } + added_producer_trees = [ + source for source in producer_trees if source not in _PYTHON_PRODUCTION_TREES + ] + for source in added_producer_trees: + _PYTHON_PRODUCTION_TREES[source] = producer_trees[source] + try: + unknown_producers = check_producers(registry, sources, ts_rows_by_vocab=ts_producer_rows) + finally: + for source in added_producer_trees: + _PYTHON_PRODUCTION_TREES.pop(source, None) check_relations(registry) check_projections(registry) - check_schema_version_owners(registry, sources) + check_schema_version_owners(registry, sources, python_facts_map=python_facts_map) budgets = check_retirement_budgets(registry, sources) - reader_metric, reader_detail = check_reader_metric(registry, sources) + ts_field_rows = {row["path"]: row for row in batch_results.get("field_uses", [])} + reader_metric, reader_detail = check_reader_metric( + registry, + sources, + ts_rows_override=ts_field_rows, + python_scan_override=py_field_scan, + ) twins = check_dual_runtime_twins(registry) print("semantic-vocabulary-drift-smoke: ok") print(" " + coverage) @@ -1213,7 +1642,12 @@ def main() -> int: for line in reader_detail: print(f" retirement_role: {line}") ledger_fields = registry["retirement_ledger"]["should_run_legacy_decision_fields"]["fields"] - uses, _ = scan_field_uses(ledger_fields, sources) + uses, _ = scan_field_uses( + ledger_fields, + sources, + ts_rows_override=ts_field_rows, + python_scan_override=py_field_scan, + ) for line in render_field_uses(uses): print(f" field_use: {line}") return 0 diff --git a/loopx/semantics/field_use.py b/loopx/semantics/field_use.py index 01703a8080..800381edea 100644 --- a/loopx/semantics/field_use.py +++ b/loopx/semantics/field_use.py @@ -41,11 +41,12 @@ from __future__ import annotations import ast +from collections.abc import Iterable, Mapping from dataclasses import dataclass from functools import lru_cache from pathlib import Path import re -from typing import Any, Iterable +from typing import Any from .inventory import SourceFile, parse_python from .production import run_typescript_scan @@ -179,7 +180,40 @@ def python_module_scan(tree: ast.AST, fields: frozenset[str]) -> tuple[dict[str, paid by everyone. Parsing errors share the inventory's ``parse_python`` boundary; ASTs are deliberately not retained in a cache. """ + found, dynamic_sites, _ = python_module_scan_with_mention(tree, fields) + return found, dynamic_sites + + +def python_module_scan_with_mention( + tree: ast.AST, + fields: frozenset[str], + literal_field: str | None = None, +) -> tuple[dict[str, set[str]], int, bool]: + """Scan field uses plus optional presence of ``literal_field`` in one walk.""" found: dict[str, set[str]] = {} + mentioned = False + if not fields: + # Fast path: when no requested field token appears anywhere in the + # module text, only computed mapping-accessor call sites are needed. + dynamic_sites = 0 + for node in ast.walk(tree): + node_type = type(node) + if literal_field is not None and not mentioned: + if node_type is ast.Name and node.id == literal_field: + mentioned = True + elif node_type is ast.Attribute and node.attr == literal_field: + mentioned = True + elif node_type is ast.Constant and node.value == literal_field: + mentioned = True + elif node_type is ast.keyword and node.arg == literal_field: + mentioned = True + if node_type is ast.Call and type(node.func) is ast.Attribute and node.args: + attr = node.func.attr + if attr in MAPPING_READ_CALLS or attr in MAPPING_WRITE_CALLS: + arg0 = node.args[0] + if not (type(arg0) is ast.Constant and type(arg0.value) is str): + dynamic_sites += 1 + return found, dynamic_sites, mentioned # Constants consumed as a literal key. Whatever is left over is the field # name travelling as data, which is how a computed access is written. keyed: set[int] = set() @@ -190,6 +224,16 @@ def record(field: str, form: str) -> None: found.setdefault(field, set()).add(form) for node in ast.walk(tree): + node_type = type(node) + if literal_field is not None and not mentioned: + if node_type is ast.Name and node.id == literal_field: + mentioned = True + elif node_type is ast.Attribute and node.attr == literal_field: + mentioned = True + elif node_type is ast.Constant and node.value == literal_field: + mentioned = True + elif node_type is ast.keyword and node.arg == literal_field: + mentioned = True key = _literal_key(node) if key is not None: if key in fields: @@ -252,7 +296,7 @@ def record(field: str, form: str) -> None: for identity, key in seen_constants: if identity not in keyed: record(key, "name_constant") - return found, dynamic_sites + return found, dynamic_sites, mentioned @lru_cache(maxsize=256) @@ -271,7 +315,11 @@ def lexical_module_count(field: str, suffix: str, sources: Iterable[SourceFile]) def scan_field_uses( - fields: Iterable[str], sources: Iterable[SourceFile], + fields: Iterable[str], + sources: Iterable[SourceFile], + *, + ts_rows_override: Mapping[str, Mapping[str, Any]] | None = None, + python_scan_override: Mapping[str, tuple[dict[str, set[str]], int]] | None = None, ) -> tuple[list[FieldUse], UnresolvedKeySites]: """Classify every module's use of each field, beside the standing unknown.""" wanted = frozenset(fields) @@ -286,13 +334,16 @@ def scan_field_uses( # population costs one parse and adds no per-field work. Measured on 145 # tracked modules: 0.86s narrowed against 0.52s more for all of them, and # the unknown it reports rises from 82 sites to 395. - ts_sources = [source for source in materialized if source.suffix == ".ts"] - # One AST request for the complete TS population, not one Node process per - # module/field. Reuse the producer scanner's parser and safe error boundary. - ts_rows = {row["path"]: row for row in run_typescript_scan( - Path(__file__).resolve().parents[2], ts_sources, - {"mode": "field_uses", "fields": sorted(wanted)}, - )} + if ts_rows_override is not None: + ts_rows = ts_rows_override + else: + ts_sources = [source for source in materialized if source.suffix == ".ts"] + # One AST request for the complete TS population, not one Node process per + # module/field. Reuse the producer scanner's parser and safe error boundary. + ts_rows = {row["path"]: row for row in run_typescript_scan( + Path(__file__).resolve().parents[2], ts_sources, + {"mode": "field_uses", "fields": sorted(wanted)}, + )} ts_dynamic_sites = sum(int(row.get("dynamic_member_sites") or 0) for row in ts_rows.values()) for source in materialized: # Every Python module contributes to the computed-key total whether or @@ -300,23 +351,26 @@ def scan_field_uses( # per-field work, never the standing unknown. present = frozenset(field for field in wanted if field in source.text) if source.suffix == ".py": - try: - tree = parse_python(source) - except (SyntaxError, ValueError): - # An unparseable tracked module is a measurement gap, and a gap - # may hold readers. Calling it a mention would shrink the - # migration surface on the strength of a parse failure, so it is - # recorded as this field's unknown and stays in the surface - # until someone reads the module. Failing closed here is worse: - # a direct caller scanning a work-in-progress tree would get an - # exception instead of a measurement. The inventory scan rejects - # such a module first, so the drift smoke never reaches this. - for field in wanted: - if lexical_module_count(field, ".py", [source]): - uses.append(FieldUse(field=field, module=source.path, - forms=frozenset({"unparsed_module"}))) - continue - forms, module_dynamic_sites = python_module_scan(tree, present) + if python_scan_override is not None and source.path in python_scan_override: + forms, module_dynamic_sites = python_scan_override[source.path] + else: + try: + tree = parse_python(source) + except (SyntaxError, ValueError): + # An unparseable tracked module is a measurement gap, and a gap + # may hold readers. Calling it a mention would shrink the + # migration surface on the strength of a parse failure, so it is + # recorded as this field's unknown and stays in the surface + # until someone reads the module. Failing closed here is worse: + # a direct caller scanning a work-in-progress tree would get an + # exception instead of a measurement. The inventory scan rejects + # such a module first, so the drift smoke never reaches this. + for field in wanted: + if lexical_module_count(field, ".py", [source]): + uses.append(FieldUse(field=field, module=source.path, + forms=frozenset({"unparsed_module"}))) + continue + forms, module_dynamic_sites = python_module_scan(tree, present) dynamic_sites += module_dynamic_sites elif source.suffix == ".ts": row = ts_rows.get(source.path) or {} @@ -360,7 +414,13 @@ def scan_field_uses( ) -def field_use_summary(fields: Iterable[str], sources: Iterable[SourceFile]) -> dict[str, Any]: +def field_use_summary( + fields: Iterable[str], + sources: Iterable[SourceFile], + *, + ts_rows_override: Mapping[str, Mapping[str, Any]] | None = None, + python_scan_override: Mapping[str, tuple[dict[str, set[str]], int]] | None = None, +) -> dict[str, Any]: """Per-field use counts and migration surface, beside the old token count. ``migration_surface`` is the number of modules that must be changed or at @@ -390,7 +450,12 @@ def field_use_summary(fields: Iterable[str], sources: Iterable[SourceFile]) -> d """ materialized = list(sources) ordered = sorted(fields) - uses, unknown = scan_field_uses(ordered, materialized) + uses, unknown = scan_field_uses( + ordered, + materialized, + ts_rows_override=ts_rows_override, + python_scan_override=python_scan_override, + ) summary: dict[str, Any] = { "fields": {}, "dynamic_mapping_key_sites": unknown.python_mapping_calls, diff --git a/loopx/semantics/inventory.py b/loopx/semantics/inventory.py index 2eee9ae288..47661cc40a 100644 --- a/loopx/semantics/inventory.py +++ b/loopx/semantics/inventory.py @@ -162,13 +162,20 @@ def python_facts(source: SourceFile) -> dict[str, list[FactEntry]]: scans of the same tree (owner_values plus build_inventory in the drift smoke) parse each file once instead of once per caller. """ + return python_facts_from_tree(source, parse_python(source)) + + +def python_facts_from_tree( + source: SourceFile, + tree: ast.Module, +) -> dict[str, list[FactEntry]]: + """Extract Python vocabulary facts from an already-parsed syntax tree.""" facts: dict[str, list[FactEntry]] = { "enums": [], "closed_sets": [], "literal_aliases": [], "string_constants": [], } - tree = parse_python(source) for node in tree.body: if isinstance(node, ast.ClassDef) and _is_enum_class(node): values: list[str] = [] @@ -361,6 +368,8 @@ def build_inventory( repo_root: Path, root: str = DEFAULT_ROOT, sources: Sequence[SourceFile] | None = None, + *, + python_facts_map: Mapping[SourceFile, dict[str, list[FactEntry]]] | None = None, ) -> dict[str, object]: resolved_sources = load_sources(repo_root, root) if sources is None else list(sources) enums: list[FactEntry] = [] @@ -370,7 +379,11 @@ def build_inventory( string_constants: list[FactEntry] = [] for source in resolved_sources: if source.suffix == ".py": - facts = python_facts(source) + facts = ( + python_facts_map[source] + if python_facts_map is not None and source in python_facts_map + else python_facts(source) + ) enums.extend(facts["enums"]) closed_sets.extend(facts["closed_sets"]) literal_aliases.extend(facts["literal_aliases"]) @@ -485,10 +498,19 @@ def string_constant_definitions( def collect_string_constants( sources: Sequence[SourceFile], + *, + python_facts_map: Mapping[SourceFile, dict[str, list[FactEntry]]] | None = None, ) -> list[StringConstantEntry]: constants: list[StringConstantEntry] = [] for source in sources: - facts = python_facts(source) if source.suffix == ".py" else typescript_facts(source) + if source.suffix == ".py": + facts = ( + python_facts_map[source] + if python_facts_map is not None and source in python_facts_map + else python_facts(source) + ) + else: + facts = typescript_facts(source) for item in facts["string_constants"]: constants.append( { diff --git a/loopx/semantics/production.py b/loopx/semantics/production.py index b9de9370fb..d650404c4a 100644 --- a/loopx/semantics/production.py +++ b/loopx/semantics/production.py @@ -2,15 +2,27 @@ from __future__ import annotations import ast +import atexit +from collections.abc import Sequence +from concurrent.futures import ThreadPoolExecutor import json +import os from pathlib import Path +import selectors import shutil import subprocess +import threading +import time from typing import Any, Callable from ..control_plane.runtime.node_probe import node_typescript_flags from .inventory import SourceFile -from .python_production import Production, enum_members, scan_python_production +from .python_production import ( + _TREES as _PYTHON_PRODUCTION_TREES, + Production, + enum_members, + scan_python_production, +) # Matched verbatim by tests/conftest.py to collapse repeated failures into one hint. @@ -50,7 +62,13 @@ def quota_action_domain(registry: dict[str, Any]) -> set[str]: return result -def collect_production(root: Path, vocabulary: dict[str, Any], sources: list[SourceFile]) -> list[Production]: +def collect_production( + root: Path, + vocabulary: dict[str, Any], + sources: list[SourceFile], + *, + ts_rows: Sequence[dict[str, Any]] | None = None, +) -> list[Production]: by_path = {s.path: s for s in sources} owner = vocabulary['owners'].get('python') enums = {} @@ -71,14 +89,25 @@ def collect_production(root: Path, vocabulary: dict[str, Any], sources: list[Sou selected = [s for s in sources if s.path in PRODUCER_FILES or any(s.path.startswith(p + '/') for p in PRODUCER_ROOTS)] rows = [] - for source in selected: - if source.suffix == '.py': - names = frozenset(site.split('::')[1] for site in returns if site.split('::')[0] == source.path) - paths = {site.split('::')[1]: tuple(path) for site, path in return_paths.items() - if site.split('::')[0] == source.path} - rows.extend(scan_python_production(source, field=field, enums=enums, return_functions=names, - return_paths=paths, call_arguments=calls, modules=by_path)) - rows.extend(_typescript_scan(root, [s for s in selected if s.suffix == '.ts'], field, returns)) + scan_python = bool(field or enums or calls or any(site.split('::')[0].endswith('.py') for site in returns)) + if scan_python: + prior_trees = set(_PYTHON_PRODUCTION_TREES) + try: + for source in selected: + if source.suffix == '.py': + names = frozenset(site.split('::')[1] for site in returns if site.split('::')[0] == source.path) + paths = {site.split('::')[1]: tuple(path) for site, path in return_paths.items() + if site.split('::')[0] == source.path} + rows.extend(scan_python_production(source, field=field, enums=enums, return_functions=names, + return_paths=paths, call_arguments=calls, modules=by_path)) + finally: + for cached_source in list(_PYTHON_PRODUCTION_TREES): + if cached_source not in prior_trees and cached_source in _PYTHON_PRODUCTION_TREES: + del _PYTHON_PRODUCTION_TREES[cached_source] + if ts_rows is not None: + rows.extend(normalize_typescript_production_rows(ts_rows)) + else: + rows.extend(_typescript_scan(root, [s for s in selected if s.suffix == '.ts'], field, returns)) if witness := INPUT_WITNESSES.get(vocabulary.get('input_producer') or ''): rows.extend(witness(vocabulary)) return rows @@ -109,6 +138,14 @@ def _call_arguments(declarations: dict[str, list[str]], sources: dict[str, Sourc return calls +def normalize_typescript_production_rows(rows: Sequence[dict[str, Any]]) -> list[Production]: + # The parser names the same blocker vocabulary as the Python scanner; + # ``typescript_dynamic`` stays the fallback for a form it cannot classify. + return [Production(r['site'], r['line'], r['form'], frozenset(r['values']), r['unresolved'], + (r.get('blocker') or 'typescript_dynamic') if r['unresolved'] else None) + for r in rows] + + def _typescript_scan( root: Path, ts_sources: list[SourceFile], field: str | None, returns: list[str], mode: str = 'production', @@ -121,26 +158,276 @@ def _typescript_scan( if field: request['field'] = field rows = run_typescript_scan(root, ts_sources, request) - # The parser names the same blocker vocabulary as the Python scanner; - # ``typescript_dynamic`` stays the fallback for a form it cannot classify. - return [Production(r['site'], r['line'], r['form'], frozenset(r['values']), r['unresolved'], - (r.get('blocker') or 'typescript_dynamic') if r['unresolved'] else None) - for r in rows] + return normalize_typescript_production_rows(rows) -def run_typescript_scan( - root: Path, ts_sources: list[SourceFile], request: dict[str, Any], -) -> list[dict[str, Any]]: - """Run repository semantic AST analysis with one bounded error boundary.""" - if not ts_sources: - return [] +_REPO_SCAN_SCRIPT = Path(__file__).resolve().parents[2] / 'scripts/semantic_production_scan.mjs' +_DEFAULT_WHICH = shutil.which +_DEFAULT_SUBPROCESS_RUN = subprocess.run +_DEFAULT_TS_SCAN_TIMEOUT_SECONDS = 60.0 +_MAX_TS_SERVER_STDERR_BYTES = 65536 +_TS_SERVER_LOCK = threading.Lock() +_TS_SERVER: subprocess.Popen[bytes] | None = None +_TS_SERVER_KEY: tuple[str, str] | None = None +_TS_SERVER_STDOUT_BUF = bytearray() + + +def _close_pipe(stream: Any) -> None: + if stream is not None: + try: + stream.close() + except OSError: + pass + + +def _shutdown_ts_server_locked(*, force: bool = False) -> None: + global _TS_SERVER, _TS_SERVER_KEY + proc = _TS_SERVER + _TS_SERVER = None + _TS_SERVER_KEY = None + _TS_SERVER_STDOUT_BUF.clear() + if proc is None: + return + try: + _close_pipe(proc.stdin) + if not force: + try: + proc.wait(timeout=1) + return + except subprocess.TimeoutExpired: + pass + except OSError: + return + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=1) + except (subprocess.TimeoutExpired, OSError): + pass + finally: + _close_pipe(proc.stdout) + _close_pipe(proc.stderr) + + +def _shutdown_ts_server() -> None: + with _TS_SERVER_LOCK: + _shutdown_ts_server_locked() + + +atexit.register(_shutdown_ts_server) + + +def _raise_syntax_error(error: Any, ts_paths: set[str]) -> None: + if (isinstance(error, dict) and error.get('code') == 'typescript_syntax' + and error.get('path') in ts_paths + and isinstance(error.get('line'), int) and error['line'] > 0): + raise ValueError(f"{error['path']}:{error['line']}: invalid TypeScript source; repair syntax before semantic scanning") + + +def _drain_nonblocking_fd( + fd: int, buf: bytearray, *, deadline: float, cmd: list[str], timeout: float, +) -> bool: + """Drain immediately available bytes from a non-blocking stderr pipe within deadline.""" + while True: + if time.monotonic() >= deadline: + raise subprocess.TimeoutExpired(cmd, timeout) + try: + chunk = os.read(fd, 65536) + except BlockingIOError: + return False + except OSError: + return True + if not chunk: + return True + buf.extend(chunk) + if len(buf) > _MAX_TS_SERVER_STDERR_BYTES: + del buf[: len(buf) - _MAX_TS_SERVER_STDERR_BYTES] + if time.monotonic() >= deadline: + raise subprocess.TimeoutExpired(cmd, timeout) + + +def _exchange_ts_server_request( + proc: subprocess.Popen[bytes], encoded: bytes, cmd: list[str], deadline: float, timeout: float, +) -> tuple[bytes, str, bool]: + """Write one NDJSON line and read one response line under a single deadline.""" + assert proc.stdin is not None and proc.stdout is not None and proc.stderr is not None + stdin_fd = proc.stdin.fileno() + stdout_fd = proc.stdout.fileno() + stderr_fd = proc.stderr.fileno() + for fd in (stdin_fd, stdout_fd, stderr_fd): + os.set_blocking(fd, False) + write_view = memoryview(encoded) + write_failed = False + stdout_buf = _TS_SERVER_STDOUT_BUF + stderr_tail = bytearray() + stdout_eof = False + stderr_eof = False + eof_drain_deadline: float | None = None + + def _check_deadline() -> None: + if time.monotonic() >= deadline: + raise subprocess.TimeoutExpired(cmd, timeout) + + def _finish_eof() -> tuple[bytes, str, bool]: + _drain_nonblocking_fd( + stderr_fd, stderr_tail, deadline=deadline, cmd=cmd, timeout=timeout, + ) + _check_deadline() + return b'', stderr_tail.decode('utf-8', errors='replace'), write_failed + + with selectors.DefaultSelector() as sel: + sel.register(stdin_fd, selectors.EVENT_WRITE) + sel.register(stdout_fd, selectors.EVENT_READ) + sel.register(stderr_fd, selectors.EVENT_READ) + while True: + _check_deadline() + if not write_view: + newline_idx = stdout_buf.find(b'\n') + if newline_idx != -1: + _drain_nonblocking_fd( + stderr_fd, stderr_tail, deadline=deadline, cmd=cmd, timeout=timeout, + ) + _check_deadline() + line = bytes(stdout_buf[:newline_idx]) + del stdout_buf[: newline_idx + 1] + return line, stderr_tail.decode('utf-8', errors='replace'), False + if (stdout_eof or write_failed) and (stderr_eof or not write_view): + if stdout_eof and stderr_eof: + return _finish_eof() + if eof_drain_deadline is None: + eof_drain_deadline = min(deadline, time.monotonic() + 0.2) + now = time.monotonic() + if now >= deadline: + raise subprocess.TimeoutExpired(cmd, timeout) + if eof_drain_deadline is not None and now >= eof_drain_deadline and (stdout_eof or write_failed): + return _finish_eof() + active_deadline = min(deadline, eof_drain_deadline) if eof_drain_deadline is not None else deadline + remaining = active_deadline - now + if remaining <= 0: + raise subprocess.TimeoutExpired(cmd, timeout) + events = sel.select(timeout=remaining) + _check_deadline() + if not events: + if eof_drain_deadline is not None and (stdout_eof or write_failed): + return _finish_eof() + raise subprocess.TimeoutExpired(cmd, timeout) + for key, mask in events: + _check_deadline() + if key.fd == stdin_fd and (mask & selectors.EVENT_WRITE): + try: + written = os.write(stdin_fd, write_view) + except BlockingIOError: + continue + except OSError: + write_failed = True + write_view = memoryview(b'') + sel.unregister(stdin_fd) + continue + if written <= 0: + write_failed = True + write_view = memoryview(b'') + sel.unregister(stdin_fd) + continue + write_view = write_view[written:] + if not write_view: + sel.unregister(stdin_fd) + _check_deadline() + elif key.fd == stderr_fd and (mask & selectors.EVENT_READ): + if _drain_nonblocking_fd( + stderr_fd, stderr_tail, deadline=deadline, cmd=cmd, timeout=timeout, + ): + stderr_eof = True + sel.unregister(stderr_fd) + elif key.fd == stdout_fd and (mask & selectors.EVENT_READ): + while True: + _check_deadline() + try: + chunk = os.read(stdout_fd, 65536) + except BlockingIOError: + break + except OSError: + stdout_eof = True + sel.unregister(stdout_fd) + break + if not chunk: + stdout_eof = True + sel.unregister(stdout_fd) + break + stdout_buf.extend(chunk) + _check_deadline() + if b'\n' in chunk: + break + + +def _invoke_typescript_via_server( + node: str, script_path: Path, payload: dict[str, Any], ts_paths: set[str], + *, timeout: float | None = None, +) -> Any: + global _TS_SERVER, _TS_SERVER_KEY + effective_timeout = _DEFAULT_TS_SCAN_TIMEOUT_SECONDS if timeout is None else timeout + deadline = time.monotonic() + effective_timeout + key = (node, str(script_path)) + cmd = [node, str(script_path), '--server'] + encoded = (json.dumps(payload) + '\n').encode('utf-8') + lock_wait = max(0.0, deadline - time.monotonic()) + if not _TS_SERVER_LOCK.acquire(timeout=lock_wait): + raise subprocess.TimeoutExpired(cmd, effective_timeout) + try: + if _TS_SERVER is None or _TS_SERVER.poll() is not None or _TS_SERVER_KEY != key: + _shutdown_ts_server_locked() + _TS_SERVER = subprocess.Popen( + cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, + ) + _TS_SERVER_KEY = key + proc = _TS_SERVER + if deadline - time.monotonic() <= 0: + _shutdown_ts_server_locked(force=True) + raise subprocess.TimeoutExpired(cmd, effective_timeout) + try: + response_line, stderr_text, write_failed = _exchange_ts_server_request( + proc, encoded, cmd, deadline, effective_timeout, + ) + except BaseException: + _shutdown_ts_server_locked(force=True) + raise + if write_failed or not response_line: + _shutdown_ts_server_locked(force=True) + if 'ERR_MODULE_NOT_FOUND' in stderr_text and "'typescript'" in stderr_text: + raise ValueError(NPM_DEV_DEPENDENCIES_MISSING) + raise ValueError('TypeScript production parser failed; run npm ci --ignore-scripts and check the Node runtime') + try: + parsed = json.loads(response_line.decode('utf-8')) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + _shutdown_ts_server_locked(force=True) + raise ValueError('TypeScript production parser failed; run npm ci --ignore-scripts and check the Node runtime') from exc + finally: + _TS_SERVER_LOCK.release() + if not isinstance(parsed, dict) or not parsed.get('ok'): + error = parsed.get('error') if isinstance(parsed, dict) else None + _raise_syntax_error(error, ts_paths) + raise ValueError('TypeScript production parser failed; run npm ci --ignore-scripts and check the Node runtime') + return parsed.get('result') + + +def _invoke_typescript_scan( + root: Path, payload: dict[str, Any], ts_paths: set[str], + *, timeout: float | None = None, +) -> Any: + """Invoke the Node TypeScript AST scanner with one bounded error boundary.""" node = shutil.which('node') if node is None: raise ValueError('TypeScript semantic scan needs Node.js on PATH; see the Node.js requirement in CONTRIBUTING.md') + effective_timeout = _DEFAULT_TS_SCAN_TIMEOUT_SECONDS if timeout is None else timeout + script_path = root / 'scripts/semantic_production_scan.mjs' + if (os.name == 'posix' and shutil.which is _DEFAULT_WHICH and subprocess.run is _DEFAULT_SUBPROCESS_RUN + and script_path.resolve() == _REPO_SCAN_SCRIPT.resolve()): + return _invoke_typescript_via_server(node, script_path, payload, ts_paths, timeout=effective_timeout) completed = subprocess.run( - [node, str(root / 'scripts/semantic_production_scan.mjs')], - input=json.dumps({**request, 'sources': [{'path': s.path, 'text': s.text} for s in ts_sources]}), - capture_output=True, text=True, encoding="utf-8", timeout=60, check=False, + [node, str(script_path)], + input=json.dumps(payload), + capture_output=True, text=True, encoding="utf-8", timeout=effective_timeout, check=False, ) if completed.returncode: # Accept only a bounded location from the parser, never echo source @@ -150,17 +437,71 @@ def run_typescript_scan( except json.JSONDecodeError: failure = None error = failure.get('error') if isinstance(failure, dict) else None - if (isinstance(error, dict) and error.get('code') == 'typescript_syntax' - and error.get('path') in {s.path for s in ts_sources} - and isinstance(error.get('line'), int) and error['line'] > 0): - raise ValueError(f"{error['path']}:{error['line']}: invalid TypeScript source; repair syntax before semantic scanning") + _raise_syntax_error(error, ts_paths) if 'ERR_MODULE_NOT_FOUND' in completed.stderr and "'typescript'" in completed.stderr: raise ValueError(NPM_DEV_DEPENDENCIES_MISSING) raise ValueError('TypeScript production parser failed; run npm ci --ignore-scripts and check the Node runtime') return json.loads(completed.stdout) -def collect_literal_uses(root: Path, field: str, sources: list[SourceFile]) -> dict[str, set[str]]: +def run_typescript_scan( + root: Path, ts_sources: list[SourceFile], request: dict[str, Any], +) -> list[dict[str, Any]]: + """Run repository semantic AST analysis with one bounded error boundary.""" + if not ts_sources: + return [] + payload = {**request, 'sources': [{'path': s.path, 'text': s.text} for s in ts_sources]} + result = _invoke_typescript_scan(root, payload, {s.path for s in ts_sources}) + if not isinstance(result, list): + raise ValueError('TypeScript production parser returned malformed scan payload') + return result + + +def run_typescript_batch_scan( + root: Path, ts_sources: Sequence[SourceFile], requests: Sequence[dict[str, Any]], +) -> dict[str, list[dict[str, Any]]]: + """Run multiple TS AST queries in a single Node process, parsing each file once.""" + if not ts_sources or not requests: + return {str(req['id']): [] for req in requests} + payload = { + 'sources': [{'path': s.path, 'text': s.text} for s in ts_sources], + 'requests': list(requests), + } + parsed = _invoke_typescript_scan(root, payload, {s.path for s in ts_sources}) + results = parsed.get('results') if isinstance(parsed, dict) else None + if not isinstance(results, dict): + raise ValueError('TypeScript production parser returned malformed batch payload') + return results + + +def submit_typescript_batch_scan( + root: Path, ts_sources: Sequence[SourceFile], requests: Sequence[dict[str, Any]], +) -> Callable[[], dict[str, list[dict[str, Any]]]]: + """Start a batched Node TS AST scan asynchronously and return a join callable.""" + if not ts_sources or not requests: + empty: dict[str, list[dict[str, Any]]] = {str(req['id']): [] for req in requests} + return lambda: empty + if shutil.which('node') is None: + raise ValueError('TypeScript semantic scan needs Node.js on PATH; see the Node.js requirement in CONTRIBUTING.md') + executor = ThreadPoolExecutor(max_workers=1) + future = executor.submit(run_typescript_batch_scan, root, ts_sources, requests) + + def _finish() -> dict[str, list[dict[str, Any]]]: + try: + return future.result() + finally: + executor.shutdown(wait=True) + + return _finish + + +def collect_literal_uses( + root: Path, + field: str, + sources: list[SourceFile], + *, + ts_rows: Sequence[dict[str, Any]] | None = None, +) -> dict[str, set[str]]: """Observe literal field writes/dispatch, with a deliberately bounded grammar.""" from .python_production import python_literal_uses @@ -169,7 +510,12 @@ def collect_literal_uses(root: Path, field: str, sources: list[SourceFile]) -> d if source.suffix == '.py': for value in python_literal_uses(source, field): observed.setdefault(value, set()).add(source.path) - for row in _typescript_scan(root, [s for s in sources if s.suffix == '.ts'], field, [], 'literal_uses'): + ts_prod = ( + normalize_typescript_production_rows(ts_rows) + if ts_rows is not None + else _typescript_scan(root, [s for s in sources if s.suffix == '.ts'], field, [], 'literal_uses') + ) + for row in ts_prod: for value in row.values: observed.setdefault(value, set()).add(row.site.split('::')[0]) return observed diff --git a/loopx/semantics/project_registry_io.py b/loopx/semantics/project_registry_io.py index 6b7e661478..d7094ff44a 100644 --- a/loopx/semantics/project_registry_io.py +++ b/loopx/semantics/project_registry_io.py @@ -4,8 +4,10 @@ import ast from collections import Counter +from collections.abc import Sequence from dataclasses import dataclass from enum import Enum +from functools import lru_cache import json from pathlib import Path import subprocess @@ -108,6 +110,45 @@ def load_registry_io_sources(repo_root: Path) -> list[SourceFile]: return result +EXTRA_REGISTRY_IO_PATTERNS = ( + f"{SOURCE_ROOT}/*.tsx", + f"{SOURCE_ROOT}/*.js", + f"{SOURCE_ROOT}/*.mjs", +) + + +def load_registry_io_sources_from_base( + repo_root: Path, base_sources: Sequence[SourceFile], +) -> list[SourceFile]: + """Reuse already-loaded ``.py``/``.ts`` sources and load remaining JS/TSX files.""" + by_path: dict[str, SourceFile] = { + source.path: source + for source in base_sources + if source.suffix in PROJECT_REGISTRY_SOURCE_SUFFIXES and not _excluded(source.path) + } + tracked = subprocess.run( + ["git", "ls-files", "--cached", "-z", "--", *EXTRA_REGISTRY_IO_PATTERNS], + cwd=repo_root, + check=True, + stdout=subprocess.PIPE, + ).stdout.decode("utf-8").split("\0") + for relative in sorted(set(tracked) - {""}): + path = repo_root / relative + if ( + _excluded(relative) + or path.is_symlink() + or not path.is_file() + or path.suffix not in PROJECT_REGISTRY_SOURCE_SUFFIXES + ): + continue + by_path[relative] = SourceFile( + path=relative, + suffix=path.suffix, + text=path.read_text(encoding="utf-8", errors="replace"), + ) + return [by_path[key] for key in sorted(by_path)] + + def _terminal_name(node: ast.AST) -> str | None: if isinstance(node, ast.Name): return node.id @@ -364,31 +405,57 @@ def visit_Call(self, node: ast.Call) -> None: self.generic_visit(node) -def scan_python_registry_io(source: SourceFile) -> list[RegistryIOObservation]: +def _scan_python_registry_io_from_tree( + source: SourceFile, + tree: ast.Module, +) -> tuple[RegistryIOObservation, ...]: + text = source.text + if ( + text.isascii() + and "json" not in text + and "write_text" not in text + and "write_bytes" not in text + and "registr" not in text.lower() + ): + return () + scanner = _PythonRegistryIOScanner(source) + scanner.visit(tree) + return tuple(scanner.observations) + + +@lru_cache(maxsize=4096) +def _scan_python_registry_io_cached(source: SourceFile) -> tuple[RegistryIOObservation, ...]: try: tree = ast.parse(source.text, filename=source.path) except SyntaxError as error: raise ValueError( f"cannot scan invalid Python source: {source.path}:{error.lineno}" ) from None - scanner = _PythonRegistryIOScanner(source) - scanner.visit(tree) - return scanner.observations + return _scan_python_registry_io_from_tree(source, tree) -def _scan_javascript_registry_io( - repo_root: Path, sources: list[SourceFile] +def scan_python_registry_io( + source: SourceFile, + *, + tree: ast.Module | None = None, +) -> list[RegistryIOObservation]: + if tree is None: + return list(_scan_python_registry_io_cached(source)) + return list(_scan_python_registry_io_from_tree(source, tree)) + + +def registry_io_javascript_request() -> dict[str, Any]: + return { + "mode": "registry_io", + "approved_reads": sorted(APPROVED_READ_APIS), + "approved_writes": sorted(APPROVED_WRITE_APIS), + "approved_transactions": sorted(APPROVED_TRANSACTION_APIS), + } + + +def _decode_javascript_registry_io_rows( + rows: Sequence[dict[str, Any]], ) -> list[RegistryIOObservation]: - rows = run_typescript_scan( - repo_root, - sources, - { - "mode": "registry_io", - "approved_reads": sorted(APPROVED_READ_APIS), - "approved_writes": sorted(APPROVED_WRITE_APIS), - "approved_transactions": sorted(APPROVED_TRANSACTION_APIS), - }, - ) return [ RegistryIOObservation( path=row["path"], @@ -402,20 +469,40 @@ def _scan_javascript_registry_io( ] +def _scan_javascript_registry_io( + repo_root: Path, sources: list[SourceFile] +) -> list[RegistryIOObservation]: + rows = run_typescript_scan(repo_root, sources, registry_io_javascript_request()) + return _decode_javascript_registry_io_rows(rows) + + def collect_project_registry_io( - repo_root: Path, sources: list[SourceFile] | None = None + repo_root: Path, + sources: list[SourceFile] | None = None, + *, + precomputed_python_observations: Sequence[RegistryIOObservation] | None = None, + precomputed_js_rows: Sequence[dict[str, Any]] | None = None, ) -> list[RegistryIOObservation]: - selected = sources if sources is not None else load_registry_io_sources(repo_root) observations: list[RegistryIOObservation] = [] - for source in selected: - if source.suffix == ".py": - observations.extend(scan_python_registry_io(source)) - javascript = [ - source - for source in selected - if source.suffix in {".ts", ".tsx", ".js", ".mjs"} - ] - observations.extend(_scan_javascript_registry_io(repo_root, javascript)) + if precomputed_python_observations is not None: + observations.extend(precomputed_python_observations) + selected = sources + else: + selected = sources if sources is not None else load_registry_io_sources(repo_root) + for source in selected: + if source.suffix == ".py": + observations.extend(scan_python_registry_io(source)) + if precomputed_js_rows is not None: + observations.extend(_decode_javascript_registry_io_rows(precomputed_js_rows)) + else: + if selected is None: + selected = load_registry_io_sources(repo_root) + javascript = [ + source + for source in selected + if source.suffix in {".ts", ".tsx", ".js", ".mjs"} + ] + observations.extend(_scan_javascript_registry_io(repo_root, javascript)) return sorted(observations) @@ -461,11 +548,18 @@ def build_project_registry_io_manifest( *, classifications: dict[str, str] | None = None, sources: list[SourceFile] | None = None, + precomputed_python_observations: Sequence[RegistryIOObservation] | None = None, + precomputed_js_rows: Sequence[dict[str, Any]] | None = None, ) -> dict[str, Any]: """Compute the census; only reviewed direct-I/O classifications are tracked.""" if classifications is None: classifications = load_project_registry_io_classifications(repo_root) - observations = collect_project_registry_io(repo_root, sources) + observations = collect_project_registry_io( + repo_root, + sources, + precomputed_python_observations=precomputed_python_observations, + precomputed_js_rows=precomputed_js_rows, + ) return { "schema_version": PROJECT_REGISTRY_IO_MANIFEST_SCHEMA, "source_policy": { @@ -500,6 +594,8 @@ def validate_project_registry_io_manifest( *, classifications: dict[str, str] | None = None, sources: list[SourceFile] | None = None, + precomputed_python_observations: Sequence[RegistryIOObservation] | None = None, + precomputed_js_rows: Sequence[dict[str, Any]] | None = None, ) -> list[str]: """Check current source policy, or an explicit export against current source.""" if manifest is not None and manifest.get("schema_version") != PROJECT_REGISTRY_IO_MANIFEST_SCHEMA: @@ -510,6 +606,8 @@ def validate_project_registry_io_manifest( repo_root, classifications=classifications, sources=sources, + precomputed_python_observations=precomputed_python_observations, + precomputed_js_rows=precomputed_js_rows, ) if manifest is None: manifest = expected diff --git a/loopx/semantics/python_production.py b/loopx/semantics/python_production.py index a97f91fa91..c83fe56612 100644 --- a/loopx/semantics/python_production.py +++ b/loopx/semantics/python_production.py @@ -137,6 +137,24 @@ def enum_members(source: SourceFile, symbol: str, *, strict: bool = False) -> di return result +def _tree_mentions_field(tree: ast.AST, field: str) -> bool: + for node in ast.walk(tree): + node_type = type(node) + if node_type is ast.Name: + if node.id == field: + return True + elif node_type is ast.Attribute: + if node.attr == field: + return True + elif node_type is ast.Constant: + if node.value == field: + return True + elif node_type is ast.keyword: + if node.arg == field: + return True + return False + + @lru_cache(maxsize=4096) def _field_mentions(source: SourceFile) -> frozenset[str]: """Reuse parsed names, not another retained AST or a source-text filter.""" @@ -153,13 +171,24 @@ def _field_mentions(source: SourceFile) -> frozenset[str]: return frozenset(names) -def python_literal_uses(source: SourceFile, field: str) -> set[str]: +def python_literal_uses( + source: SourceFile, + field: str, + *, + tree: ast.Module | None = None, +) -> set[str]: """Literal writes and direct dispatch operands; not alias/data-flow proof.""" # Parsing precedes absence: escaped keys and normalized identifiers count, - # and invalid syntax must fail even without a textual field mention. - if field not in _field_mentions(source): + # and invalid syntax must fail even without a textual field mention. Avoid + # populating `_TREES` for full-repo literal scans so 2M AST nodes do not + # remain pinned across unrelated steps. + if tree is None: + if source in _TREES: + tree = _TREES[source] + else: + tree = ast.parse(source.text, filename=source.path) + if not _tree_mentions_field(tree, field): return set() - tree = _parsed(source) def reads(node: ast.AST) -> bool: if isinstance(node, ast.Name): @@ -195,7 +224,9 @@ def literals(node: ast.AST) -> set[str]: # Production collection already separates conditional results from their # conditions and does not inspect strings containing sample source text. - rows = scan_python_production(source, field=field, enums={}) + rows = _scan_python_production_tree( + source, tree, field=field, enums={}, skip_field_mention_check=True, + ) result = set().union(*(row.values for row in rows)) for node in ast.walk(tree): if isinstance(node, ast.Compare): @@ -217,8 +248,14 @@ def literals(node: ast.AST) -> set[str]: def _qualified_bindings(source: SourceFile, tree: ast.Module, owners: Mapping[str, _Binding], modules: Mapping[str, SourceFile] | None = None) -> dict[str, _Binding]: + if not owners: + return {} bindings = {owner.split('::')[1]: value for owner, value in owners.items() if owner.split('::')[0] == source.path} + if not bindings and source.text.isascii() and '\\' not in source.text and not any( + owner.split('::')[1] in source.text for owner in owners + ): + return {} imports = {(_module(owner.split('::')[0]), owner.split('::')[1]): value for owner, value in owners.items()} symbols = {symbol for _, symbol in imports} @@ -368,6 +405,27 @@ def _union(values: list[ast.expr]) -> ast.expr: return node +def _can_mention_production( + source: SourceFile, + field: str | None, + enums: Mapping[str, object], + return_functions: frozenset[str], + call_arguments: Mapping[str, object] | None, +) -> bool: + if return_functions: + return True + text = source.text + if not text.isascii() or '\\' in text: + return True + if field and field in text: + return True + if any(owner.split('::')[1] in text for owner in enums): + return True + if call_arguments and any(owner.split('::')[1] in text for owner in call_arguments): + return True + return False + + def scan_python_production( source: SourceFile, *, @@ -412,14 +470,44 @@ def scan_python_production( # The scan never mutates the tree, so one parse per file serves every # vocabulary; synthetic selection nodes are built fresh, never spliced in. tree = _parsed(source) + return _scan_python_production_tree( + source, + tree, + field=field, + enums=enums, + return_functions=return_functions, + return_paths=return_paths, + call_arguments=call_arguments, + modules=modules, + ) + + +def _scan_python_production_tree( + source: SourceFile, + tree: ast.Module, + *, + field: str | None, + enums: Mapping[str, Mapping[str, str]], + return_functions: frozenset[str] = frozenset(), + return_paths: Mapping[str, tuple[str | int, ...]] | None = None, + call_arguments: Mapping[str, Mapping[str, int | None]] | None = None, + modules: Mapping[str, SourceFile] | None = None, + skip_field_mention_check: bool = False, +) -> list[Production]: + if not skip_field_mention_check and not _can_mention_production( + source, field, enums, return_functions, call_arguments + ): + return [] bindings = _qualified_bindings(source, tree, enums, modules) call_arguments = call_arguments or {} calls = _qualified_bindings(source, tree, call_arguments, modules) return_paths = return_paths or {} # Every output form needs a field, registered return or qualified owner. # Keep enum results and builder arguments even when the field is absent. - if not bindings and not calls and not return_functions and ( - not field or field not in _field_mentions(source) + if not bindings and not calls and not return_functions and not skip_field_mention_check and ( + not field + or (source.text.isascii() and '\\' not in source.text and field not in source.text) + or field not in _field_mentions(source) ): return [] module_functions = _module_functions(source, tree) diff --git a/scripts/semantic_production_scan.mjs b/scripts/semantic_production_scan.mjs index 55b46a62b1..946a9781bd 100644 --- a/scripts/semantic_production_scan.mjs +++ b/scripts/semantic_production_scan.mjs @@ -1,163 +1,259 @@ #!/usr/bin/env node // Parse supplied tracked source text only; never load or execute product modules. +import readline from 'node:readline'; import ts from 'typescript'; -let input = ''; -for await (const chunk of process.stdin) input += chunk; -const request = JSON.parse(input); -const result = []; -for (const source of request.sources) { - const tree = ts.createSourceFile(source.path, source.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); +const DIRECT_READS = new Set(['readFile', 'readFileSync', 'readJson', 'readJSON', 'readTextFile']); +const DIRECT_WRITES = new Set([ + 'outputJson', 'write', 'writeFile', 'writeFileSync', 'writeJson', 'writeJSON', 'writeTextFile', +]); + +const unwrap = node => { + while (node && (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || + ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node))) node = node.expression; + return node; +}; + +const staticName = expression => { + const node = unwrap(expression); + return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : null; +}; + +const named = node => { + if (!node) return null; + if (ts.isComputedPropertyName(node)) return staticName(node.expression); + return ts.isIdentifier(node) ? node.text : staticName(node); +}; + +// Say why a write stayed unknown using the same labels as the Python scanner, +// so one residue taxonomy covers both runtimes instead of a single catch-all. +const blockerFor = node => { + if (!node) return 'other'; + if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) return 'attribute_read'; + if (ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isAwaitExpression(node)) return 'call_result'; + if (ts.isIdentifier(node)) return 'unstable_local'; + // `other`, not `dynamic_key`: the shared vocabulary defines `dynamic_key` + // as a computed or non-literal subscript, and none of these is one. Python + // answers `other` for the same shapes -- a dict literal or an f-string + // where a scalar was required -- so the two runtimes agree on the label. + if (ts.isObjectLiteralExpression(node) || ts.isArrayLiteralExpression(node) || + ts.isTemplateExpression(node)) return 'other'; + return 'typescript_dynamic'; +}; + +class SyntaxScanError extends Error { + constructor(path, line) { + super('typescript_syntax'); + this.payload = {error: {path, line, code: 'typescript_syntax'}}; + } +} + +const treeCache = new Map(); +const shadowedCache = new Map(); + +const getTree = source => { + let tree = treeCache.get(source.path); + if (tree !== undefined) return tree; + tree = ts.createSourceFile(source.path, source.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); if (tree.parseDiagnostics.length) { const line = tree.getLineAndCharacterOfPosition(tree.parseDiagnostics[0].start ?? 0).line + 1; - process.stdout.write(JSON.stringify({error: {path: source.path, line, code: "typescript_syntax"}})); - process.exit(2); + throw new SyntaxScanError(source.path, line); } - const field = request.field; - const returns = new Set((request.return_functions ?? []).filter(x => x.startsWith(`${source.path}::`))); - const unwrap = node => { - while (node && (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || - ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node))) node = node.expression; - return node; + treeCache.set(source.path, tree); + return tree; +}; + +// The scanner has no scope model, so it cannot tell the builtin `String` +// from a parameter that shadows it, nor the `undefined` literal from a +// local of that name. Shadowing is detected per file so repeated queries +// against one parsed tree reuse the same global-shadowing set. +const getShadowedGlobals = (path, tree) => { + let shadowed = shadowedCache.get(path); + if (shadowed !== undefined) return shadowed; + shadowed = new Set(); + const noteName = name => { + if (!name) return; + if (ts.isIdentifier(name)) shadowed.add(name.text); + else if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) + for (const element of name.elements) if (ts.isBindingElement(element)) noteName(element.name); }; - if (request.mode === 'registry_io') { - const approvedReads = new Set(request.approved_reads ?? []); - const approvedWrites = new Set(request.approved_writes ?? []); - const approvedTransactions = new Set(request.approved_transactions ?? []); - const directReads = new Set(['readFile', 'readFileSync', 'readJson', 'readJSON', 'readTextFile']); - const directWrites = new Set(['outputJson', 'write', 'writeFile', 'writeFileSync', 'writeJson', 'writeJSON', 'writeTextFile']); - const callName = expression => { - const node = unwrap(expression); - if (ts.isIdentifier(node)) return node.text; - if (ts.isPropertyAccessExpression(node)) return node.name.text; - return null; - }; - const identifierRole = name => { - const normalized = name.toLowerCase(); - if ((normalized.includes('global') && normalized.includes('registr')) || - normalized === 'globalpath' || normalized === 'globalregistry') return 'global'; - if (normalized.includes('registr') && - !['registrypayload', 'registryrecord', 'registryrecords', 'registrydata'].includes(normalized)) { - return 'project'; - } + const collect = node => { + if (ts.isParameter(node) || ts.isVariableDeclaration(node) || ts.isBindingElement(node)) noteName(node.name); + else if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) noteName(node.name); + else if (ts.isImportSpecifier(node) || ts.isImportClause(node) || ts.isNamespaceImport(node)) noteName(node.name); + ts.forEachChild(node, collect); + }; + collect(tree); + shadowedCache.set(path, shadowed); + return shadowed; +}; + +const scanRegistryIO = (source, tree, sub, result) => { + const callName = expression => { + const node = unwrap(expression); + if (ts.isIdentifier(node)) return node.text; + if (ts.isPropertyAccessExpression(node)) return node.name.text; + return null; + }; + const identifierRole = name => { + const normalized = name.toLowerCase(); + if ((normalized.includes('global') && normalized.includes('registr')) || + normalized === 'globalpath' || normalized === 'globalregistry') return 'global'; + if (normalized.includes('registr') && + !['registrypayload', 'registryrecord', 'registryrecords', 'registrydata'].includes(normalized)) { + return 'project'; + } + return 'unknown'; + }; + const mergeRoles = roles => roles.includes('global') ? 'global' + : roles.includes('project') ? 'project' : 'unknown'; + const pathRole = expression => { + const node = unwrap(expression); + if (!node) return 'unknown'; + if (ts.isIdentifier(node)) return identifierRole(node.text); + if (ts.isPropertyAccessExpression(node)) { + const own = identifierRole(node.name.text); + return own === 'unknown' ? pathRole(node.expression) : own; + } + if (ts.isElementAccessExpression(node)) { + return mergeRoles([pathRole(node.expression), pathRole(node.argumentExpression)]); + } + if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) { + const normalized = node.text.replaceAll('\\', '/').toLowerCase(); + if (normalized.includes('registry.global.json')) return 'global'; + if (normalized.endsWith('/.loopx/registry.json') || + normalized === '.loopx/registry.json' || normalized === 'registry.json') return 'project'; return 'unknown'; - }; - const mergeRoles = roles => roles.includes('global') ? 'global' - : roles.includes('project') ? 'project' : 'unknown'; - const pathRole = expression => { - const node = unwrap(expression); - if (!node) return 'unknown'; - if (ts.isIdentifier(node)) return identifierRole(node.text); - if (ts.isPropertyAccessExpression(node)) { - const own = identifierRole(node.name.text); - return own === 'unknown' ? pathRole(node.expression) : own; - } - if (ts.isElementAccessExpression(node)) { - return mergeRoles([pathRole(node.expression), pathRole(node.argumentExpression)]); - } - if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) { - const normalized = node.text.replaceAll('\\', '/').toLowerCase(); - if (normalized.includes('registry.global.json')) return 'global'; - if (normalized.endsWith('/.loopx/registry.json') || - normalized === '.loopx/registry.json' || normalized === 'registry.json') return 'project'; - return 'unknown'; - } - if (ts.isCallExpression(node) || ts.isNewExpression(node)) { - const name = callName(node.expression) ?? ''; - if (name === 'globalRegistryPath') return 'global'; - if (['defaultRegistryPath', 'findRegistry', 'registryPath'].includes(name)) return 'project'; - if (name === 'Path' && (node.arguments ?? []).length > 0) return pathRole(node.arguments[0]); - if (ts.isPropertyAccessExpression(node.expression) && - ['absolute', 'expanduser', 'resolve'].includes(name)) { - return pathRole(node.expression.expression); - } - return 'unknown'; - } - if (ts.isBinaryExpression(node)) return mergeRoles([pathRole(node.left), pathRole(node.right)]); - if (ts.isConditionalExpression(node)) { - return mergeRoles([pathRole(node.whenTrue), pathRole(node.whenFalse)]); - } - if (ts.isTemplateExpression(node)) { - return mergeRoles(node.templateSpans.map(span => pathRole(span.expression))); + } + if (ts.isCallExpression(node) || ts.isNewExpression(node)) { + const name = callName(node.expression) ?? ''; + if (name === 'globalRegistryPath') return 'global'; + if (['defaultRegistryPath', 'findRegistry', 'registryPath'].includes(name)) return 'project'; + if (name === 'Path' && (node.arguments ?? []).length > 0) return pathRole(node.arguments[0]); + if (ts.isPropertyAccessExpression(node.expression) && + ['absolute', 'expanduser', 'resolve'].includes(name)) { + return pathRole(node.expression.expression); } return 'unknown'; - }; - const record = (node, scope, kind, api) => { - const location = tree.getLineAndCharacterOfPosition(node.getStart(tree)); - result.push({ - path: source.path, - scope, - line: location.line + 1, - column: location.character + 1, - kind, - api, - }); - }; - const visit = (node, scope) => { - if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) { - const name = node.name ? callName(node.name) : null; - scope = name ? (scope === '' ? name : `${scope}.${name}`) : ''; - } else if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) { - const parent = node.parent; - const name = ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent) - ? callName(parent.name) : null; - scope = name ? (scope === '' ? name : `${scope}.${name}`) : ''; + } + if (ts.isBinaryExpression(node)) return mergeRoles([pathRole(node.left), pathRole(node.right)]); + if (ts.isConditionalExpression(node)) { + return mergeRoles([pathRole(node.whenTrue), pathRole(node.whenFalse)]); + } + if (ts.isTemplateExpression(node)) { + return mergeRoles(node.templateSpans.map(span => pathRole(span.expression))); + } + return 'unknown'; + }; + const record = (node, scope, kind, api) => { + const location = tree.getLineAndCharacterOfPosition(node.getStart(tree)); + result.push({ + path: source.path, + scope, + line: location.line + 1, + column: location.character + 1, + kind, + api, + }); + }; + const visit = (node, scope) => { + if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) { + const name = node.name ? callName(node.name) : null; + scope = name ? (scope === '' ? name : `${scope}.${name}`) : ''; + } else if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) { + const parent = node.parent; + const name = ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent) + ? callName(parent.name) : null; + scope = name ? (scope === '' ? name : `${scope}.${name}`) : ''; + } + if (ts.isCallExpression(node)) { + const api = callName(node.expression); + if (sub.approvedReads.has(api)) record(node, scope, 'codec_read', api); + else if (sub.approvedWrites.has(api)) record(node, scope, 'codec_write', api); + else if (sub.approvedTransactions.has(api)) record(node, scope, 'codec_transaction', api); + else if (DIRECT_READS.has(api) && node.arguments.length > 0 && + pathRole(node.arguments[0]) === 'project') { + record(node, scope, 'direct_json_read', api); + } else if (DIRECT_WRITES.has(api) && node.arguments.length > 0 && + pathRole(node.arguments[0]) === 'project') { + record(node, scope, 'direct_json_write', api); } - if (ts.isCallExpression(node)) { - const api = callName(node.expression); - if (approvedReads.has(api)) record(node, scope, 'codec_read', api); - else if (approvedWrites.has(api)) record(node, scope, 'codec_write', api); - else if (approvedTransactions.has(api)) record(node, scope, 'codec_transaction', api); - else if (directReads.has(api) && node.arguments.length > 0 && - pathRole(node.arguments[0]) === 'project') { - record(node, scope, 'direct_json_read', api); - } else if (directWrites.has(api) && node.arguments.length > 0 && - pathRole(node.arguments[0]) === 'project') { - record(node, scope, 'direct_json_write', api); - } + } + ts.forEachChild(node, child => visit(child, scope)); + }; + visit(tree, ''); +}; + +const scanFieldUses = (source, tree, fields, result) => { + const forms = new Map(); + // A computed member access may name any field, so it is the standing + // unknown a name-keyed scan cannot resolve. It is reported apart from the + // Python mapping-call count because the two exclusions differ: `rows[i]` + // and `payload[key]` are one syntax here, so this is an upper bound. + let dynamicSites = 0; + // String literals a key position consumed. A field-named literal left over + // is the name travelling as data -- the Python scan's `name_constant`. + const keyed = new Set(); + const constants = []; + const record = (key, form) => { + if (!fields.has(key)) return; + if (!forms.has(key)) forms.set(key, new Set()); + forms.get(key).add(form); + }; + const markKeyed = name => { + if (!name) return; + keyed.add(name); + if (ts.isComputedPropertyName(name)) keyed.add(unwrap(name.expression)); + }; + const visit = node => { + if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + const property = ts.isPropertyAccessExpression(node); + const key = property ? node.name.text : staticName(node.argumentExpression); + if (!property) { + const argument = unwrap(node.argumentExpression); + if (key === null && argument && !ts.isNumericLiteral(argument)) dynamicSites += 1; + else if (key !== null) keyed.add(argument); } - ts.forEachChild(node, child => visit(child, scope)); - }; - visit(tree, ''); - continue; - } - // Say why a write stayed unknown using the same labels as the Python scanner, - // so one residue taxonomy covers both runtimes instead of a single catch-all. - const blockerFor = node => { - if (!node) return 'other'; - if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) return 'attribute_read'; - if (ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isAwaitExpression(node)) return 'call_result'; - if (ts.isIdentifier(node)) return 'unstable_local'; - // `other`, not `dynamic_key`: the shared vocabulary defines `dynamic_key` - // as a computed or non-literal subscript, and none of these is one. Python - // answers `other` for the same shapes -- a dict literal or an f-string - // where a scalar was required -- so the two runtimes agree on the label. - if (ts.isObjectLiteralExpression(node) || ts.isArrayLiteralExpression(node) || - ts.isTemplateExpression(node)) return 'other'; - return 'typescript_dynamic'; + let target = node, parent = node.parent; + while (parent && unwrap(parent) === target) { target = parent; parent = parent.parent; } + const assignment = ts.isBinaryExpression(parent) && parent.left === target && + parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && + parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment; + const update = (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) && + [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(parent.operator); + const deletion = ts.isDeleteExpression(parent); + const prefix = property ? 'property' : 'subscript'; + if (assignment || update || deletion) record(key, `${prefix}_write`); + if ((!assignment && !deletion) || update || + (assignment && parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken)) { + record(key, `${prefix}_read`); + } + } else if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + const name = node.propertyName ?? node.name; + markKeyed(name); + record(named(name), 'destructured_read'); + } else if (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) { + markKeyed(node.name); + record(named(node.name), 'object_literal_key'); + } else if (ts.isPropertySignature(node) || ts.isPropertyDeclaration(node)) { + markKeyed(node.name); + record(named(node.name), 'property_signature'); + } else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) { + if (fields.has(node.text)) constants.push(node); + } + ts.forEachChild(node, visit); }; - // The scanner has no scope model, so it cannot tell the builtin `String` - // from a parameter that shadows it, nor the `undefined` literal from a - // local of that name. A caller-supplied `String` can return anything, so - // trusting the builtin reading would report a produced value the code never - // produces. Shadowing is therefore detected per file -- coarser than per - // scope, which can only withhold a builtin reading, never invent one. - const shadowedGlobals = new Set(); - { - const noteName = name => { - if (!name) return; - if (ts.isIdentifier(name)) shadowedGlobals.add(name.text); - else if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) - for (const element of name.elements) if (ts.isBindingElement(element)) noteName(element.name); - }; - const collect = node => { - if (ts.isParameter(node) || ts.isVariableDeclaration(node) || ts.isBindingElement(node)) noteName(node.name); - else if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) noteName(node.name); - else if (ts.isImportSpecifier(node) || ts.isImportClause(node) || ts.isNamespaceImport(node)) noteName(node.name); - ts.forEachChild(node, collect); - }; - collect(tree); - } + visit(tree); + for (const node of constants) if (!keyed.has(node)) record(node.text, 'name_constant'); + result.push({ + path: source.path, + dynamic_member_sites: dynamicSites, + fields: Object.fromEntries([...forms].map(([key, observed]) => [key, [...observed].sort()])), + }); +}; + +const scanProductionOrLiterals = (source, tree, mode, field, returns, result) => { + const shadowedGlobals = getShadowedGlobals(source.path, tree); const merge = parts => ({ values: [...new Set(parts.flatMap(part => part.values))].sort(), unresolved: parts.some(part => part.unresolved), @@ -168,12 +264,8 @@ for (const source of request.sources) { if (!node) return {values: [], unresolved: true, blocker: 'other'}; if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return {values: node.text ? [node.text] : [], unresolved: false}; if (node.kind === ts.SyntaxKind.NullKeyword) return {values: [], unresolved: false}; - // ``undefined`` carries no value and is not an unknown, matching the way - // the Python scanner treats an explicit ``None``. if (ts.isIdentifier(node) && node.text === 'undefined' && !shadowedGlobals.has('undefined')) return {values: [], unresolved: false}; if (ts.isConditionalExpression(node)) return merge([values(node.whenTrue), values(node.whenFalse)]); - // ``a || b`` and ``a ?? b`` are a finite selection, exactly like the - // Python scanner's BoolOp arms; ``String(x)`` is a transparent wrapper. if (ts.isBinaryExpression(node) && [ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(node.operatorToken.kind)) { return merge([values(node.left), values(node.right)]); @@ -183,15 +275,6 @@ for (const source of request.sources) { !shadowedGlobals.has('String')) return values(node.arguments[0]); return {values: [], unresolved: true, blocker: blockerFor(node)}; }; - const staticName = expression => { - const node = unwrap(expression); - return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : null; - }; - const named = node => { - if (!node) return null; - if (ts.isComputedPropertyName(node)) return staticName(node.expression); - return ts.isIdentifier(node) ? node.text : staticName(node); - }; const target = node => ts.isIdentifier(node) ? node.text === field : ts.isPropertyAccessExpression(node) ? node.name.text === field : ts.isElementAccessExpression(node) && staticName(node.argumentExpression) === field; @@ -204,7 +287,7 @@ for (const source of request.sources) { !shadowedGlobals.has('String')) return reads(node.arguments[0]); return ts.isBinaryExpression(node) && [ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(node.operatorToken.kind) && - reads(node.left) && (staticName(node.right) === "" || unwrap(node.right).kind === ts.SyntaxKind.NullKeyword); + reads(node.left) && (staticName(node.right) === '' || unwrap(node.right).kind === ts.SyntaxKind.NullKeyword); }; const literals = expression => { const node = unwrap(expression); @@ -215,81 +298,6 @@ for (const source of request.sources) { } return values(node).values; }; - if (request.mode === 'field_uses') { - const fields = new Set(request.fields); - const forms = new Map(); - // A computed member access may name any field, so it is the standing - // unknown a name-keyed scan cannot resolve. It is reported apart from the - // Python mapping-call count because the two exclusions differ: `rows[i]` - // and `payload[key]` are one syntax here, so this is an upper bound. - let dynamicSites = 0; - // String literals a key position consumed. A field-named literal left over - // is the name travelling as data -- the Python scan's `name_constant`. - const keyed = new Set(); - const constants = []; - const record = (key, form) => { - if (!fields.has(key)) return; - if (!forms.has(key)) forms.set(key, new Set()); - forms.get(key).add(form); - }; - const markKeyed = name => { - if (!name) return; - keyed.add(name); - if (ts.isComputedPropertyName(name)) keyed.add(unwrap(name.expression)); - }; - const visit = node => { - if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { - const property = ts.isPropertyAccessExpression(node); - const key = property ? node.name.text : staticName(node.argumentExpression); - if (!property) { - const argument = unwrap(node.argumentExpression); - if (key === null && argument && !ts.isNumericLiteral(argument)) dynamicSites += 1; - else if (key !== null) keyed.add(argument); - } - let target = node, parent = node.parent; - while (parent && unwrap(parent) === target) { target = parent; parent = parent.parent; } - const assignment = ts.isBinaryExpression(parent) && parent.left === target && - parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && - parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment; - const update = (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) && - [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(parent.operator); - const deletion = ts.isDeleteExpression(parent); - const prefix = property ? 'property' : 'subscript'; - if (assignment || update || deletion) record(key, `${prefix}_write`); - if ((!assignment && !deletion) || update || - (assignment && parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken)) { - record(key, `${prefix}_read`); - } - } else if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - // `const {field} = payload` and `const {field: alias} = payload` read - // the field exactly as `payload.field` does, in a declaration or in a - // parameter list. `propertyName` is present only when the binding - // renames the key; otherwise the bound name is the key. - const name = node.propertyName ?? node.name; - markKeyed(name); - record(named(name), 'destructured_read'); - } else if (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) { - // An object literal key is where TypeScript writes the field. The - // Python scan counts the same construct as `dict_literal_key`, so - // porting a dict literal to TypeScript must not shrink the surface. - markKeyed(node.name); - record(named(node.name), 'object_literal_key'); - } else if (ts.isPropertySignature(node) || ts.isPropertyDeclaration(node)) { - // A declared contract surface: the type a retirement has to change. - markKeyed(node.name); - record(named(node.name), 'property_signature'); - } else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) { - if (fields.has(node.text)) constants.push(node); - } - ts.forEachChild(node, visit); - }; - visit(tree); - for (const node of constants) if (!keyed.has(node)) record(node.text, 'name_constant'); - result.push({path: source.path, dynamic_member_sites: dynamicSites, fields: Object.fromEntries( - [...forms].map(([key, observed]) => [key, [...observed].sort()]), - )}); - continue; - } function walk(node, scope) { if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) scope = scope === '' ? named(node.name) : `${scope}.${named(node.name)}`; else if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) { @@ -305,7 +313,7 @@ for (const source of request.sources) { if (form) { result.push({site: `${source.path}::${scope}`, line: tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1, form, ...values(expression)}); } - if (request.mode === 'literal_uses') { + if (mode === 'literal_uses') { let observed = []; if (ts.isBinaryExpression(node) && [ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken, @@ -325,5 +333,87 @@ for (const source of request.sources) { ts.forEachChild(node, child => walk(child, scope)); } walk(tree, ''); +}; + +const runSubRequest = (allSources, sub) => { + const allowedPaths = Array.isArray(sub.paths) ? new Set(sub.paths) : null; + const selected = allowedPaths ? allSources.filter(s => allowedPaths.has(s.path)) : allSources; + const result = []; + if (sub.mode === 'registry_io') { + const registryContext = { + approvedReads: new Set(sub.approved_reads ?? []), + approvedWrites: new Set(sub.approved_writes ?? []), + approvedTransactions: new Set(sub.approved_transactions ?? []), + }; + for (const source of selected) scanRegistryIO(source, getTree(source), registryContext, result); + return result; + } + if (sub.mode === 'field_uses') { + const fields = new Set(sub.fields); + for (const source of selected) scanFieldUses(source, getTree(source), fields, result); + return result; + } + const returnsByPath = new Map(); + for (const item of sub.return_functions ?? []) { + const idx = item.indexOf('::'); + if (idx === -1) continue; + const p = item.slice(0, idx); + let set = returnsByPath.get(p); + if (!set) { + set = new Set(); + returnsByPath.set(p, set); + } + set.add(item); + } + const emptyReturns = new Set(); + for (const source of selected) { + const returns = returnsByPath.get(source.path) ?? emptyReturns; + scanProductionOrLiterals(source, getTree(source), sub.mode, sub.field, returns, result); + } + return result; +}; + +const executePayload = payload => { + treeCache.clear(); + shadowedCache.clear(); + try { + if (Array.isArray(payload.requests)) { + const results = {}; + for (const sub of payload.requests) results[sub.id] = runSubRequest(payload.sources, sub); + return {results}; + } + return runSubRequest(payload.sources, payload); + } finally { + treeCache.clear(); + shadowedCache.clear(); + } +}; + +if (process.argv.includes('--server')) { + const rl = readline.createInterface({input: process.stdin, crlfDelay: Infinity}); + for await (const line of rl) { + if (!line.trim()) continue; + try { + const result = executePayload(JSON.parse(line)); + process.stdout.write(JSON.stringify({ok: true, result}) + '\n'); + } catch (error) { + if (error instanceof SyntaxScanError) { + process.stdout.write(JSON.stringify({ok: false, ...error.payload}) + '\n'); + } else { + process.stdout.write(JSON.stringify({ok: false, error: {code: 'internal'}}) + '\n'); + } + } + } +} else { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + try { + process.stdout.write(JSON.stringify(executePayload(JSON.parse(input)))); + } catch (error) { + if (error instanceof SyntaxScanError) { + process.stdout.write(JSON.stringify(error.payload)); + process.exit(2); + } + throw error; + } } -process.stdout.write(JSON.stringify(result)); diff --git a/scripts/settlement_receipt_source_witness.mts b/scripts/settlement_receipt_source_witness.mts index 628fd664f8..e967b70da4 100644 --- a/scripts/settlement_receipt_source_witness.mts +++ b/scripts/settlement_receipt_source_witness.mts @@ -1,23 +1,38 @@ // Bounded source witness: execute shipped owners, without defining vocabulary // values, classifying sources, or enrolling them in the production scanner. import { readFileSync } from "node:fs"; +import readline from "node:readline"; import { reduceTurnSettlementTransaction } from "../loopx/control_plane/turn_driver/settlement.ts"; import { readQuotaSettlement } from "../loopx/control_plane/quota/settlement_readback.ts"; import { executeTaskLeaseAcquire } from "../loopx/control_plane/work_items/task_lease_acquire.ts"; -const request = JSON.parse(readFileSync(0, "utf8")); -let result: unknown; -switch (request.operation) { - case "turn": - result = reduceTurnSettlementTransaction(request.input); - break; - case "readback": - result = await readQuotaSettlement(request.input); - break; - case "lease_acquire": - result = await executeTaskLeaseAcquire(request.input); - break; - default: - throw new Error("unsupported settlement source witness operation"); +async function executeWitness(request: { operation: string; input: unknown }): Promise { + switch (request.operation) { + case "turn": + return reduceTurnSettlementTransaction(request.input as never); + case "readback": + return await readQuotaSettlement(request.input as never); + case "lease_acquire": + return await executeTaskLeaseAcquire(request.input as never); + default: + throw new Error("unsupported settlement source witness operation"); + } +} + +if (process.argv.includes("--server")) { + const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); + for await (const line of rl) { + if (!line.trim()) continue; + try { + const result = await executeWitness(JSON.parse(line)); + process.stdout.write(JSON.stringify({ ok: true, result }) + "\n"); + } catch (error) { + process.stdout.write( + JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }) + "\n", + ); + } + } +} else { + const request = JSON.parse(readFileSync(0, "utf8")); + process.stdout.write(JSON.stringify(await executeWitness(request))); } -process.stdout.write(JSON.stringify(result)); diff --git a/tests/architecture/_repo_ast_cache.py b/tests/architecture/_repo_ast_cache.py new file mode 100644 index 0000000000..63538903e9 --- /dev/null +++ b/tests/architecture/_repo_ast_cache.py @@ -0,0 +1,193 @@ +"""Per-worker read and read-only AST cache for architecture census tests. + +Architecture tests across ``tests/architecture/`` repeatedly scan the same +tracked ``loopx/`` Python modules within a single pytest / xdist worker. +Caching file reads and read-only AST parses by ``(resolved_path, st_mtime_ns, +st_size)`` eliminates redundant disk reads and ``ast.parse`` calls while +automatically invalidating whenever a file changes on disk. + +IMPORTANT: ``parse_python_cached`` returns shared, read-only ``ast.Module`` +instances. Callers MUST NOT mutate returned AST nodes (no ``setattr``, +``delattr``, child rewriting, or list mutation on ``body``); use +``read_text_cached(path)`` + ``ast.parse(...)`` when mutation is required. +""" + +from __future__ import annotations + +import ast +from functools import lru_cache +import os +from pathlib import Path +import re +from typing import Protocol + +_REPO_ROOT = Path(__file__).resolve().parents[2] +_MAX_CACHE_ENTRIES = 4096 +# Matches escapes that can construct arbitrary ASCII characters or join split literals. +_CHAR_ESCAPE_RE = re.compile(r"\\(?:[xXuUN\r\n]|[0-7]{1,3})") +# Matches Python string literals without backtracking, then detects adjacent literals +# (implicit concatenation across whitespace/comments) or `+` / f-string interpolation. +_PY_STRING_PATTERN = ( + r"[rRuUbBfF]{0,2}(?:" + + r'"""[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' + + r"|'''[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" + + r'|"(?!"")[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"' + + r"|'(?!'')[^'\\\r\n]*(?:\\.[^'\\\r\n]*)*'" + + r")" +) +_ADJACENT_STRING_SCAN_RE = re.compile( + rf"#[^\r\n]*|(?P{_PY_STRING_PATTERN}(?:[ \t\r\n\f]|#[^\r\n]*)*{_PY_STRING_PATTERN})|{_PY_STRING_PATTERN}" +) +_PLUS_OR_FSTRING_SCAN_RE = re.compile( + rf"#[^\r\n]*|(?P{_PY_STRING_PATTERN}(?:[ \t\r\n\f]|#[^\r\n]*)*\+|(?:\+[ \t\r\n\f]*[rRuUbBfF]{{0,2}}['\"]|[fF][rRuUbB]?['\"]))|{_PY_STRING_PATTERN}" +) + + +class CacheStats(Protocol): + """Typed view of ``functools.lru_cache.cache_info()`` tuples.""" + + @property + def hits(self) -> int: ... + @property + def misses(self) -> int: ... + @property + def maxsize(self) -> int | None: ... + @property + def currsize(self) -> int: ... + + +def clear_caches() -> None: + """Clear all per-worker cached directory, path, text, syntax, and AST entries.""" + _canonical_path.cache_clear() + _iter_repo_python_sources.cache_clear() + _read_text_cached.cache_clear() + _check_python_syntax_cached.cache_clear() + _parse_python_cached.cache_clear() + may_split_or_escape_literal.cache_clear() + + +def cache_info() -> dict[str, CacheStats]: + """Return ``lru_cache`` statistics for tests and diagnostics.""" + return { + "sources": _iter_repo_python_sources.cache_info(), + "text": _read_text_cached.cache_info(), + "syntax": _check_python_syntax_cached.cache_info(), + "ast": _parse_python_cached.cache_info(), + "split_literal": may_split_or_escape_literal.cache_info(), + } + + +def has_char_escape(source: str) -> bool: + """Return True if ``source`` uses hex, unicode, octal, or line escapes.""" + return _CHAR_ESCAPE_RE.search(source) is not None + + +@lru_cache(maxsize=_MAX_CACHE_ENTRIES) +def may_split_or_escape_literal(source: str, *, include_plus: bool = False) -> bool: + """Return True when ``source`` can assemble a target literal without spelling it whole. + + Detects non-trivial escape sequences, line continuations, and implicit adjacent + string literal concatenation (for example ``"a" "b"``, ``r"a" r"b"``, or multiline + literals separated by whitespace/comments). When ``include_plus=True``, also flags + ``+`` string concatenation and f-string literals for suites that fold ``BinOp``/``JoinedStr``. + """ + if _CHAR_ESCAPE_RE.search(source) is not None: + return True + for match in _ADJACENT_STRING_SCAN_RE.finditer(source): + if match.lastgroup == "adj": + return True + if include_plus: + for match in _PLUS_OR_FSTRING_SCAN_RE.finditer(source): + if match.lastgroup == "concat": + return True + return False + + +@lru_cache(maxsize=_MAX_CACHE_ENTRIES) +def _canonical_path(raw_path: str) -> str: + return str(Path(raw_path).resolve()) + + +def _stat_target(path: Path) -> tuple[str, os.stat_result]: + resolved = _canonical_path(str(path)) + return resolved, os.stat(resolved) + + +def _scan_python_sources(root: Path, exclude_parts: frozenset[str]) -> tuple[Path, ...]: + if not root.exists(): + return () + found: list[Path] = [] + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [name for name in dirnames if name not in exclude_parts] + base = Path(dirpath) + for filename in filenames: + if filename.endswith(".py"): + found.append(base / filename) + found.sort() + return tuple(found) + + +@lru_cache(maxsize=64) +def _iter_repo_python_sources( + root: Path, + exclude_parts: frozenset[str], +) -> tuple[Path, ...]: + return _scan_python_sources(root, exclude_parts) + + +def iter_python_sources( + root: Path, + *, + exclude_parts: tuple[str, ...] | frozenset[str] = ("__pycache__",), +) -> tuple[Path, ...]: + """Return sorted ``*.py`` paths under ``root``, skipping ``exclude_parts``. + + Repository directories under ``_REPO_ROOT`` are cached per worker; arbitrary + external/``tmp_path`` directories are scanned fresh so tests mutating temp + trees never observe stale directory listings. + """ + excluded = frozenset(exclude_parts) + try: + resolved = root.resolve() + in_repo = resolved.is_relative_to(_REPO_ROOT) + except OSError: + in_repo = False + if in_repo: + return _iter_repo_python_sources(root, excluded) + return _scan_python_sources(root, excluded) + + +@lru_cache(maxsize=_MAX_CACHE_ENTRIES) +def _read_text_cached(resolved_path: str, mtime_ns: int, size: int) -> str: + del mtime_ns, size + return Path(resolved_path).read_text(encoding="utf-8") + + +def read_text_cached(path: Path) -> str: + """Read UTF-8 text from ``path``, cached by ``(resolved_path, mtime_ns, size)``.""" + resolved, st = _stat_target(path) + return _read_text_cached(resolved, st.st_mtime_ns, st.st_size) + + +@lru_cache(maxsize=_MAX_CACHE_ENTRIES) +def _check_python_syntax_cached(resolved_path: str, mtime_ns: int, size: int) -> None: + source = _read_text_cached(resolved_path, mtime_ns, size) + ast.parse(source, filename=resolved_path) + + +def check_python_syntax_cached(path: Path) -> None: + """Validate Python syntax without retaining an AST in the shared cache.""" + resolved, st = _stat_target(path) + _check_python_syntax_cached(resolved, st.st_mtime_ns, st.st_size) + + +@lru_cache(maxsize=_MAX_CACHE_ENTRIES) +def _parse_python_cached(resolved_path: str, mtime_ns: int, size: int) -> ast.Module: + source = _read_text_cached(resolved_path, mtime_ns, size) + return ast.parse(source, filename=resolved_path) + + +def parse_python_cached(path: Path) -> ast.Module: + """Parse ``path`` into a shared immutable ``ast.Module`` cached by stat key.""" + resolved, st = _stat_target(path) + return _parse_python_cached(resolved, st.st_mtime_ns, st.st_size) diff --git a/tests/architecture/test_benchmark_experiment_identity_owner.py b/tests/architecture/test_benchmark_experiment_identity_owner.py index f6cb71ade6..d9a776cb79 100644 --- a/tests/architecture/test_benchmark_experiment_identity_owner.py +++ b/tests/architecture/test_benchmark_experiment_identity_owner.py @@ -26,6 +26,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.benchmark_toolkit import experiment_identity as owner from loopx.capabilities.benchmark_toolkit import ( concurrency_envelope, @@ -177,12 +184,11 @@ def string_elements(node: ast.AST) -> list[str] | None: return None -def identity_rows(source: str, name: str) -> list[dict[str, object]]: - """Rows for every arm-vocabulary or token-shape decision inside ``source``.""" - +def _identity_rows_from_tree( + tree: ast.Module, source: str, name: str +) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] - tree = ast.parse(source) - if ARM_PRESCREEN in source: + if ARM_PRESCREEN in source or may_split_or_escape_literal(source): for node in ast.walk(tree): elements = string_elements(node) if elements is None or set(elements) != ARM_NAMES: @@ -222,12 +228,19 @@ def identity_rows(source: str, name: str) -> list[dict[str, object]]: return list(unique.values()) -def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: - if not any(token in source for token in PRESCREEN_TOKENS): - return [] - if "A-Za-z0-9" not in source: +def identity_rows(source: str, name: str) -> list[dict[str, object]]: + """Rows for every arm-vocabulary or token-shape decision inside ``source``.""" + + if ( + ARM_PRESCREEN not in source + and not may_split_or_escape_literal(source) + and not any(token in source for token in PRESCREEN_TOKENS) + ): return [] - tree = ast.parse(source) + return _identity_rows_from_tree(ast.parse(source), source, name) + + +def _unfoldable_rows_from_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_level_string_constants(tree) return [ {"file": name, "line": node.lineno, "kind": "unfoldable_regex"} @@ -240,16 +253,31 @@ def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: ] +def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: + if not any(token in source for token in PRESCREEN_TOKENS): + return [] + return _unfoldable_rows_from_tree(ast.parse(source), name) + + def collect(root: pathlib.Path, scan_dir: str) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] - for path in sorted((root / scan_dir).rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(root / scan_dir): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue - rows.extend(identity_rows(source, path.relative_to(root).as_posix())) + has_arm_candidate = ( + ARM_PRESCREEN in source + or may_split_or_escape_literal(source) + ) + has_token_candidate = any(token in source for token in PRESCREEN_TOKENS) + if not has_arm_candidate and not has_token_candidate: + continue + rows.extend( + _identity_rows_from_tree( + parse_python_cached(path), source, path.relative_to(root).as_posix() + ) + ) return rows @@ -529,7 +557,7 @@ def test_unfoldable_token_construction_cannot_hide() -> None: def parse(module: ModuleType) -> ast.Module: path = pathlib.Path(str(module.__file__)).resolve() - return ast.parse(path.read_text(encoding="utf-8")) + return parse_python_cached(path) def module_level_bindings(tree: ast.Module) -> set[str]: @@ -575,3 +603,23 @@ def parser_arm_choices() -> list[str]: assert keyword.value.id == "ARM_ROLE_CHOICES" return list(benchmark_concurrency.ARM_ROLE_CHOICES) raise AssertionError("no argparse choices= argument found") + + +def test_collect_prescreen_catches_implicit_split_arm_and_token_literals( + tmp_path: pathlib.Path, +) -> None: + pkg = tmp_path / "loopx" + pkg.mkdir() + (pkg / "split_arm.py").write_text( + 'ARMS = {"base" "line", "control", "treatment", "explore"}\n', + encoding="utf-8", + ) + (pkg / "split_token.py").write_text( + 'import re\nPAT = re.compile(r"^[A-Za-z0-9]" r"[A-Za-z0-9_.:@+-]{0,127}$")\n', + encoding="utf-8", + ) + rows = collect(tmp_path, "loopx") + assert {(str(row["file"]), str(row["kind"])) for row in rows} == { + ("loopx/split_arm.py", "arm_vocabulary"), + ("loopx/split_token.py", "token_shape"), + } diff --git a/tests/architecture/test_chat_action_kind_owner.py b/tests/architecture/test_chat_action_kind_owner.py index b7fedf31f3..ea11b323bb 100644 --- a/tests/architecture/test_chat_action_kind_owner.py +++ b/tests/architecture/test_chat_action_kind_owner.py @@ -20,6 +20,12 @@ import pytest from loopx import chat_action_store, chat_actions +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) REPO_ROOT = Path(__file__).resolve().parents[2] OWNER_PATH = "loopx/chat_action_store.py" @@ -61,10 +67,9 @@ def set_literal(node: ast.AST) -> frozenset[str] | None: return frozenset(members) -def module_level_bindings(source: str) -> list[tuple[list[ast.expr], ast.expr | None]]: - """(targets, value) pairs for module-level assignments, typed or untyped.""" +def _module_level_bindings_tree(tree: ast.Module) -> list[tuple[list[ast.expr], ast.expr | None]]: bindings: list[tuple[list[ast.expr], ast.expr | None]] = [] - for statement in ast.parse(source).body: + for statement in tree.body: if isinstance(statement, ast.Assign): bindings.append((list(statement.targets), statement.value)) elif isinstance(statement, ast.AnnAssign): @@ -72,21 +77,33 @@ def module_level_bindings(source: str) -> list[tuple[list[ast.expr], ast.expr | return bindings -def vocabulary_assignments(source: str) -> list[str]: - """Names in this source that restate the owner's vocabulary as their own set.""" +def module_level_bindings(source: str) -> list[tuple[list[ast.expr], ast.expr | None]]: + """(targets, value) pairs for module-level assignments, typed or untyped.""" + return _module_level_bindings_tree(ast.parse(source)) + + +def _vocabulary_assignments_tree(tree: ast.Module) -> list[str]: held: list[str] = [] - for targets, value in module_level_bindings(source): + for targets, value in _module_level_bindings_tree(tree): if value is None or set_literal(value) != KIND_VALUE: continue held.extend(target.id for target in targets if isinstance(target, ast.Name)) return held +def vocabulary_assignments(source: str) -> list[str]: + """Names in this source that restate the owner's vocabulary as their own set.""" + return _vocabulary_assignments_tree(ast.parse(source)) + + def modules_holding_the_vocabulary() -> list[str]: offenders: list[str] = [] - for path in sorted(REPO_ROOT.glob("loopx/**/*.py")): + for path in iter_python_sources(REPO_ROOT / "loopx"): try: - held = vocabulary_assignments(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and "operation.execute" not in source: + continue + held = _vocabulary_assignments_tree(parse_python_cached(path)) except (SyntaxError, UnicodeDecodeError): # pragma: no cover - guarded tree continue if held: @@ -124,3 +141,17 @@ def test_the_census_reads_a_reintroduced_copy_whatever_it_is_called_or_annotated @pytest.mark.parametrize("action_kind", sorted(KIND_VALUE)) def test_every_declared_kind_is_dispatchable(action_kind: str) -> None: assert action_kind in chat_actions.SUPPORTED_ACTION_KINDS + + +def test_repo_prescreen_catches_implicit_split_action_kind_literals( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + (tmp_path / "loopx").mkdir() + sample = tmp_path / "loopx" / "shadow.py" + members = ", ".join( + '"operation." "execute"' if value == "operation.execute" else repr(value) + for value in sorted(KIND_VALUE) + ) + sample.write_text(f"SHADOW = {{{members}}}\n", encoding="utf-8") + monkeypatch.setitem(globals(), "REPO_ROOT", tmp_path) + assert modules_holding_the_vocabulary() == ["loopx/shadow.py"] diff --git a/tests/architecture/test_chat_capabilities_route_single_owner.py b/tests/architecture/test_chat_capabilities_route_single_owner.py index c0da9b98bc..aa64929d2b 100644 --- a/tests/architecture/test_chat_capabilities_route_single_owner.py +++ b/tests/architecture/test_chat_capabilities_route_single_owner.py @@ -21,6 +21,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + from loopx import chat_server, dashboard_launcher @@ -36,7 +42,7 @@ def _python_modules(root: Path) -> list[Path]: - return sorted(path for path in (root / "loopx").rglob("*.py")) + return list(iter_python_sources(root / "loopx")) def _web_sources(root: Path) -> list[Path]: @@ -116,10 +122,10 @@ def _module_bindings(root: Path) -> dict[str, int]: """Name every module that binds the constant at module level.""" offenders: dict[str, int] = {} for path in _python_modules(root): - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) if CONSTANT_NAME not in source: continue - tree = ast.parse(source) + tree = parse_python_cached(path) lines = [ node.lineno for node in tree.body diff --git a/tests/architecture/test_connector_token_shape_owner.py b/tests/architecture/test_connector_token_shape_owner.py index d3ca0c0649..856adcfdda 100644 --- a/tests/architecture/test_connector_token_shape_owner.py +++ b/tests/architecture/test_connector_token_shape_owner.py @@ -26,6 +26,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + from loopx.extensions import external_connector_provider as provider from loopx.extensions import external_connector_runtime as owner from loopx.extensions.lark import document_comment_provider as lark_document @@ -145,10 +151,7 @@ def regex_calls(tree: ast.Module) -> list[ast.Call]: return calls -def shape_rows(source: str, name: str) -> list[dict[str, object]]: - if not any(token in source for token in PRESCREEN_TOKENS) or MARKER not in source: - return [] - tree = ast.parse(source) +def _shape_rows_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_level_string_constants(tree) rows: list[dict[str, object]] = [] for node in regex_calls(tree): @@ -160,10 +163,13 @@ def shape_rows(source: str, name: str) -> list[dict[str, object]]: return rows -def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: - if not any(token in source for token in PRESCREEN_TOKENS) or MARKER not in source: +def shape_rows(source: str, name: str) -> list[dict[str, object]]: + if not any(token in source for token in PRESCREEN_TOKENS): return [] - tree = ast.parse(source) + return _shape_rows_tree(ast.parse(source), name) + + +def _unfoldable_rows_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_level_string_constants(tree) return [ {"file": name, "line": node.lineno, "kind": "unfoldable"} @@ -173,19 +179,26 @@ def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: ] +def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: + if not any(token in source for token in PRESCREEN_TOKENS): + return [] + return _unfoldable_rows_tree(ast.parse(source), name) + + def collect() -> tuple[list[dict[str, object]], list[dict[str, object]]]: shapes: list[dict[str, object]] = [] unfoldable: list[dict[str, object]] = [] - for path in sorted((REPO_ROOT / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(REPO_ROOT / "loopx"): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue + if not any(token in source for token in PRESCREEN_TOKENS): + continue relative = path.relative_to(REPO_ROOT).as_posix() - shapes.extend(shape_rows(source, relative)) - unfoldable.extend(unfoldable_rows(source, relative)) + tree = parse_python_cached(path) + shapes.extend(_shape_rows_tree(tree, relative)) + unfoldable.extend(_unfoldable_rows_tree(tree, relative)) return shapes, unfoldable @@ -211,7 +224,7 @@ def referenced(tree: ast.Module, name: str) -> bool: def parse(module: ModuleType) -> ast.Module: path = pathlib.Path(str(module.__file__)).resolve() - return ast.parse(path.read_text(encoding="utf-8")) + return parse_python_cached(path) # -------------------------------------------------------------------------- diff --git a/tests/architecture/test_content_digest_production_owner.py b/tests/architecture/test_content_digest_production_owner.py index e42a176b75..a64c066d18 100644 --- a/tests/architecture/test_content_digest_production_owner.py +++ b/tests/architecture/test_content_digest_production_owner.py @@ -49,6 +49,12 @@ BARE_SHA256_PATTERN, ENVELOPED_SHA256_PATTERN, ) +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) from tests.architecture.test_content_digest_single_owner import ( _collect_scopes, _fold_text, @@ -90,8 +96,7 @@ def _fold_joined_prefix(node: ast.JoinedStr, scope: Any) -> str | None: return prefix -def _hand_built_envelopes(source: str) -> list[str]: - tree = ast.parse(source) +def _hand_built_envelopes_tree(tree: ast.Module) -> list[str]: root = _collect_scopes(tree) hits: list[str] = [] for node in ast.walk(tree): @@ -126,6 +131,10 @@ def _hand_built_envelopes(source: str) -> list[str]: return hits +def _hand_built_envelopes(source: str) -> list[str]: + return _hand_built_envelopes_tree(ast.parse(source)) + + def _scan_source(relative: str, source: str) -> list[str]: if relative == PRODUCTION_OWNER: return [] @@ -135,9 +144,11 @@ def _scan_source(relative: str, source: str) -> list[str]: def _scan_surface(directory: str) -> dict[str, list[str]]: offenders: dict[str, list[str]] = {} root = REPOSITORY_ROOT / directory - for path in sorted(root.rglob("*.py")): + for path in iter_python_sources(root): relative = path.relative_to(REPOSITORY_ROOT).as_posix() - hits = _scan_source(relative, path.read_text(encoding="utf-8")) + if relative == PRODUCTION_OWNER: + continue + hits = _hand_built_envelopes_tree(parse_python_cached(path)) if hits: offenders[relative] = hits return offenders @@ -261,11 +272,14 @@ def test_the_owner_is_the_only_module_that_states_the_prefix_rule() -> None: # the staging meaningful: the prefix literal lives in exactly two modules, # the generated shape owner and the production owner. holders: dict[str, list[str]] = {} - for path in sorted((REPOSITORY_ROOT / "loopx").rglob("*.py")): + for path in iter_python_sources(REPOSITORY_ROOT / "loopx"): relative = path.relative_to(REPOSITORY_ROOT).as_posix() if relative in {PRODUCTION_OWNER, "loopx/control_plane/content_digest.py"}: continue - tree = ast.parse(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and ENVELOPE not in source: + continue + tree = parse_python_cached(path) prefixed = [ target.id for node in tree.body @@ -422,3 +436,23 @@ def test_a_valid_bare_digest_still_matches_the_bare_shape() -> None: digest = hashlib.sha256(b"x").hexdigest() assert BARE_SHA256_PATTERN.fullmatch(digest) assert digest_envelope.sha256_envelope(b"x") == f"sha256:{digest}" + + +def test_scan_surface_catches_multiline_and_adjacent_split_envelopes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + surface = tmp_path / "loopx" / "capabilities" / "periodic_report" + surface.mkdir(parents=True) + (surface / "split.py").write_text( + 'def build(digest: str) -> str:\n' + ' return (\n' + ' "sha"\n' + ' # comment inside wrap\n' + ' "256:"\n' + ' + digest\n' + ' )\n', + encoding="utf-8", + ) + monkeypatch.setitem(globals(), "REPOSITORY_ROOT", tmp_path) + offenders = _scan_surface("loopx/capabilities/periodic_report") + assert list(offenders) == ["loopx/capabilities/periodic_report/split.py"] diff --git a/tests/architecture/test_content_digest_single_owner.py b/tests/architecture/test_content_digest_single_owner.py index ee512f209d..b25fd35018 100644 --- a/tests/architecture/test_content_digest_single_owner.py +++ b/tests/architecture/test_content_digest_single_owner.py @@ -41,6 +41,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + read_text_cached, +) + from loopx.control_plane import content_digest from loopx.control_plane.content_digest import ( BARE_SHA256_PATTERN, @@ -785,6 +791,25 @@ def _analyse(source: str, name: str = "") -> dict[str, Any]: _REPO_SCAN: list[dict[str, Any]] | None = None +_CONTENT_DIGEST_IMPORT_RE = re.compile( + r"\b(?:from\s+[\w.]*content_digest\b|import\s+(?:[^\n]*|\([^)]*)\bcontent_digest\b)" +) + + +def _needs_digest_scan(source: str) -> bool: + if "content_digest" in source and _CONTENT_DIGEST_IMPORT_RE.search(source) is not None: + return True + if may_split_or_escape_literal(source, include_plus=True): + return True + if ( + "{" in source + and "}" in source + and ("64}" in source or "{64" in source or '"6"' in source or "'6'" in source) + and ("a-f" in source or "0-9" in source or "f0" in source or "9a" in source) + ): + return True + return False + def _repo_scan() -> list[dict[str, Any]]: """One pass over every module under `loopx/`, shared by all four layers. @@ -796,13 +821,18 @@ def _repo_scan() -> list[dict[str, Any]]: global _REPO_SCAN if _REPO_SCAN is None: entries: list[dict[str, Any]] = [] - for path in sorted( - candidate - for candidate in PACKAGE_ROOT.rglob("*.py") - if "__pycache__" not in candidate.parts - ): - source = path.read_text(encoding="utf-8") - entry = _analyse(source, str(path)) + for path in iter_python_sources(PACKAGE_ROOT): + source = read_text_cached(path) + if _needs_digest_scan(source): + entry = _analyse(source, str(path)) + else: + entry = { + "statements": [], + "constructions": [], + "owner_imports": {}, + "owner_text_reads": [], + "loaded": set(), + } entry["path"] = path entry["relative"] = f"loopx/{path.relative_to(PACKAGE_ROOT).as_posix()}" parts = list(path.relative_to(PACKAGE_ROOT.parent).parts) @@ -1796,3 +1826,17 @@ def test_benchmark_dynamic_regex_exemption_stays_in_the_marker_reader() -> None: assert len(unreadable) == 1, "the marker exception must not hide another matcher" assert marker_reader.lineno <= unreadable[0]["line"] <= marker_reader.end_lineno assert unreadable[0]["construction"] == "search", "not a whole-value reader" + + +@pytest.mark.parametrize( + "source", + [ + 'import re\nPAT = re.compile(r"^[0-9a-f]{6" r"4}$")\n', + 'import re\nPAT = re.compile(\n r"^[0-9a-f]{"\n # wrapped across lines\n r"64}$"\n)\n', + 'import re\nPAT = re.compile(\n r"^sha"\n # wrapped comment\n r"256:[0-9a-f]{64}$"\n)\n', + ], +) +def test_digest_prescreen_retains_implicit_split_literals(source: str) -> None: + assert _needs_digest_scan(source) is True + analysis = _analyse(source) + assert analysis["constructions"] diff --git a/tests/architecture/test_contributor_task_board.py b/tests/architecture/test_contributor_task_board.py index 487d4d703e..8c49b6759e 100644 --- a/tests/architecture/test_contributor_task_board.py +++ b/tests/architecture/test_contributor_task_board.py @@ -2,6 +2,7 @@ from __future__ import annotations +import os import re import runpy import shutil @@ -13,9 +14,33 @@ ROOT = Path(__file__).resolve().parents[2] +@pytest.fixture(scope="module") +def _shared_smoke(): + return runpy.run_path(str(ROOT / "examples/docs-governance-smoke.py")) + + +@pytest.fixture(scope="module") +def _shared_board_tree(tmp_path_factory: pytest.TempPathFactory) -> Path: + root = tmp_path_factory.mktemp("contributor-board-shared") + (root / "docs/architecture").mkdir(parents=True) + os.symlink(ROOT / "docs/architecture/rfcs", root / "docs/architecture/rfcs") + (root / "scripts").mkdir() + shutil.copyfile( + ROOT / "scripts/generate_rfc_status_index.py", + root / "scripts/generate_rfc_status_index.py", + ) + return root + + @pytest.fixture -def check_board(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - smoke = runpy.run_path(str(ROOT / "examples/docs-governance-smoke.py")) +def check_board( + request: pytest.FixtureRequest, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + _shared_smoke, + _shared_board_tree: Path, +): + smoke = _shared_smoke check = smoke["assert_contributor_task_board_is_current"] scope = check.__globals__ @@ -23,17 +48,27 @@ def original_read(path: str) -> str: return (ROOT / path).read_text(encoding="utf-8") board = original_read("docs/development/contributor-tasks.md") - # The board consumes the real generator and real local RFC files. Changes to - # lifecycle in these disposable files must affect admission immediately. - shutil.copytree( - ROOT / "docs/architecture/rfcs", tmp_path / "docs/architecture/rfcs" - ) - (tmp_path / "scripts").mkdir() - shutil.copyfile( - ROOT / "scripts/generate_rfc_status_index.py", - tmp_path / "scripts/generate_rfc_status_index.py", - ) - monkeypatch.setitem(scope, "REPO_ROOT", tmp_path) + # Most tests only mutate the in-memory board text; only tests that mutate + # RFC files on disk need a fresh temporary RFC directory with a private copy + # of the edited RFC and symlinked siblings. + if request.node.originalname == "test_inactive_or_unmerged_design_cannot_be_available": + rfcs_dir = tmp_path / "docs/architecture/rfcs" + rfcs_dir.mkdir(parents=True) + for entry in (ROOT / "docs/architecture/rfcs").iterdir(): + target = rfcs_dir / entry.name + if entry.name == "goal-direction-baseline-v0.md": + shutil.copyfile(entry, target) + else: + os.symlink(entry, target) + (tmp_path / "scripts").mkdir() + shutil.copyfile( + ROOT / "scripts/generate_rfc_status_index.py", + tmp_path / "scripts/generate_rfc_status_index.py", + ) + board_root = tmp_path + else: + board_root = _shared_board_tree + monkeypatch.setitem(scope, "REPO_ROOT", board_root) def run(updated: str = board) -> None: monkeypatch.setitem( @@ -56,7 +91,7 @@ def run(updated: str = board) -> None: "| Synthetic admission gap. Exit: preserve canonical admission. " "| Focused admission negative controls | Available |" ) - return run, board.replace(first_row, fixture_row, 1), tmp_path + return run, board.replace(first_row, fixture_row, 1), board_root def edit_row( diff --git a/tests/architecture/test_control_plane_import_boundaries.py b/tests/architecture/test_control_plane_import_boundaries.py index 82f34c0381..59d315540e 100644 --- a/tests/architecture/test_control_plane_import_boundaries.py +++ b/tests/architecture/test_control_plane_import_boundaries.py @@ -4,6 +4,7 @@ import importlib from importlib.util import resolve_name from pathlib import Path +import re import subprocess import sys @@ -13,6 +14,11 @@ REVIEWED_MAINTAINABILITY_EXCEPTIONS, evaluate_maintainability_findings, ) +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) REPOSITORY_ROOT = Path(__file__).resolve().parents[2] PACKAGE_ROOT = REPOSITORY_ROOT / "loopx" @@ -74,7 +80,7 @@ def _module_name(path: Path) -> str: def _resolved_imports(path: Path) -> set[str]: module_name = _module_name(path) package_name = module_name if path.name == "__init__.py" else module_name.rpartition(".")[0] - tree = ast.parse(path.read_bytes(), filename=str(path)) + tree = parse_python_cached(path) imports: set[str] = set() for node in ast.walk(tree): if isinstance(node, ast.Import): @@ -92,7 +98,7 @@ def _resolved_from_imports(path: Path) -> dict[str, set[str]]: if path.is_relative_to(PACKAGE_ROOT): module_name = _module_name(path) package_name = module_name if path.name == "__init__.py" else module_name.rpartition(".")[0] - tree = ast.parse(path.read_bytes(), filename=str(path)) + tree = parse_python_cached(path) imports: dict[str, set[str]] = {} for node in ast.walk(tree): if not isinstance(node, ast.ImportFrom): @@ -107,7 +113,7 @@ def _resolved_from_imports(path: Path) -> dict[str, set[str]]: def _top_level_imported_names(path: Path) -> set[str]: - tree = ast.parse(path.read_bytes(), filename=str(path)) + tree = parse_python_cached(path) return { alias.asname or alias.name for node in tree.body @@ -117,7 +123,7 @@ def _top_level_imported_names(path: Path) -> set[str]: def _top_level_function_names(path: Path) -> set[str]: - tree = ast.parse(path.read_bytes(), filename=str(path)) + tree = parse_python_cached(path) return { node.name for node in tree.body @@ -128,7 +134,7 @@ def _top_level_function_names(path: Path) -> set[str]: def _top_level_import_bindings(path: Path) -> dict[str, str]: module_name = _module_name(path) package_name = module_name.rpartition(".")[0] - tree = ast.parse(path.read_bytes(), filename=str(path)) + tree = parse_python_cached(path) bindings: dict[str, str] = {} for node in tree.body: if isinstance(node, ast.Import): @@ -144,7 +150,7 @@ def _top_level_import_bindings(path: Path) -> dict[str, str]: def _public_import_only_bindings(path: Path) -> dict[str, str]: - tree = ast.parse(path.read_bytes(), filename=str(path)) + tree = parse_python_cached(path) loaded_names = { node.id for node in ast.walk(tree) @@ -157,11 +163,32 @@ def _public_import_only_bindings(path: Path) -> dict[str, str]: } +_FACADE_IMPORT_HINT = re.compile( + r"\bfrom\s*(?:\\\r?\n\s*)*loopx(?:\s*\.\s*(?:status|quota)\b|\s+import(?:\s*\([^)]*\b(?:status|quota)\b|[^\n]*\b(?:status|quota)\b))", + re.DOTALL, +) +_RELATIVE_FACADE_HINT = re.compile( + r"\bfrom\s*(?:\\\r?\n\s*)*\.+(?:\s*(?:status|quota)\b|\s+import(?:\s*\([^)]*\b(?:status|quota)\b|[^\n]*\b(?:status|quota)\b))", + re.DOTALL, +) + + def _public_contract_evidence() -> dict[tuple[str, str], set[str]]: evidence: dict[tuple[str, str], set[str]] = {} for root in PUBLIC_CONTRACT_ROOTS: - for path in root.rglob("*.py"): - tree = ast.parse(path.read_bytes(), filename=str(path)) + for path in iter_python_sources(root): + try: + source = read_text_cached(path) + except UnicodeDecodeError: + tree = ast.parse(path.read_bytes(), filename=str(path)) + else: + if ( + ("status" not in source and "quota" not in source) + or "loopx" not in source + or _FACADE_IMPORT_HINT.search(source) is None + ): + continue + tree = parse_python_cached(path) # Aliases such as ``from loopx import status as status_module`` are a # real consumer of a facade export, reached by attribute access # rather than a from-import. Without this map the audit would report @@ -192,11 +219,14 @@ def _public_contract_evidence() -> dict[tuple[str, str], set[str]]: evidence.setdefault((facade_name, node.attr), set()).add( str(path.relative_to(REPOSITORY_ROOT)) ) + facade_exports = [ + (facade_name, importlib.import_module(facade_name)._PUBLIC_COMPAT_REEXPORTS) + for facade_name in PUBLIC_COMPAT_FACADES + ] for path in (REPOSITORY_ROOT / "docs").rglob("*.md"): text = path.read_text(encoding="utf-8") - for facade_name in PUBLIC_COMPAT_FACADES: - facade = importlib.import_module(facade_name) - for export_name in facade._PUBLIC_COMPAT_REEXPORTS: + for facade_name, exports in facade_exports: + for export_name in exports: if ( f"{facade_name}.{export_name}" in text or f"from {facade_name} import {export_name}" in text @@ -221,7 +251,7 @@ def _review_outward_dependencies(edges, *, reviewed=REVIEWED_MAINTAINABILITY_EXC def test_control_plane_has_no_unreviewed_outward_dependencies() -> None: outward_dependencies = { (_module_name(path), dependency) - for path in CONTROL_PLANE_ROOT.rglob("*.py") + for path in iter_python_sources(CONTROL_PLANE_ROOT) for dependency in _resolved_imports(path) if any( dependency == prefix or dependency.startswith(prefix + ".") @@ -559,14 +589,18 @@ def test_inert_lark_projector_does_not_load_routes_before_activation(tmp_path) - def test_core_does_not_import_experiments() -> None: - forbidden_edges = { - (_module_name(path), dependency) - for path in PACKAGE_ROOT.rglob("*.py") - if not path.is_relative_to(EXPERIMENT_ROOT) - for dependency in _resolved_imports(path) - if dependency == EXPERIMENT_PREFIX - or dependency.startswith(EXPERIMENT_PREFIX + ".") - } + forbidden_edges: set[tuple[str, str]] = set() + for path in iter_python_sources(PACKAGE_ROOT): + if path.is_relative_to(EXPERIMENT_ROOT): + continue + source = read_text_cached(path) + if "experiments" not in source: + continue + for dependency in _resolved_imports(path): + if dependency == EXPERIMENT_PREFIX or dependency.startswith( + EXPERIMENT_PREFIX + "." + ): + forbidden_edges.add((_module_name(path), dependency)) assert not forbidden_edges, ( "stable LoopX code must not depend on opt-in experiments; " @@ -608,16 +642,31 @@ def test_internal_consumers_bypass_status_and_quota_reexport_routes() -> None: internal_paths = ( path for root in (PACKAGE_ROOT, SCRIPTS_ROOT) - for path in root.rglob("*.py") + for path in iter_python_sources(root) if path not in {STATUS_MODULE, QUOTA_MODULE} ) - indirect_imports = { - (_module_name(path) if path.is_relative_to(PACKAGE_ROOT) else str(path.relative_to(REPOSITORY_ROOT)), facade, name) - for path in internal_paths - for facade, imported_names in _resolved_from_imports(path).items() - if facade in facade_reexports - for name in imported_names & facade_reexports[facade] - } + indirect_imports = set() + for path in internal_paths: + source = read_text_cached(path) + if ( + ("status" not in source and "quota" not in source) + or "from" not in source + or ( + _FACADE_IMPORT_HINT.search(source) is None + and _RELATIVE_FACADE_HINT.search(source) is None + ) + ): + continue + for facade, imported_names in _resolved_from_imports(path).items(): + if facade not in facade_reexports: + continue + for name in imported_names & facade_reexports[facade]: + target = ( + _module_name(path) + if path.is_relative_to(PACKAGE_ROOT) + else str(path.relative_to(REPOSITORY_ROOT)) + ) + indirect_imports.add((target, facade, name)) assert not indirect_imports, ( "repository-internal consumers must import extracted symbols from their " @@ -738,7 +787,8 @@ def test_lark_inbox_provider_is_owned_by_the_extension_layer() -> None: } remaining_legacy_imports = { (_module_name(path), dependency) - for path in PACKAGE_ROOT.rglob("*.py") + for path in iter_python_sources(PACKAGE_ROOT) + if "lark" in read_text_cached(path) for dependency in _resolved_imports(path) if dependency in legacy_imports } @@ -768,7 +818,8 @@ def test_lark_projection_sinks_are_owned_by_the_extension_layer() -> None: core_provider_imports = { (_module_name(path), dependency) for root in (PACKAGE_ROOT / "capabilities", PACKAGE_ROOT / "presentation") - for path in root.rglob("*.py") + for path in iter_python_sources(root) + if "lark" in read_text_cached(path) for dependency in _resolved_imports(path) if dependency == "loopx.extensions.lark" or dependency.startswith("loopx.extensions.lark.") diff --git a/tests/architecture/test_goal_id_path_segment_owner.py b/tests/architecture/test_goal_id_path_segment_owner.py index 67ac51537f..f22339c44b 100644 --- a/tests/architecture/test_goal_id_path_segment_owner.py +++ b/tests/architecture/test_goal_id_path_segment_owner.py @@ -13,6 +13,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx import history, paths, runtime from loopx.control_plane.quota import slot_accounting @@ -49,9 +56,12 @@ def _states_traversal_rule(node: ast.AST) -> bool: def _sites(root: Path) -> dict[str, int]: found: dict[str, int] = {} - for path in sorted((root / "loopx").rglob("*.py")): + for path in iter_python_sources(root / "loopx"): + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and "goal id is required" not in source: + continue relative = path.relative_to(root).as_posix() - tree = ast.parse(path.read_text(encoding="utf-8")) + tree = parse_python_cached(path) count = sum( 1 for node in ast.walk(tree) diff --git a/tests/architecture/test_issue_fix_close_event_type_owner.py b/tests/architecture/test_issue_fix_close_event_type_owner.py index 30eacdf7c1..b524cd4817 100644 --- a/tests/architecture/test_issue_fix_close_event_type_owner.py +++ b/tests/architecture/test_issue_fix_close_event_type_owner.py @@ -31,6 +31,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.issue_fix import ( metrics_projection as projection_mod, metrics_supplement as owner, @@ -83,14 +90,7 @@ def _members(node: ast.expr) -> frozenset[str] | None: return None -def _close_type_literal_sites(source: str) -> list[int]: - """Every collection literal in the source folding to ISSUE_CLOSE, counted once. - - ``frozenset({...})`` is walked as both the call and its inner set; the inner - node is skipped so one restatement is one site, not two. - """ - - tree = ast.parse(source) +def _close_type_literal_sites_tree(tree: ast.Module) -> list[int]: wrapped = { id(node.args[0]) for node in ast.walk(tree) @@ -106,14 +106,27 @@ def _close_type_literal_sites(source: str) -> list[int]: ] +def _close_type_literal_sites(source: str) -> list[int]: + """Every collection literal in the source folding to ISSUE_CLOSE, counted once. + + ``frozenset({...})`` is walked as both the call and its inner set; the inner + node is skipped so one restatement is one site, not two. + """ + + return _close_type_literal_sites_tree(ast.parse(source)) + + @pytest.fixture(scope="module") def tree_offenders() -> dict[str, list[int]]: offenders: dict[str, list[int]] = {} - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): relative = path.relative_to(REPO_ROOT).as_posix() if relative == OWNER_PATH: continue - sites = _close_type_literal_sites(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and "issue_close_recommended" not in source: + continue + sites = _close_type_literal_sites_tree(parse_python_cached(path)) if sites: offenders[relative] = sites return offenders diff --git a/tests/architecture/test_issue_fix_local_time_owner.py b/tests/architecture/test_issue_fix_local_time_owner.py index 14d7a4398f..011711dbd3 100644 --- a/tests/architecture/test_issue_fix_local_time_owner.py +++ b/tests/architecture/test_issue_fix_local_time_owner.py @@ -22,6 +22,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.issue_fix import reward_memory, reviewer_notification from loopx.domain_packs import issue_fix as issue_fix_pack @@ -98,10 +105,7 @@ def matcher_calls(tree: ast.Module) -> list[ast.Call]: return calls -def time_rows(source: str, name: str) -> list[dict[str, object]]: - if ":" not in source: - return [] - tree = ast.parse(source) +def _time_rows_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_constants(tree) rows: list[dict[str, object]] = [] for node in matcher_calls(tree): @@ -110,10 +114,13 @@ def time_rows(source: str, name: str) -> list[dict[str, object]]: return rows -def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: - if ":" not in source or "[0-3]" not in source: +def time_rows(source: str, name: str) -> list[dict[str, object]]: + if ":" not in source and not may_split_or_escape_literal(source, include_plus=True): return [] - tree = ast.parse(source) + return _time_rows_tree(ast.parse(source), name) + + +def _unfoldable_rows_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_constants(tree) return [ {"file": name, "line": node.lineno, "kind": "unfoldable"} @@ -123,29 +130,54 @@ def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: ] +def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: + if (":" not in source or "[0-3]" not in source) and not may_split_or_escape_literal( + source, include_plus=True + ): + return [] + return _unfoldable_rows_tree(ast.parse(source), name) + + def collect(root: pathlib.Path) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] - for path in sorted((root / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(root / "loopx"): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue - rows.extend(time_rows(source, path.relative_to(root).as_posix())) + if not any(matcher in source for matcher in MATCHERS): + continue + if not may_split_or_escape_literal(source, include_plus=True) and ( + ":" not in source + or not ( + "[0-5]" in source + or "[01]" in source + or "2[0-3]" in source + ) + ): + continue + rows.extend(_time_rows_tree(parse_python_cached(path), path.relative_to(root).as_posix())) return rows def collect_unfoldable(root: pathlib.Path) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] - for path in sorted((root / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(root / "loopx"): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue - rows.extend(unfoldable_rows(source, path.relative_to(root).as_posix())) + if not any(matcher in source for matcher in MATCHERS): + continue + if not may_split_or_escape_literal(source, include_plus=True) and ( + ":" not in source or "[0-3]" not in source + ): + continue + rows.extend( + _unfoldable_rows_tree( + parse_python_cached(path), path.relative_to(root).as_posix() + ) + ) return rows @@ -217,14 +249,17 @@ def referenced(tree: ast.Module, name: str) -> bool: def parse(module: ModuleType) -> ast.Module: path = pathlib.Path(str(module.__file__)).resolve() - return ast.parse(path.read_text(encoding="utf-8")) + return parse_python_cached(path) def modules_importing_the_owner() -> set[str]: importing: set[str] = set() - for path in sorted((REPO_ROOT / "loopx").rglob("*.py")): + for path in iter_python_sources(REPO_ROOT / "loopx"): try: - tree = ast.parse(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if source.isascii() and OWNER_NAME not in source: + continue + tree = parse_python_cached(path) except (OSError, UnicodeDecodeError, SyntaxError): continue for node in ast.walk(tree): diff --git a/tests/architecture/test_issue_fix_queue_receipt_version_owner.py b/tests/architecture/test_issue_fix_queue_receipt_version_owner.py index 4bc99c1658..1f70e10e03 100644 --- a/tests/architecture/test_issue_fix_queue_receipt_version_owner.py +++ b/tests/architecture/test_issue_fix_queue_receipt_version_owner.py @@ -23,6 +23,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.issue_fix import reviewer_notification from loopx.domain_packs import issue_fix as issue_fix_pack @@ -112,8 +119,7 @@ def module_constants(tree: ast.Module) -> dict[str, str]: return constants -def version_rows(source: str, name: str) -> list[dict[str, object]]: - tree = ast.parse(source) +def _version_rows_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_constants(tree) rows: list[dict[str, object]] = [] for _bound, lineno, value in stated_bindings(tree): @@ -122,16 +128,23 @@ def version_rows(source: str, name: str) -> list[dict[str, object]]: return rows +def version_rows(source: str, name: str) -> list[dict[str, object]]: + return _version_rows_tree(ast.parse(source), name) + + def collect(root: pathlib.Path) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] - for path in sorted((root / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(root / "loopx"): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue - rows.extend(version_rows(source, path.relative_to(root).as_posix())) + if ( + "receipt_v1" not in source + and not may_split_or_escape_literal(source, include_plus=True) + ): + continue + rows.extend(_version_rows_tree(parse_python_cached(path), path.relative_to(root).as_posix())) return rows diff --git a/tests/architecture/test_lark_event_prefix_owner.py b/tests/architecture/test_lark_event_prefix_owner.py index 26e2faeb79..91570c8adc 100644 --- a/tests/architecture/test_lark_event_prefix_owner.py +++ b/tests/architecture/test_lark_event_prefix_owner.py @@ -13,6 +13,8 @@ import pathlib +from tests.architecture._repo_ast_cache import iter_python_sources, read_text_cached + from loopx.extensions.lark import ( event_collector_runtime, goal_topic_runtime, @@ -25,14 +27,10 @@ def _module_sources() -> dict[str, str]: - sources: dict[str, str] = {} - for path in sorted((REPO_ROOT / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue - sources[path.relative_to(REPO_ROOT).as_posix()] = path.read_text( - encoding="utf-8" - ) - return sources + return { + path.relative_to(REPO_ROOT).as_posix(): read_text_cached(path) + for path in iter_python_sources(REPO_ROOT / "loopx") + } def test_only_the_owner_states_each_event_line_prefix() -> None: diff --git a/tests/architecture/test_lark_identity_shape_owner.py b/tests/architecture/test_lark_identity_shape_owner.py index dfe96c195e..cf94d0b9a2 100644 --- a/tests/architecture/test_lark_identity_shape_owner.py +++ b/tests/architecture/test_lark_identity_shape_owner.py @@ -25,6 +25,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + from loopx.extensions.lark import ( event_collector, event_collector_routes, @@ -280,12 +286,7 @@ def regex_constructions(tree: ast.Module) -> list[ast.Call]: return calls -def shape_rows_in_source(source: str, name: str) -> list[dict[str, object]]: - """Every whole-value identifier shape decided inside ``source``.""" - - if not any(token in source for token in PRESCREEN_TOKENS): - return [] - tree = ast.parse(source) +def _shape_rows_in_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_level_string_constants(tree) rows: list[dict[str, object]] = [] for node in regex_constructions(tree): @@ -309,14 +310,15 @@ def shape_rows_in_source(source: str, name: str) -> list[dict[str, object]]: return sorted(rows, key=lambda row: (str(row["file"]), int(row["line"]))) -def unfoldable_rows_in_source(source: str, name: str) -> list[dict[str, object]]: - """Regex constructions in ``source`` whose pattern value cannot be folded.""" +def shape_rows_in_source(source: str, name: str) -> list[dict[str, object]]: + """Every whole-value identifier shape decided inside ``source``.""" if not any(token in source for token in PRESCREEN_TOKENS): return [] - if not any(token in source for token in IDENTIFIER_RELEVANCE_TOKENS): - return [] - tree = ast.parse(source) + return _shape_rows_in_tree(ast.parse(source), name) + + +def _unfoldable_rows_in_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_level_string_constants(tree) return [ {"file": name, "line": node.lineno, "unfoldable": True} @@ -325,13 +327,21 @@ def unfoldable_rows_in_source(source: str, name: str) -> list[dict[str, object]] ] +def unfoldable_rows_in_source(source: str, name: str) -> list[dict[str, object]]: + """Regex constructions in ``source`` whose pattern value cannot be folded.""" + + if not any(token in source for token in PRESCREEN_TOKENS): + return [] + if not any(token in source for token in IDENTIFIER_RELEVANCE_TOKENS): + return [] + return _unfoldable_rows_in_tree(ast.parse(source), name) + + def collect_source_rows(root: pathlib.Path) -> list[tuple[str, str]]: pairs: list[tuple[str, str]] = [] - for path in sorted(root.rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(root): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue pairs.append((path.relative_to(REPO_ROOT).as_posix(), source)) @@ -339,19 +349,33 @@ def collect_source_rows(root: pathlib.Path) -> list[tuple[str, str]]: def collect_shape_definitions(root: pathlib.Path) -> list[dict[str, object]]: - return [ - row - for name, source in collect_source_rows(root) - for row in shape_rows_in_source(source, name) - ] + rows: list[dict[str, object]] = [] + for path in iter_python_sources(root): + try: + source = read_text_cached(path) + except (OSError, UnicodeDecodeError): + continue + if not any(token in source for token in PRESCREEN_TOKENS): + continue + name = path.relative_to(REPO_ROOT).as_posix() + rows.extend(_shape_rows_in_tree(parse_python_cached(path), name)) + return rows def collect_unfoldable_definitions(root: pathlib.Path) -> list[dict[str, object]]: - return [ - row - for name, source in collect_source_rows(root) - for row in unfoldable_rows_in_source(source, name) - ] + rows: list[dict[str, object]] = [] + for path in iter_python_sources(root): + try: + source = read_text_cached(path) + except (OSError, UnicodeDecodeError): + continue + if not any(token in source for token in PRESCREEN_TOKENS): + continue + if not any(token in source for token in IDENTIFIER_RELEVANCE_TOKENS): + continue + name = path.relative_to(REPO_ROOT).as_posix() + rows.extend(_unfoldable_rows_in_tree(parse_python_cached(path), name)) + return rows def offender_rows( @@ -435,7 +459,7 @@ def references(tree: ast.Module, name: str) -> bool: def parse_module(module: ModuleType) -> ast.Module: path = pathlib.Path(str(module.__file__)).resolve() - return ast.parse(path.read_text(encoding="utf-8")) + return parse_python_cached(path) # -------------------------------------------------------------------------- diff --git a/tests/architecture/test_lark_sink_visibility_owner.py b/tests/architecture/test_lark_sink_visibility_owner.py index 4aeebd959c..61ad1b104e 100644 --- a/tests/architecture/test_lark_sink_visibility_owner.py +++ b/tests/architecture/test_lark_sink_visibility_owner.py @@ -33,6 +33,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.explore.result_log import EXPLORE_RESULT_PROJECTION_VERSION from loopx.cli_commands.explore_feishu_commands import register_explore_feishu_commands from loopx.cli_commands.lark_kanban import register_lark_kanban_commands @@ -90,10 +96,7 @@ def module_source(path: pathlib.Path) -> str: return path.read_text(encoding="utf-8") -def module_level_binds(source: str) -> list[tuple[int, str]]: - """Name the module-level assignments that restate a guarded name.""" - - tree = ast.parse(source) +def _module_level_binds_tree(tree: ast.Module) -> list[tuple[int, str]]: found: list[tuple[int, str]] = [] for node in tree.body: if not isinstance(node, ast.Assign): @@ -104,10 +107,13 @@ def module_level_binds(source: str) -> list[tuple[int, str]]: return found -def inline_pair_sites(source: str) -> list[tuple[int, str]]: - """Name every string literal that carries one half of the pair.""" +def module_level_binds(source: str) -> list[tuple[int, str]]: + """Name the module-level assignments that restate a guarded name.""" - tree = ast.parse(source) + return _module_level_binds_tree(ast.parse(source)) + + +def _inline_pair_sites_tree(tree: ast.Module) -> list[tuple[int, str]]: found: list[tuple[int, str]] = [] for node in ast.walk(tree): if isinstance(node, ast.Constant) and node.value in PAIR_VALUES: @@ -116,20 +122,32 @@ def inline_pair_sites(source: str) -> list[tuple[int, str]]: return found +def inline_pair_sites(source: str) -> list[tuple[int, str]]: + """Name every string literal that carries one half of the pair.""" + + return _inline_pair_sites_tree(ast.parse(source)) + + def scan_tree() -> tuple[list[str], list[str]]: """Return (restated-name findings, inline-literal findings) across ``loopx/``.""" name_findings: list[str] = [] literal_findings: list[str] = [] - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): rel = path.relative_to(REPO_ROOT).as_posix() if rel == OWNER_PATH: continue - source = module_source(path) - for lineno, name in module_level_binds(source): - name_findings.append(f"{rel}:{lineno} rebinds {name}") - if any(token in source for token in PRESCREEN_TOKENS): - for lineno, value in inline_pair_sites(source): + source = read_text_cached(path) + has_guarded = any(name in source for name in GUARDED_NAMES) + has_prescreen = any(token in source for token in PRESCREEN_TOKENS) + if not has_guarded and not has_prescreen: + continue + tree = parse_python_cached(path) + if has_guarded: + for lineno, name in _module_level_binds_tree(tree): + name_findings.append(f"{rel}:{lineno} rebinds {name}") + if has_prescreen: + for lineno, value in _inline_pair_sites_tree(tree): literal_findings.append(f"{rel}:{lineno} spells out {value!r}") return name_findings, literal_findings diff --git a/tests/architecture/test_legacy_markdown_writer_retirement.py b/tests/architecture/test_legacy_markdown_writer_retirement.py index fd39f1f4a8..4f9e768a2d 100644 --- a/tests/architecture/test_legacy_markdown_writer_retirement.py +++ b/tests/architecture/test_legacy_markdown_writer_retirement.py @@ -8,6 +8,12 @@ from pathlib import Path import subprocess +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + REPOSITORY_ROOT = Path(__file__).resolve().parents[2] PACKAGE_ROOT = REPOSITORY_ROOT / "loopx" @@ -94,9 +100,13 @@ } }; +const retiredModuleName = "handoff_mode_legacy_plan"; for (const relative of request.sources) { const sourcePath = path.resolve(request.root, relative); const text = fs.readFileSync(sourcePath, "utf8"); + if (!text.includes(retiredModuleName) && !request.retired_symbols.some(s => text.includes(s))) { + continue; + } const tree = ts.createSourceFile( relative, text, @@ -140,13 +150,21 @@ def _module_name(path: Path) -> str: return ".".join(("loopx", *parts)) +_PYTHON_PRESCREEN_TOKENS = tuple( + {module.rsplit(".", 1)[-1] for module in RETIRED_MODULES} | RETIRED_PYTHON_SYMBOLS +) + + def _python_offenders() -> list[tuple[str, str, str]]: offenders: list[tuple[str, str, str]] = [] - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): + source = read_text_cached(path) + if not any(tok in source for tok in _PYTHON_PRESCREEN_TOKENS): + continue relative = str(path.relative_to(REPOSITORY_ROOT)) module = _module_name(path) package = module if path.name == "__init__.py" else module.rpartition(".")[0] - tree = ast.parse(path.read_text(encoding="utf-8"), filename=relative) + tree = parse_python_cached(path) for node in ast.walk(tree): if isinstance(node, ast.Import): imported = {alias.name for alias in node.names} diff --git a/tests/architecture/test_model_behavior_actor_result_field_owner.py b/tests/architecture/test_model_behavior_actor_result_field_owner.py index 67d4847e7d..83068f2d06 100644 --- a/tests/architecture/test_model_behavior_actor_result_field_owner.py +++ b/tests/architecture/test_model_behavior_actor_result_field_owner.py @@ -41,6 +41,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.control_plane.testing import ( model_behavior_qualification as owner, onboarding_model_behavior_qualification as consumer, @@ -75,14 +82,7 @@ def _members(node: ast.expr) -> frozenset[str] | None: return None -def _field_literal_sites(source: str) -> list[int]: - """Every collection literal in the source folding to FIELDS, counted once. - - ``frozenset({...})`` is walked as both the call and its inner set; the inner - node is skipped so one restatement is one site, not two. - """ - - tree = ast.parse(source) +def _field_literal_sites_tree(tree: ast.Module) -> list[int]: wrapped = { id(node.args[0]) for node in ast.walk(tree) @@ -98,6 +98,16 @@ def _field_literal_sites(source: str) -> list[int]: ] +def _field_literal_sites(source: str) -> list[int]: + """Every collection literal in the source folding to FIELDS, counted once. + + ``frozenset({...})`` is walked as both the call and its inner set; the inner + node is skipped so one restatement is one site, not two. + """ + + return _field_literal_sites_tree(ast.parse(source)) + + def _binding_sites(source: str, names: tuple[str, ...]) -> list[int]: """Module-level assignments to one of ``names`` whose value folds to FIELDS. @@ -147,11 +157,14 @@ def _package_same_value_candidates() -> dict[str, list[int]]: """Advisory whole-package census: report same-value sites for review only.""" candidates: dict[str, list[int]] = {} - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): relative = path.relative_to(REPO_ROOT).as_posix() if relative == OWNER_PATH: continue - sites = _field_literal_sites(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and "actor_ref" not in source: + continue + sites = _field_literal_sites_tree(parse_python_cached(path)) if sites: candidates[relative] = sites return candidates diff --git a/tests/architecture/test_nokv_qualified_pin_single_owner.py b/tests/architecture/test_nokv_qualified_pin_single_owner.py index c9557e32dd..064422b21b 100644 --- a/tests/architecture/test_nokv_qualified_pin_single_owner.py +++ b/tests/architecture/test_nokv_qualified_pin_single_owner.py @@ -30,6 +30,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] OWNER_MODULE = "loopx/control_plane/coordination/nokv_qualification.py" OWNED_NAMES = ("QUALIFIED_NOKV_SDK_VERSION", "QUALIFIED_NOKV_API_VERSION") @@ -50,34 +57,40 @@ def _rel(path: pathlib.PurePath) -> str: def _product_sources() -> list[pathlib.Path]: - return sorted( - path - for path in (REPO_ROOT / "loopx").rglob("*.py") - if "__pycache__" not in path.parts - ) + return list(iter_python_sources(REPO_ROOT / "loopx")) -def _assigned_names(node: ast.stmt) -> tuple[list[str], str]: +def _assigned_name_targets(node: ast.AST) -> tuple[list[str], ast.expr | None]: if isinstance(node, ast.Assign): return ( [target.id for target in node.targets if isinstance(target, ast.Name)], - ast.unparse(node.value), + node.value, ) if ( isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value ): - return ([node.target.id], ast.unparse(node.value)) - return ([], "") + return ([node.target.id], node.value) + return ([], None) + + +def _assigned_names(node: ast.stmt) -> tuple[list[str], str]: + names, value_node = _assigned_name_targets(node) + if not names or value_node is None: + return ([], "") + return (names, ast.unparse(value_node)) def _module_level_definitions() -> dict[str, list[str]]: found: dict[str, list[str]] = {name: [] for name in OWNED_NAMES} for path in _product_sources(): - tree = ast.parse(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if source.isascii() and not any(name in source for name in OWNED_NAMES): + continue + tree = parse_python_cached(path) for node in tree.body: - names, _ = _assigned_names(node) + names, _ = _assigned_name_targets(node) for name in names: if name in found: found[name].append(_rel(path.relative_to(REPO_ROOT))) @@ -89,15 +102,20 @@ def _any_depth_definitions() -> list[tuple[str, int, str]]: hits: list[tuple[str, int, str]] = [] for path in _product_sources(): - tree = ast.parse(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if source.isascii() and not any(name in source for name in OWNED_NAMES): + continue + tree = parse_python_cached(path) + rel = _rel(path.relative_to(REPO_ROOT)) for node in ast.walk(tree): - names, value = _assigned_names(node) - rel = _rel(path.relative_to(REPO_ROOT)) - hits.extend( - (rel, node.lineno, f"{name} = {value}") - for name in names - if name in OWNED_NAMES - ) + names, value_node = _assigned_name_targets(node) + matched = [name for name in names if name in OWNED_NAMES] + if matched and value_node is not None: + value = ast.unparse(value_node) + hits.extend( + (rel, node.lineno, f"{name} = {value}") + for name in matched + ) return hits @@ -109,8 +127,13 @@ def _sdk_literal_sites(value: object) -> list[str]: """ sites: set[str] = set() + str_value = value if isinstance(value, str) and value else None for path in _product_sources(): - tree = ast.parse(path.read_text(encoding="utf-8")) + if str_value is not None: + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and str_value not in source: + continue + tree = parse_python_cached(path) for node in ast.walk(tree): if isinstance(node, ast.Constant) and node.value == value: sites.add(_rel(path.relative_to(REPO_ROOT))) diff --git a/tests/architecture/test_posix_flag_portability.py b/tests/architecture/test_posix_flag_portability.py index 7b42b11b61..1c01cb537f 100644 --- a/tests/architecture/test_posix_flag_portability.py +++ b/tests/architecture/test_posix_flag_portability.py @@ -27,6 +27,12 @@ from pathlib import Path from typing import Any +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + REPO_ROOT = Path(__file__).resolve().parents[2] LOOPX_ROOT = REPO_ROOT / "loopx" CEILINGS_FIXTURE = Path(__file__).with_name("posix_flag_ceilings.json") @@ -35,9 +41,8 @@ _COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$") -def bare_flag_uses(source: str) -> list[tuple[int, str]]: - """Every direct `os.` or `from os import ` in one module.""" - tree = ast.parse(source) +def _bare_flag_uses_tree(tree: ast.Module) -> list[tuple[int, str]]: + """Every direct `os.` or `from os import ` in a parsed module.""" aliases = { alias.asname or alias.name for node in ast.walk(tree) @@ -63,11 +68,19 @@ def bare_flag_uses(source: str) -> list[tuple[int, str]]: return sorted(uses) +def bare_flag_uses(source: str) -> list[tuple[int, str]]: + """Every direct `os.` or `from os import ` in one module.""" + return _bare_flag_uses_tree(ast.parse(source)) + + def observed_ceiling(loopx_root: Path | None = None) -> dict[str, list[tuple[int, str]]]: root = loopx_root or LOOPX_ROOT observed: dict[str, list[tuple[int, str]]] = {} - for path in sorted(root.rglob("*.py")): - uses = bare_flag_uses(path.read_text(encoding="utf-8")) + for path in iter_python_sources(root): + source = read_text_cached(path) + if source.isascii() and not any(flag in source for flag in POSIX_ONLY_FLAGS): + continue + uses = _bare_flag_uses_tree(parse_python_cached(path)) if uses: observed[path.relative_to(REPO_ROOT).as_posix()] = uses return observed diff --git a/tests/architecture/test_progress_review_pending_reason_owner.py b/tests/architecture/test_progress_review_pending_reason_owner.py index bd2cb515f0..51770c00b0 100644 --- a/tests/architecture/test_progress_review_pending_reason_owner.py +++ b/tests/architecture/test_progress_review_pending_reason_owner.py @@ -23,6 +23,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.progress_review import receipt from loopx.control_plane.work_items import ( external_progress_review, @@ -36,9 +43,7 @@ REASON_VALUE = "pending_evaluation" -def reason_assignments(source: str) -> list[str]: - """Names bound to the pending-reason literal anywhere in a module.""" - tree = ast.parse(source) +def _reason_assignments_tree(tree: ast.Module) -> list[str]: held: list[str] = [] for node in ast.walk(tree): if isinstance(node, (ast.Assign, ast.AnnAssign)): @@ -59,11 +64,19 @@ def reason_assignments(source: str) -> list[str]: return held +def reason_assignments(source: str) -> list[str]: + """Names bound to the pending-reason literal anywhere in a module.""" + return _reason_assignments_tree(ast.parse(source)) + + def modules_holding_the_reason() -> list[str]: holders: list[str] = [] - for path in sorted(REPO_ROOT.glob("loopx/**/*.py")): + for path in iter_python_sources(REPO_ROOT / "loopx"): try: - held = reason_assignments(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and REASON_VALUE not in source: + continue + held = _reason_assignments_tree(parse_python_cached(path)) except (SyntaxError, UnicodeDecodeError): # pragma: no cover - guarded tree continue if held: diff --git a/tests/architecture/test_progress_review_signal_owner.py b/tests/architecture/test_progress_review_signal_owner.py index ace533f7af..2cff75cb45 100644 --- a/tests/architecture/test_progress_review_signal_owner.py +++ b/tests/architecture/test_progress_review_signal_owner.py @@ -23,6 +23,13 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities import configuration_ui from loopx.capabilities.progress_review import policy as capability_policy from loopx.capabilities.progress_review import receipt @@ -69,7 +76,7 @@ def literal_value(node: ast.AST) -> tuple[str, ...] | None: def signal_rows(source: str, name: str) -> list[dict[str, object]]: - if "noul" not in source: + if "noul" not in source and not may_split_or_escape_literal(source): return [] tree = ast.parse(source) return [ @@ -81,15 +88,20 @@ def signal_rows(source: str, name: str) -> list[dict[str, object]]: def collect(root: pathlib.Path) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] - for path in sorted((root / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(root / "loopx"): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue + if "noul" not in source and not may_split_or_escape_literal(source): + continue + tree = parse_python_cached(path) relative = path.relative_to(root).as_posix() - rows.extend(signal_rows(source, relative)) + rows.extend( + {"file": relative, "line": node.lineno, "kind": "signal_vocabulary"} + for node in ast.walk(tree) + if literal_value(node) == SIGNAL_VALUE + ) return rows @@ -120,9 +132,12 @@ def offenders( def modules_importing_the_owner() -> set[str]: importing: set[str] = set() - for path in sorted((REPO_ROOT / "loopx").rglob("*.py")): + for path in iter_python_sources(REPO_ROOT / "loopx"): try: - tree = ast.parse(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if source.isascii() and OWNER_NAME not in source: + continue + tree = parse_python_cached(path) except (OSError, UnicodeDecodeError, SyntaxError): continue for node in ast.walk(tree): @@ -141,7 +156,7 @@ def referenced(tree: ast.Module, name: str) -> bool: def parse(module: ModuleType) -> ast.Module: path = pathlib.Path(str(module.__file__)).resolve() - return ast.parse(path.read_text(encoding="utf-8")) + return parse_python_cached(path) def test_no_other_module_states_the_signal_set() -> None: diff --git a/tests/architecture/test_progress_scope_owner.py b/tests/architecture/test_progress_scope_owner.py index cae2ce5cc4..1e89009ef4 100644 --- a/tests/architecture/test_progress_scope_owner.py +++ b/tests/architecture/test_progress_scope_owner.py @@ -35,6 +35,12 @@ from loopx.control_plane import progress_scope as owner from loopx.control_plane.agents import agent_lane_recommendation from loopx.control_plane.status import run_projection +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) REPOSITORY_ROOT = pathlib.Path(__file__).resolve().parents[2] PACKAGE_ROOT = REPOSITORY_ROOT / "loopx" @@ -93,16 +99,12 @@ def _label(path: pathlib.Path, tree: pathlib.Path) -> str: def _python_sources(tree: pathlib.Path) -> list[pathlib.Path]: - return sorted( - path - for path in (tree / "loopx").rglob("*.py") - if "__pycache__" not in path.parts - ) + return list(iter_python_sources(tree / "loopx")) -def _module_level_bound_names(source: str) -> list[str]: +def _module_level_bound_names_tree(tree: ast.Module) -> list[str]: names: list[str] = [] - for node in ast.parse(source).body: + for node in tree.body: if isinstance(node, ast.Assign): names.extend( target.id for target in node.targets if isinstance(target, ast.Name) @@ -112,13 +114,20 @@ def _module_level_bound_names(source: str) -> list[str]: return names +def _module_level_bound_names(source: str) -> list[str]: + return _module_level_bound_names_tree(ast.parse(source)) + + def declaring_modules(tree: pathlib.Path) -> list[str]: """Every module under ``tree`` that re-binds the guarded name at module level.""" - return sorted( - _label(path, tree) - for path in _python_sources(tree) - if GUARDED_NAME in _module_level_bound_names(path.read_text(encoding="utf-8")) - ) + declared: list[str] = [] + for path in _python_sources(tree): + source = read_text_cached(path) + if source.isascii() and GUARDED_NAME not in source: + continue + if GUARDED_NAME in _module_level_bound_names_tree(parse_python_cached(path)): + declared.append(_label(path, tree)) + return sorted(declared) def _scope_literal_nodes(node: ast.expr | None) -> list[ast.Constant]: @@ -174,8 +183,12 @@ def inline_value_sites(tree: pathlib.Path) -> dict[str, int]: """Where the value is written out again in a position that consumes it as a scope.""" sites: dict[str, int] = {} for path in _python_sources(tree): - source = path.read_text(encoding="utf-8") - hits = _value_positions(ast.parse(source), source) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and ( + SCOPE_VALUE not in source or "progress" not in source + ): + continue + hits = _value_positions(parse_python_cached(path), source) if hits: sites[_label(path, tree)] = len(hits) return sites diff --git a/tests/architecture/test_public_safe_slug_owner.py b/tests/architecture/test_public_safe_slug_owner.py index 7975e60c6f..3a78de8fc0 100644 --- a/tests/architecture/test_public_safe_slug_owner.py +++ b/tests/architecture/test_public_safe_slug_owner.py @@ -26,6 +26,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + from loopx import public_safe_text from loopx.capabilities.issue_fix import periodic_report as issue_fix_report from loopx.capabilities.periodic_report import ( @@ -174,10 +180,7 @@ def regex_calls(tree: ast.Module) -> list[ast.Call]: return calls -def shape_rows(source: str, name: str) -> list[dict[str, object]]: - if not any(token in source for token in PRESCREEN_TOKENS): - return [] - tree = ast.parse(source) +def _shape_rows_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_level_string_constants(tree) rows: list[dict[str, object]] = [] for node in regex_calls(tree): @@ -191,12 +194,13 @@ def shape_rows(source: str, name: str) -> list[dict[str, object]]: return rows -def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: +def shape_rows(source: str, name: str) -> list[dict[str, object]]: if not any(token in source for token in PRESCREEN_TOKENS): return [] - if "[a-z" not in source: - return [] - tree = ast.parse(source) + return _shape_rows_tree(ast.parse(source), name) + + +def _unfoldable_rows_tree(tree: ast.Module, name: str) -> list[dict[str, object]]: constants = module_level_string_constants(tree) return [ {"file": name, "line": node.lineno, "kind": "unfoldable_regex"} @@ -206,17 +210,23 @@ def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: ] +def unfoldable_rows(source: str, name: str) -> list[dict[str, object]]: + if not any(token in source for token in PRESCREEN_TOKENS): + return [] + return _unfoldable_rows_tree(ast.parse(source), name) + + def collect(root: pathlib.Path) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] - for path in sorted((root / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(root / "loopx"): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue + if not any(token in source for token in PRESCREEN_TOKENS): + continue relative = path.relative_to(root).as_posix() - rows.extend(shape_rows(source, relative)) + rows.extend(_shape_rows_tree(parse_python_cached(path), relative)) return rows @@ -290,7 +300,7 @@ def referenced(tree: ast.Module, name: str) -> bool: def parse(module: ModuleType) -> ast.Module: path = pathlib.Path(str(module.__file__)).resolve() - return ast.parse(path.read_text(encoding="utf-8")) + return parse_python_cached(path) # -------------------------------------------------------------------------- @@ -304,9 +314,12 @@ def test_no_other_module_compiles_the_slug_shape() -> None: def modules_importing_the_owner() -> set[str]: importing: set[str] = set() - for path in sorted((REPO_ROOT / "loopx").rglob("*.py")): + for path in iter_python_sources(REPO_ROOT / "loopx"): try: - tree = ast.parse(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if source.isascii() and "PUBLIC_SAFE_SLUG_PATTERN" not in source: + continue + tree = parse_python_cached(path) except (OSError, UnicodeDecodeError, SyntaxError): continue for node in ast.walk(tree): @@ -339,14 +352,14 @@ def test_owner_states_the_shape_as_the_recorded_literal() -> None: def test_no_module_hides_an_unfoldable_slug_construction() -> None: rows: list[dict[str, object]] = [] - for path in sorted((REPO_ROOT / "loopx").rglob("*.py")): - if "__pycache__" in path.parts: - continue + for path in iter_python_sources(REPO_ROOT / "loopx"): try: - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) except (OSError, UnicodeDecodeError): continue - rows.extend(unfoldable_rows(source, path.relative_to(REPO_ROOT).as_posix())) + if not any(token in source for token in PRESCREEN_TOKENS) or "[a-z" not in source: + continue + rows.extend(_unfoldable_rows_tree(parse_python_cached(path), path.relative_to(REPO_ROOT).as_posix())) assert unfoldable_offender_rows(rows) == [] diff --git a/tests/architecture/test_repo_ast_cache.py b/tests/architecture/test_repo_ast_cache.py new file mode 100644 index 0000000000..015510ef23 --- /dev/null +++ b/tests/architecture/test_repo_ast_cache.py @@ -0,0 +1,109 @@ +"""Regression tests for ``tests.architecture._repo_ast_cache``.""" + +from __future__ import annotations + +import ast +import os +from pathlib import Path + +import pytest + +from tests.architecture._repo_ast_cache import ( + cache_info, + check_python_syntax_cached, + clear_caches, + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + + +def test_cache_invalidates_when_file_stat_changes(tmp_path: Path) -> None: + target = tmp_path / "sample.py" + target.write_text("VALUE = 'first'\n", encoding="utf-8") + + first_text = read_text_cached(target) + first_tree = parse_python_cached(target) + assert first_text == "VALUE = 'first'\n" + assert parse_python_cached(target) is first_tree + + # Ensure both size and mtime_ns change deterministically. + target.write_text("VALUE = 'second_longer'\n", encoding="utf-8") + stat = target.stat() + os.utime(target, ns=(stat.st_atime_ns, stat.st_mtime_ns + 1_000_000)) + + assert read_text_cached(target) == "VALUE = 'second_longer'\n" + second_tree = parse_python_cached(target) + assert second_tree is not first_tree + assert isinstance(second_tree.body[0], ast.Assign) + assert isinstance(second_tree.body[0].value, ast.Constant) + assert second_tree.body[0].value.value == "second_longer" + + +def test_parse_python_cached_does_not_suppress_or_cache_syntax_errors( + tmp_path: Path, +) -> None: + broken = tmp_path / "broken.py" + broken.write_text("def broken(:\n", encoding="utf-8") + + with pytest.raises(SyntaxError): + parse_python_cached(broken) + + broken.write_text("VALID = 1\n", encoding="utf-8") + stat = broken.stat() + os.utime(broken, ns=(stat.st_atime_ns, stat.st_mtime_ns + 1_000_000)) + + tree = parse_python_cached(broken) + assert len(tree.body) == 1 + check_python_syntax_cached(broken) + before_hits = cache_info()["syntax"].hits + check_python_syntax_cached(broken) + assert cache_info()["syntax"].hits == before_hits + 1 + + +def test_iter_python_sources_excludes_pycache_and_sees_new_tmp_files( + tmp_path: Path, +) -> None: + (tmp_path / "__pycache__").mkdir() + (tmp_path / "__pycache__" / "ignored.py").write_text("X = 1\n", encoding="utf-8") + first = tmp_path / "a.py" + first.write_text("A = 1\n", encoding="utf-8") + + assert iter_python_sources(tmp_path) == (first,) + + second = tmp_path / "b.py" + second.write_text("B = 2\n", encoding="utf-8") + assert iter_python_sources(tmp_path) == (first, second) + + clear_caches() + + +@pytest.mark.parametrize( + ("source", "include_plus", "expected"), + [ + ('X = "plain"\n', False, False), + ('X = ""\nY = """docstring\n"quoted"\n"""\n', False, False), + ('# comment with "unmatched\nX = "ok"\n', False, False), + ('X = "periodic_" "report_trigger_decision_v0"\n', False, True), + ('X = r"^[0-9a-f]{6" r"4}$"\n', False, True), + ('X = (\n "sha"\n # wrapped across lines\n "256:"\n)\n', False, True), + ('X = "a""b"\n', False, True), + ('X = "a"\'b\'\n', False, True), + ('X = "sha\\x3256:"\n', False, True), + ('X = "a\\12b"\n', False, True), + ('X = "a" \\\n "b"\n', False, True), + ('X = "a" + y\n', False, False), + ('X = "a" + y\n', True, True), + ('X = PREFIX + "256:"\n', True, True), + ('X = f"sha{suffix}"\n', True, True), + ('X = "a + b"\n', True, False), + ], +) +def test_may_split_or_escape_literal_detects_concat_and_escapes( + source: str, include_plus: bool, expected: bool +) -> None: + assert may_split_or_escape_literal(source, include_plus=include_plus) is expected + before_hits = cache_info()["split_literal"].hits + assert may_split_or_escape_literal(source, include_plus=include_plus) is expected + assert cache_info()["split_literal"].hits == before_hits + 1 diff --git a/tests/architecture/test_repository_identity_safe_id_owner.py b/tests/architecture/test_repository_identity_safe_id_owner.py index f37b145452..f67fcfdeb3 100644 --- a/tests/architecture/test_repository_identity_safe_id_owner.py +++ b/tests/architecture/test_repository_identity_safe_id_owner.py @@ -31,6 +31,12 @@ from loopx import repository_identity as owner from loopx.control_plane.projects import registry as registry_mod from loopx.presentation import static_site as static_site_mod +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] PACKAGE_ROOT = REPO_ROOT / "loopx" @@ -41,15 +47,7 @@ STATIC_SITE_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$" -def _compiled_pattern_sites(source: str, pattern: str) -> list[int]: - """Every ``re.compile()`` call in the source whose pattern matches. - - Keys on the pattern literal, so a restatement under any name (or with extra - flags) is still one site; a bare pattern string that is never compiled is not - a compiled-regex restatement and is left alone. - """ - - tree = ast.parse(source) +def _compiled_pattern_sites_tree(tree: ast.Module, pattern: str) -> list[int]: sites: list[int] = [] for node in ast.walk(tree): if not isinstance(node, ast.Call): @@ -66,14 +64,28 @@ def _compiled_pattern_sites(source: str, pattern: str) -> list[int]: return sites +def _compiled_pattern_sites(source: str, pattern: str) -> list[int]: + """Every ``re.compile()`` call in the source whose pattern matches. + + Keys on the pattern literal, so a restatement under any name (or with extra + flags) is still one site; a bare pattern string that is never compiled is not + a compiled-regex restatement and is left alone. + """ + + return _compiled_pattern_sites_tree(ast.parse(source), pattern) + + @pytest.fixture(scope="module") def tree_offenders() -> dict[str, list[int]]: offenders: dict[str, list[int]] = {} - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): relative = path.relative_to(REPO_ROOT).as_posix() if relative == OWNER_PATH: continue - sites = _compiled_pattern_sites(path.read_text(encoding="utf-8"), PATTERN) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and PATTERN not in source: + continue + sites = _compiled_pattern_sites_tree(parse_python_cached(path), PATTERN) if sites: offenders[relative] = sites return offenders diff --git a/tests/architecture/test_reward_memory_field_vocabulary_owner.py b/tests/architecture/test_reward_memory_field_vocabulary_owner.py index c2159890ea..014c7e73a3 100644 --- a/tests/architecture/test_reward_memory_field_vocabulary_owner.py +++ b/tests/architecture/test_reward_memory_field_vocabulary_owner.py @@ -54,6 +54,14 @@ import pytest +from tests.architecture._repo_ast_cache import ( + check_python_syntax_cached, + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.explore import todo_branch_plan, worker_branch_plan from loopx.capabilities.issue_fix import github_public, pr_description from loopx.capabilities.issue_fix import repository_commit_evidence as commit_evidence @@ -171,10 +179,9 @@ def folded_value(node: ast.expr) -> tuple[str, object] | None: return None -def _analyse(source: str): - """Derive the consumed sites once; syntax trees remain temporary.""" +def _analyse_tree(tree: ast.Module): + """Derive the consumed sites from a parsed AST.""" - tree = ast.parse(source) bindings = [] for node in tree.body: if isinstance(node, ast.Assign): @@ -190,6 +197,12 @@ def _analyse(source: str): return bindings, members, strings +def _analyse(source: str): + """Derive the consumed sites once; syntax trees remain temporary.""" + + return _analyse_tree(ast.parse(source)) + + def _binding_lines(bindings, name, kind, payload): return [line for line, names, value in bindings if name in names and value == (kind, payload)] @@ -217,6 +230,21 @@ def body_literal_sites(source: str, body: str) -> list[int]: return _sites(_analyse(source), "", "body", body)[1] +_REWARD_SCAN_TOKENS = ( + "actor_role", + "confidence", + "source_freshness", + "surface_id", + "A-Za-z0-9_", + "_SOURCE_FIELDS", + "_REASONING_FIELDS", + "_GUARD_FIELDS", + "_SCOPE_FIELDS", + "TOKEN_PATTERN", + "_REPO_PATTERN", +) + + def _repository_scan(): queries = [(name, "members", spec[0], spec[1], {}) for name, spec in SET_DECISIONS.items()] @@ -224,9 +252,17 @@ def _repository_scan(): for name, spec in PATTERN_DECISIONS.items()] bindings = {name: [] for name, *_ in queries} sites = {name: {} for name, *_ in queries} - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): + source = read_text_cached(path) + if ( + not may_split_or_escape_literal(source) + and not any(tok in source for tok in _REWARD_SCAN_TOKENS) + ): + # Validate syntax without pinning full-tree ASTs into the shared cache. + check_python_syntax_cached(path) + continue rel = path.relative_to(REPO_ROOT).as_posix() - analysis = _analyse(path.read_text(encoding="utf-8")) + analysis = _analyse_tree(parse_python_cached(path)) for name, kind, payload, owner_path, _declared in queries: if rel == owner_path: continue diff --git a/tests/architecture/test_semantic_development_probe.py b/tests/architecture/test_semantic_development_probe.py index 02a78232ee..b68be9f41d 100644 --- a/tests/architecture/test_semantic_development_probe.py +++ b/tests/architecture/test_semantic_development_probe.py @@ -4,6 +4,7 @@ import os from pathlib import Path +import shutil import subprocess import sys @@ -23,33 +24,41 @@ def _write(root: Path, relative: str, text: str) -> None: path.write_text(text, encoding="utf-8") -@pytest.fixture -def repository(tmp_path: Path) -> Path: - subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) +@pytest.fixture(scope="module") +def _base_probe_repo(tmp_path_factory: pytest.TempPathFactory) -> Path: + root = tmp_path_factory.mktemp("dev-probe-base") + subprocess.run(["git", "init", "-q", str(root)], check=True) subprocess.run( - ["git", "-C", str(tmp_path), "config", "user.email", "fixture@example.com"], + ["git", "-C", str(root), "config", "user.email", "fixture@example.com"], check=True, ) subprocess.run( - ["git", "-C", str(tmp_path), "config", "user.name", "Fixture"], + ["git", "-C", str(root), "config", "user.name", "Fixture"], check=True, ) _write( - tmp_path, + root, "loopx/a.py", 'from typing import Literal\nMode = Literal["fast", "slow"]\n', ) _write( - tmp_path, + root, "loopx/semantics/vocabulary_v0.json", '{"vocabularies":{"mode":{"values":["fast","slow","safe"],' '"owners":{"python":"loopx/owner.py::Mode"}}}}\n', ) - subprocess.run(["git", "-C", str(tmp_path), "add", "loopx"], check=True) + subprocess.run(["git", "-C", str(root), "add", "loopx"], check=True) subprocess.run( - ["git", "-C", str(tmp_path), "commit", "-qm", "baseline"], check=True + ["git", "-C", str(root), "commit", "-qm", "baseline"], check=True ) - return tmp_path + return root + + +@pytest.fixture +def repository(tmp_path: Path, _base_probe_repo: Path) -> Path: + target = tmp_path / "repo" + shutil.copytree(_base_probe_repo, target, copy_function=shutil.copyfile) + return target def _registry() -> dict: diff --git a/tests/architecture/test_semantic_field_use.py b/tests/architecture/test_semantic_field_use.py index 3b3d7eaa17..fc9a4f1664 100644 --- a/tests/architecture/test_semantic_field_use.py +++ b/tests/architecture/test_semantic_field_use.py @@ -18,6 +18,7 @@ field_use_summary, lexical_module_count, python_module_scan, + python_module_scan_with_mention, scan_field_uses, ) from loopx.semantics.inventory import SourceFile @@ -411,3 +412,19 @@ def test_every_equivalent_writing_of_one_access_is_still_one_module_of_work() -> assert len(uses) == 1, uses assert uses[0].reads and uses[0].writes and uses[0].binds and uses[0].unresolved assert uses[0].role == "reader" and uses[0].in_migration_surface + + +def test_python_module_scan_with_mention_preserves_dynamic_sites_and_literal_mentions() -> None: + forms, dyn, mentioned = python_module_scan_with_mention( + ast.parse(r'payload.get(k); v = "\x65ffective_action"'), + frozenset(), + "effective_action", + ) + assert forms == {} and dyn == 1 and mentioned is True + + forms2, dyn2, mentioned2 = python_module_scan_with_mention( + ast.parse("payload.get(k); payload['goal_boundary'] = 1"), + FIELDS, + "effective_action", + ) + assert forms2 == {FIELD: {"subscript_write"}} and dyn2 == 1 and mentioned2 is False diff --git a/tests/architecture/test_semantic_production.py b/tests/architecture/test_semantic_production.py index 6d9e11dedd..988039075e 100644 --- a/tests/architecture/test_semantic_production.py +++ b/tests/architecture/test_semantic_production.py @@ -2,13 +2,18 @@ from __future__ import annotations import ast +import json +import os +from pathlib import Path +import subprocess +import time + import pytest from loopx.semantics import python_production from loopx.semantics.production import collect_production, validate_production, quota_action_domain from loopx.semantics.python_production import Production from loopx.semantics.inventory import SourceFile -from pathlib import Path ROOT = Path(__file__).resolve().parents[2] SITE = 'loopx/control_plane/quota/probe.py::emit' @@ -390,3 +395,289 @@ def test_typescript_scan_names_the_missing_setup_step(monkeypatch): production.run_typescript_scan(ROOT, source, {}) assert str(raised.value) == production.NPM_DEV_DEPENDENCIES_MISSING assert 'x.mjs' not in str(raised.value), 'parser stderr must never reach public diagnostics' + + +def test_typescript_batch_scan_matches_single_queries_and_preserves_syntax_boundary(): + from loopx.semantics import production + + valid = SourceFile( + 'loopx/control_plane/quota/batch_probe.ts', + '.ts', + 'export function decide(ok: boolean) { const p = {effective_action: ok ? "run" : "wait"}; return p; }\n', + ) + requests = [ + { + 'id': 'lit', + 'mode': 'literal_uses', + 'field': 'effective_action', + 'return_functions': [], + 'paths': [valid.path], + }, + { + 'id': 'prod', + 'mode': 'production', + 'field': 'effective_action', + 'return_functions': [], + 'paths': [valid.path], + }, + { + 'id': 'fu', + 'mode': 'field_uses', + 'fields': ['effective_action'], + 'paths': [valid.path], + }, + ] + batched = production.run_typescript_batch_scan(ROOT, [valid], requests) + assert batched['lit'] == production.run_typescript_scan( + ROOT, [valid], {'mode': 'literal_uses', 'field': 'effective_action', 'return_functions': []}, + ) + assert batched['prod'] == production.run_typescript_scan( + ROOT, [valid], {'mode': 'production', 'field': 'effective_action', 'return_functions': []}, + ) + assert batched['fu'] == production.run_typescript_scan( + ROOT, [valid], {'mode': 'field_uses', 'fields': ['effective_action']}, + ) + + broken = SourceFile('loopx/control_plane/quota/broken_batch.ts', '.ts', 'const s = "secret";\nfunction invalid( {\n') + finish = production.submit_typescript_batch_scan( + ROOT, + [valid, broken], + [{'id': 'broken', 'mode': 'literal_uses', 'field': 'effective_action', 'paths': [broken.path]}], + ) + with pytest.raises(ValueError, match=r'broken_batch\.ts:3: invalid TypeScript source') as err: + finish() + assert 'secret' not in str(err.value) + + +def test_resident_ts_server_times_out_reaps_worker_and_recovers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + from loopx.semantics import production + + scripts_dir = tmp_path / 'scripts' + scripts_dir.mkdir() + pid_file = tmp_path / 'hung.pid' + stub = scripts_dir / 'semantic_production_scan.mjs' + stub.write_text( + 'import fs from "node:fs";\n' + f'fs.writeFileSync({json.dumps(str(pid_file))}, String(process.pid), "utf8");\n' + 'if (process.argv.includes("--server")) {\n' + ' process.stdin.on("data", () => {});\n' + ' setInterval(() => {}, 1000);\n' + '}\n', + encoding='utf-8', + ) + valid = SourceFile( + 'loopx/control_plane/quota/recovery_probe.ts', + '.ts', + 'export function decide(ok: boolean) { return {effective_action: ok ? "run" : "wait"}; }\n', + ) + query = {'mode': 'literal_uses', 'field': 'effective_action', 'return_functions': []} + + production._shutdown_ts_server() + try: + with monkeypatch.context() as scoped: + scoped.setattr(production, '_REPO_SCAN_SCRIPT', stub) + scoped.setattr(production, '_DEFAULT_TS_SCAN_TIMEOUT_SECONDS', 0.25) + started = time.monotonic() + with pytest.raises(subprocess.TimeoutExpired): + production.run_typescript_scan(tmp_path, [valid], query) + elapsed = time.monotonic() - started + assert elapsed < 2.0, f'timeout exceeded bounded deadline: {elapsed:.2f}s' + assert production._TS_SERVER is None + assert not production._TS_SERVER_LOCK.locked() + hung_pid = int(pid_file.read_text(encoding='utf-8')) + with pytest.raises(ProcessLookupError): + os.kill(hung_pid, 0) + + recovered = production.run_typescript_scan(ROOT, [valid], query) + assert recovered and recovered[0]['values'] == ['run', 'wait'] + assert not production._TS_SERVER_LOCK.locked() + finally: + production._shutdown_ts_server() + + +def test_resident_ts_server_rebuilds_after_corrupt_response( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + from loopx.semantics import production + + scripts_dir = tmp_path / 'scripts' + scripts_dir.mkdir() + stub = scripts_dir / 'semantic_production_scan.mjs' + stub.write_text( + 'process.stdout.write("not-json\\n");\n' + 'process.stderr.write("broken worker stderr");\n' + 'process.exit(0);\n', + encoding='utf-8', + ) + valid = SourceFile( + 'loopx/control_plane/quota/corrupt_recovery_probe.ts', + '.ts', + 'export function decide() { return {effective_action: "run"}; }\n', + ) + query = {'mode': 'literal_uses', 'field': 'effective_action', 'return_functions': []} + + production._shutdown_ts_server() + try: + with monkeypatch.context() as scoped: + scoped.setattr(production, '_REPO_SCAN_SCRIPT', stub) + with pytest.raises(ValueError, match='TypeScript production parser failed'): + production.run_typescript_scan(tmp_path, [valid], query) + assert production._TS_SERVER is None + assert not production._TS_SERVER_LOCK.locked() + + recovered = production.run_typescript_scan(ROOT, [valid], query) + assert recovered and recovered[0]['values'] == ['run'] + finally: + production._shutdown_ts_server() + + +def test_resident_ts_server_trickle_stdout_respects_deadline_and_recovers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + from loopx.semantics import production + + scripts_dir = tmp_path / 'scripts' + scripts_dir.mkdir() + pid_file = tmp_path / 'trickle.pid' + stub = scripts_dir / 'semantic_production_scan.mjs' + stub.write_text( + 'import fs from "node:fs";\n' + 'import readline from "node:readline";\n' + f'fs.writeFileSync({json.dumps(str(pid_file))}, String(process.pid), "utf8");\n' + 'const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\n' + 'rl.on("line", (line) => {\n' + ' const req = JSON.parse(line);\n' + ' const slow = req.field === "slow_trickle";\n' + ' process.stdout.write("{\\"ok\\":true,");\n' + ' if (!slow) {\n' + ' setTimeout(() => {\n' + ' process.stdout.write("\\"result\\":[{\\"site\\":\\"s\\",\\"line\\":1,\\"form\\":\\"dict\\",\\"values\\":[\\"run\\"],\\"unresolved\\":false}]}\\n");\n' + ' }, 30);\n' + ' return;\n' + ' }\n' + ' const timer = setInterval(() => { process.stdout.write(" "); }, 25);\n' + ' setTimeout(() => clearInterval(timer), 3000);\n' + '});\n', + encoding='utf-8', + ) + valid = SourceFile( + 'loopx/control_plane/quota/trickle_probe.ts', + '.ts', + 'export function decide() { return {effective_action: "run"}; }\n', + ) + fast_query = {'mode': 'literal_uses', 'field': 'effective_action', 'return_functions': []} + slow_query = {'mode': 'literal_uses', 'field': 'slow_trickle', 'return_functions': []} + + production._shutdown_ts_server() + try: + # Positive case: multi-chunk trickle response completing inside deadline succeeds. + with monkeypatch.context() as scoped: + scoped.setattr(production, '_REPO_SCAN_SCRIPT', stub) + scoped.setattr(production, '_DEFAULT_TS_SCAN_TIMEOUT_SECONDS', 0.4) + ok = production.run_typescript_scan(tmp_path, [valid], fast_query) + assert ok and ok[0]['values'] == ['run'] + + # Negative case 1: continuous trickle without newline fails at deadline and reaps worker. + with monkeypatch.context() as scoped: + scoped.setattr(production, '_REPO_SCAN_SCRIPT', stub) + scoped.setattr(production, '_DEFAULT_TS_SCAN_TIMEOUT_SECONDS', 0.2) + started = time.monotonic() + with pytest.raises(subprocess.TimeoutExpired): + production.run_typescript_scan(tmp_path, [valid], slow_query) + assert time.monotonic() - started < 1.5 + assert production._TS_SERVER is None + assert not production._TS_SERVER_LOCK.locked() + with pytest.raises(ProcessLookupError): + os.kill(int(pid_file.read_text(encoding='utf-8')), 0) + + # Negative case 2: complete readable stdout returning after deadline still fails bounded. + clock = {'now': 0.0} + real_read = os.read + + def advancing_stdout_read(fd: int, n: int) -> bytes: + data = real_read(fd, n) + proc = production._TS_SERVER + if proc is not None and proc.stdout is not None and fd == proc.stdout.fileno() and data: + clock['now'] += 0.40 + return data + + with monkeypatch.context() as scoped: + scoped.setattr(production, '_REPO_SCAN_SCRIPT', stub) + scoped.setattr(production, '_DEFAULT_TS_SCAN_TIMEOUT_SECONDS', 0.25) + scoped.setattr(production.time, 'monotonic', lambda: clock['now']) + scoped.setattr(production.os, 'read', advancing_stdout_read) + with pytest.raises(subprocess.TimeoutExpired): + production.run_typescript_scan(tmp_path, [valid], fast_query) + assert production._TS_SERVER is None + assert not production._TS_SERVER_LOCK.locked() + + recovered = production.run_typescript_scan(ROOT, [valid], fast_query) + assert recovered and recovered[0]['values'] == ['run'] + finally: + production._shutdown_ts_server() + + +def test_resident_ts_server_stderr_drain_respects_deadline_and_recovers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + from loopx.semantics import production + + scripts_dir = tmp_path / 'scripts' + scripts_dir.mkdir() + pid_file = tmp_path / 'stderr.pid' + stub = scripts_dir / 'semantic_production_scan.mjs' + stub.write_text( + 'import fs from "node:fs";\n' + 'import readline from "node:readline";\n' + f'fs.writeFileSync({json.dumps(str(pid_file))}, String(process.pid), "utf8");\n' + 'const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });\n' + 'rl.on("line", () => {\n' + ' process.stderr.write("diagnostic-noise-line\\n");\n' + ' process.stdout.write("{\\"ok\\":true,\\"result\\":[{\\"site\\":\\"s\\",\\"line\\":1,\\"form\\":\\"dict\\",\\"values\\":[\\"run\\"],\\"unresolved\\":false}]}\\n");\n' + '});\n', + encoding='utf-8', + ) + valid = SourceFile( + 'loopx/control_plane/quota/stderr_probe.ts', + '.ts', + 'export function decide() { return {effective_action: "run"}; }\n', + ) + query = {'mode': 'literal_uses', 'field': 'effective_action', 'return_functions': []} + + production._shutdown_ts_server() + try: + # Positive case: small stderr alongside valid response succeeds inside deadline. + with monkeypatch.context() as scoped: + scoped.setattr(production, '_REPO_SCAN_SCRIPT', stub) + scoped.setattr(production, '_DEFAULT_TS_SCAN_TIMEOUT_SECONDS', 0.5) + ok = production.run_typescript_scan(tmp_path, [valid], query) + assert ok and ok[0]['values'] == ['run'] + + # Negative case: final stderr drain crossing shared deadline raises TimeoutExpired and reaps. + clock = {'now': 0.0} + real_read = os.read + + def advancing_stderr_read(fd: int, n: int) -> bytes: + proc = production._TS_SERVER + if proc is not None and proc.stderr is not None and fd == proc.stderr.fileno(): + clock['now'] += 0.65 + return real_read(fd, n) + + with monkeypatch.context() as scoped: + scoped.setattr(production, '_REPO_SCAN_SCRIPT', stub) + scoped.setattr(production, '_DEFAULT_TS_SCAN_TIMEOUT_SECONDS', 0.5) + scoped.setattr(production.time, 'monotonic', lambda: clock['now']) + scoped.setattr(production.os, 'read', advancing_stderr_read) + with pytest.raises(subprocess.TimeoutExpired): + production.run_typescript_scan(tmp_path, [valid], query) + assert production._TS_SERVER is None + assert not production._TS_SERVER_LOCK.locked() + with pytest.raises(ProcessLookupError): + os.kill(int(pid_file.read_text(encoding='utf-8')), 0) + + recovered = production.run_typescript_scan(ROOT, [valid], query) + assert recovered and recovered[0]['values'] == ['run'] + finally: + production._shutdown_ts_server() diff --git a/tests/architecture/test_semantic_quota_run_witness.py b/tests/architecture/test_semantic_quota_run_witness.py index 114adb348c..17a2f02d33 100644 --- a/tests/architecture/test_semantic_quota_run_witness.py +++ b/tests/architecture/test_semantic_quota_run_witness.py @@ -24,21 +24,40 @@ def test_actual_quota_outputs_establish_the_migrated_actions() -> None: assert observed <= set(vocabulary()["values"]) -@pytest.fixture -def isolated_source(tmp_path, monkeypatch): - # The witness executes the classifier's real imports in the isolated tree. - # Copy the owning control plane so a new import cannot strand the mutation. +@pytest.fixture(scope="module") +def _isolated_control_plane_base(tmp_path_factory: pytest.TempPathFactory) -> Path: + root = tmp_path_factory.mktemp("quota-witness-cp") shutil.copytree( - ROOT / "loopx/control_plane", tmp_path / "loopx/control_plane", - ignore=shutil.ignore_patterns("__pycache__", "*.pyc"), + ROOT / "loopx/control_plane", + root / "loopx/control_plane", + ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.py", "*.md"), + copy_function=shutil.copyfile, ) - for name in ["scripts/quota_run_decision_witness.mts", - "tests/control_plane_ts/fixtures/quota_run_decision.json"]: - target = tmp_path / name + for name in [ + "scripts/quota_run_decision_witness.mts", + "tests/control_plane_ts/fixtures/quota_run_decision.json", + ]: + target = root / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / name, target) - monkeypatch.setattr(witness, "__file__", str(tmp_path / "loopx/semantics/production.py")) - return tmp_path + return root + + +@pytest.fixture +def isolated_source(_isolated_control_plane_base: Path, monkeypatch): + # Share the read-only control_plane snapshot per worker and restore the one + # mutated file after each test to avoid repeated multi-hundred-file copies. + policy = _isolated_control_plane_base / "loopx/control_plane/quota/run_decision.ts" + original_policy = policy.read_text(encoding="utf-8") + monkeypatch.setattr( + witness, + "__file__", + str(_isolated_control_plane_base / "loopx/semantics/production.py"), + ) + try: + yield _isolated_control_plane_base + finally: + policy.write_text(original_policy, encoding="utf-8") def test_a_changed_rule_cannot_keep_its_old_production_credit(isolated_source) -> None: diff --git a/tests/architecture/test_settlement_receipt_source_boundaries.py b/tests/architecture/test_settlement_receipt_source_boundaries.py index 8ac56223dd..a61472e36a 100644 --- a/tests/architecture/test_settlement_receipt_source_boundaries.py +++ b/tests/architecture/test_settlement_receipt_source_boundaries.py @@ -8,9 +8,11 @@ from __future__ import annotations +import atexit import hashlib import json import subprocess +import threading from itertools import product from pathlib import Path @@ -55,22 +57,66 @@ def identity(): return SettlementIdentity(**IDENTITY_INPUT).as_dict() +_WITNESS_LOCK = threading.Lock() +_WITNESS_PROC: subprocess.Popen[str] | None = None + + +def _shutdown_witness_proc() -> None: + global _WITNESS_PROC + with _WITNESS_LOCK: + proc = _WITNESS_PROC + _WITNESS_PROC = None + if proc is None: + return + try: + if proc.stdin is not None: + proc.stdin.close() + except OSError: + pass + try: + proc.wait(timeout=1) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=1) + except OSError: + pass + + +atexit.register(_shutdown_witness_proc) + + def _direct(operation, payload): - completed = subprocess.run( - [ - "node", - "--no-warnings", - "--experimental-strip-types", - str(ROOT / "scripts/settlement_receipt_source_witness.mts"), - ], - input=json.dumps({"operation": operation, "input": payload}), - capture_output=True, - text=True, - cwd=ROOT, - timeout=30, - ) - assert completed.returncode == 0, completed.stderr - return json.loads(completed.stdout) + global _WITNESS_PROC + encoded = json.dumps({"operation": operation, "input": payload}) + "\n" + with _WITNESS_LOCK: + if _WITNESS_PROC is None or _WITNESS_PROC.poll() is not None: + _WITNESS_PROC = subprocess.Popen( + [ + "node", + "--no-warnings", + "--experimental-strip-types", + str(ROOT / "scripts/settlement_receipt_source_witness.mts"), + "--server", + ], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + cwd=ROOT, + ) + proc = _WITNESS_PROC + assert proc.stdin is not None and proc.stdout is not None + proc.stdin.write(encoded) + proc.stdin.flush() + line = proc.stdout.readline() + if not line: + stderr = proc.stderr.read() if proc.stderr is not None else "" + _WITNESS_PROC = None + raise AssertionError(f"settlement witness failed: {stderr}") + response = json.loads(line) + assert response.get("ok"), response.get("error") + return response["result"] def _turn(identity, **overrides): diff --git a/tests/architecture/test_source_session_registry_denial.py b/tests/architecture/test_source_session_registry_denial.py index fb9163403b..45a80016ec 100644 --- a/tests/architecture/test_source_session_registry_denial.py +++ b/tests/architecture/test_source_session_registry_denial.py @@ -5,6 +5,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + REPO_ROOT = Path(__file__).resolve().parents[2] DIRECT_LOADER_ALLOWLIST = { @@ -104,10 +110,13 @@ def _assert_recreation_reader_is_location_only(tree: ast.Module) -> None: def test_direct_project_registry_loaders_have_source_session_denial() -> None: callers: set[str] = set() - for path in (REPO_ROOT / "loopx").rglob("*.py"): + for path in iter_python_sources(REPO_ROOT / "loopx"): if path.name == "registry_codec.py": continue - tree = ast.parse(path.read_text(encoding="utf-8")) + source = read_text_cached(path) + if source.isascii() and "load_project_registry" not in source: + continue + tree = parse_python_cached(path) if any( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) diff --git a/tests/architecture/test_state_projection_bullet_pattern_owner.py b/tests/architecture/test_state_projection_bullet_pattern_owner.py index 458fb6d877..5625f00769 100644 --- a/tests/architecture/test_state_projection_bullet_pattern_owner.py +++ b/tests/architecture/test_state_projection_bullet_pattern_owner.py @@ -35,6 +35,12 @@ from loopx import state_projection as consumer from loopx.control_plane.status import active_state_projection as owner from loopx.control_plane.todos.contract import compact_todo_text +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] PACKAGE_ROOT = REPO_ROOT / "loopx" @@ -46,15 +52,7 @@ PRIORITY_PATTERN = r"^\[(P[0-4])\]\s+(.+)$" -def _compiled_pattern_sites(source: str, pattern: str) -> list[int]: - """Every ``re.compile()`` call in the source whose pattern matches. - - Keys on the pattern literal, so a restatement under any name (or with extra - flags) is still one site; a bare pattern string that is never compiled is not - a compiled-regex restatement and is left alone. - """ - - tree = ast.parse(source) +def _compiled_pattern_sites_tree(tree: ast.Module, pattern: str) -> list[int]: sites: list[int] = [] for node in ast.walk(tree): if not isinstance(node, ast.Call): @@ -71,14 +69,28 @@ def _compiled_pattern_sites(source: str, pattern: str) -> list[int]: return sites +def _compiled_pattern_sites(source: str, pattern: str) -> list[int]: + """Every ``re.compile()`` call in the source whose pattern matches. + + Keys on the pattern literal, so a restatement under any name (or with extra + flags) is still one site; a bare pattern string that is never compiled is not + a compiled-regex restatement and is left alone. + """ + + return _compiled_pattern_sites_tree(ast.parse(source), pattern) + + @pytest.fixture(scope="module") def tree_offenders() -> dict[str, list[int]]: offenders: dict[str, list[int]] = {} - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): relative = path.relative_to(REPO_ROOT).as_posix() if relative == OWNER_PATH: continue - sites = _compiled_pattern_sites(path.read_text(encoding="utf-8"), PATTERN) + source = read_text_cached(path) + if not may_split_or_escape_literal(source) and PATTERN not in source: + continue + sites = _compiled_pattern_sites_tree(parse_python_cached(path), PATTERN) if sites: offenders[relative] = sites return offenders diff --git a/tests/architecture/test_wire_schema_version_owners.py b/tests/architecture/test_wire_schema_version_owners.py index e83a7b379d..4945357145 100644 --- a/tests/architecture/test_wire_schema_version_owners.py +++ b/tests/architecture/test_wire_schema_version_owners.py @@ -41,6 +41,14 @@ import pytest +from tests.architecture._repo_ast_cache import ( + check_python_syntax_cached, + iter_python_sources, + may_split_or_escape_literal, + parse_python_cached, + read_text_cached, +) + from loopx.capabilities.issue_fix import cli as issue_fix_cli from loopx.capabilities.issue_fix import metrics_projection, repository_snapshot from loopx.capabilities.issue_fix.cli import register_issue_fix_commands @@ -133,10 +141,9 @@ def module_source(rel_path: str) -> str: return (REPO_ROOT / rel_path).read_text(encoding="utf-8") -def _analyse(source: str, names: frozenset[str]): - """Derive named bindings and string sites without retaining syntax trees.""" +def _analyse_tree(tree: ast.Module, names: frozenset[str]): + """Derive named bindings and string sites from a parsed AST.""" - tree = ast.parse(source) bindings = [] for node in tree.body: if isinstance(node, ast.Assign): @@ -148,6 +155,12 @@ def _analyse(source: str, names: frozenset[str]): return bindings, strings +def _analyse(source: str, names: frozenset[str]): + """Derive named bindings and string sites without retaining syntax trees.""" + + return _analyse_tree(ast.parse(source), names) + + def _binding_lines(bindings, name: str, value: str | None): return [line for line, names, expression in bindings if name in names and (value is None or expression == repr(value))] @@ -184,13 +197,29 @@ def literal_sites(source: str, value: str) -> list[int]: return _sites(_analyse(source, frozenset()), "", value)[1] +_SCHEMA_VALUE_HINTS = ( + "periodic_report_", + "issue_fix_repository_reporting_", + "semantic_preference_provider_", +) + + def _repository_scan(): bindings = {name: [] for name in DECISIONS} sites = {name: {} for name in DECISIONS} names = frozenset(DECISIONS) - for path in sorted(PACKAGE_ROOT.rglob("*.py")): + for path in iter_python_sources(PACKAGE_ROOT): + source = read_text_cached(path) + if ( + not may_split_or_escape_literal(source) + and not any(hint in source for hint in _SCHEMA_VALUE_HINTS) + and not any(k in source for k in names) + ): + # Validate syntax without pinning full-tree ASTs into the shared cache. + check_python_syntax_cached(path) + continue rel = path.relative_to(REPO_ROOT).as_posix() - analysis = _analyse(path.read_text(encoding="utf-8"), names) + analysis = _analyse_tree(parse_python_cached(path), names) for name, (owner_path, _module, value, _consumers) in DECISIONS.items(): if rel == owner_path: continue @@ -435,6 +464,8 @@ def test_the_scan_leaves_a_folded_consumer_alone(label: str, source: str) -> Non @pytest.mark.parametrize("source,owner,named,inline", [ ('REQUEST_SCHEMA = "semantic_preference_provider_request_v0"\n', False, 1, 1), + ('REQUEST_SCHEMA = "semantic_preference_" "provider_request_v0"\n', False, 1, 1), + ('help = (\n "Public-safe semantic_preference_"\n # comment\n "provider_request_v0 here"\n)\n', False, 0, 1), ('help = "Public-safe semantic_preference_provider_request_v0 here"\n', False, 0, 1), ('REQUEST_SCHEMA = "a_different_document_v0"\n', False, 0, 0), ('REQUEST_SCHEMA = "semantic_preference_provider_request_v0"\n', True, 0, 0), diff --git a/tests/architecture/test_work_lane_contract_schema_version_single_owner.py b/tests/architecture/test_work_lane_contract_schema_version_single_owner.py index 4976abd407..487db80b86 100644 --- a/tests/architecture/test_work_lane_contract_schema_version_single_owner.py +++ b/tests/architecture/test_work_lane_contract_schema_version_single_owner.py @@ -15,6 +15,12 @@ import pytest +from tests.architecture._repo_ast_cache import ( + iter_python_sources, + parse_python_cached, + read_text_cached, +) + from loopx.control_plane.quota import task_orchestration from loopx.control_plane.work_items import ( capability_monitor_fallback, @@ -38,17 +44,17 @@ def _modules(root: Path) -> list[Path]: - return sorted(path for path in (root / "loopx").rglob("*.py")) + return list(iter_python_sources(root / "loopx")) def _constant_bindings(root: Path) -> dict[str, list[int]]: """Name every module that binds the constant at module level.""" offenders: dict[str, list[int]] = {} for path in _modules(root): - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) if CONSTANT_NAME not in source: continue - tree = ast.parse(source) + tree = parse_python_cached(path) lines = [ node.lineno for node in tree.body @@ -75,7 +81,7 @@ def _inline_restatements(root: Path) -> dict[str, int]: relative = path.relative_to(root).as_posix() if relative == OWNER_MODULE: continue - source = path.read_text(encoding="utf-8") + source = read_text_cached(path) hits = source.count(f'"{WIRE_VALUE}"') + source.count(f"'{WIRE_VALUE}'") if hits: counts[relative] = hits