From 3c36a85cf09e5608e5cc20aeb21722e611c729b0 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Fri, 27 Nov 2026 22:44:13 -0500 Subject: [PATCH 1/2] Emit clean frontier from --codemod-plan-out and guard hidden-import promotion on script setup and declared layer boundaries --- nominal_refactor_advisor/cli.py | 46 ++-- nominal_refactor_advisor/codemod_runtime.py | 21 ++ nominal_refactor_advisor/declared_root.py | 67 +++++ nominal_refactor_advisor/hidden_imports.py | 273 ++++++++++++++++++-- tests/test_hidden_imports.py | 106 ++++++++ tests/test_refactor_advisor.py | 77 ++++++ 6 files changed, 549 insertions(+), 41 deletions(-) diff --git a/nominal_refactor_advisor/cli.py b/nominal_refactor_advisor/cli.py index 40f45453..6100598c 100644 --- a/nominal_refactor_advisor/cli.py +++ b/nominal_refactor_advisor/cli.py @@ -3725,29 +3725,39 @@ def with_projected_findings( "projected_findings": json_report_object(report), } + def _emit_application_blocked( + self, + synthesis_report: FindingRecipeSynthesisReport, + ) -> int: + print( + json.dumps( + { + **self.unexecuted_payload(), + "application_blocked": True, + "application_block_reason": ( + synthesis_report.application_block_reason + ), + }, + indent=2, + ) + ) + return 1 + def run(self) -> int: synthesis_report = self.finding_plan.report - if not synthesis_report.application_blocked: + if ( + self.execution_request.mode.applies_changes + and synthesis_report.application_blocked + ): + return self._emit_application_blocked(synthesis_report) + if self.plan_out is not None: + exportable = self.finding_plan.exportable_plan_document + if exportable is None: + return self._emit_application_blocked(synthesis_report) write_cli_json_artifact( self.plan_out, - json_report_object(self.finding_plan.document), + json_report_object(exportable), ) - if ( - self.execution_request.mode.applies_changes or self.plan_out is not None - ) and synthesis_report.application_blocked: - print( - json.dumps( - { - **self.unexecuted_payload(), - "application_blocked": True, - "application_block_reason": ( - synthesis_report.application_block_reason - ), - }, - indent=2, - ) - ) - return 1 if not self.execution_request.mode.requested: print(json.dumps(self.unexecuted_payload(), indent=2)) return 0 diff --git a/nominal_refactor_advisor/codemod_runtime.py b/nominal_refactor_advisor/codemod_runtime.py index a7bcf254..7e4f3eee 100644 --- a/nominal_refactor_advisor/codemod_runtime.py +++ b/nominal_refactor_advisor/codemod_runtime.py @@ -3433,6 +3433,27 @@ def application_blocked(self) -> bool: def application_block_reason(self) -> str: return self.report.application_block_reason + @property + def exportable_plan_document(self) -> CodemodPlanDocument | None: + """The unique clean plan document safe to emit for `--codemod-plan-out`. + + Returns the full document when unblocked; otherwise the single clean + trajectory frontier branch or the proved conflict-free candidate batch + when non-empty, leaving `needs_input`, `needs_operation`, and + conflicting sibling findings reported beside it. + """ + + if not self.application_blocked: + return self.document + if ( + len(self.trajectory_frontier.branches) == 1 + and self.trajectory_frontier.branches[0].document.has_recipes + ): + return self.trajectory_frontier.branches[0].document + if self.document.has_recipes: + return self.document + return None + def simulate( self, snapshot: CodemodSourceSnapshot, diff --git a/nominal_refactor_advisor/declared_root.py b/nominal_refactor_advisor/declared_root.py index c70545f0..c1b91e93 100644 --- a/nominal_refactor_advisor/declared_root.py +++ b/nominal_refactor_advisor/declared_root.py @@ -83,6 +83,46 @@ def member( return [f"{attribute}={source}"], [] +@dataclass(frozen=True) +class ForbiddenImportEdge: + """One architectural layer boundary declared in ``[tool.nominal-refactor-advisor]``: + no module under ``source_prefix`` may load any module under ``target_prefix`` + at import time, directly or transitively.""" + + source_prefix: str + target_prefix: str + + def applies_to(self, module_name: str) -> bool: + return _module_matches_prefix(module_name, self.source_prefix) + + def forbids(self, module_name: str) -> bool: + return _module_matches_prefix(module_name, self.target_prefix) + + @classmethod + def from_table_entry( + cls, pyproject: Path, entry: object + ) -> tuple[ForbiddenImportEdge, ...]: + match entry: + case {"from": str(source), "to": str(target)} if source and target: + return (cls(source, target),) + case {"from": str(source), "to": list(targets)} if source and targets: + parsed: list[ForbiddenImportEdge] = [] + for target in targets: + if not isinstance(target, str) or not target: + raise ValueError( + f"{pyproject}: forbidden-imports target must be a non-empty string; got {target!r}" + ) + parsed.append(cls(source, target)) + return tuple(parsed) + raise ValueError( + f"{pyproject}: each forbidden-imports entry requires non-empty `from` and `to`; got {entry!r}" + ) + + +def _module_matches_prefix(module_name: str, prefix: str) -> bool: + return module_name == prefix or module_name.startswith(f"{prefix}.") + + @dataclass(frozen=True) class DerivedSpelling: """A family whose members' spellings the repository's own function derives. @@ -203,6 +243,33 @@ def keyword_binders_for(cls, path: Path) -> frozenset[str]: return cls.declared_names_for(path, "keyword-binders") + @classmethod + def forbidden_imports_for(cls, path: Path) -> tuple[ForbiddenImportEdge, ...]: + """The cross-layer import edges ``path``'s repository forbids at load time:: + + [tool.nominal-refactor-advisor] + forbidden-imports = [ + { from = "pkg.client", to = ["textual", "pkg.widgets"] }, + ] + """ + + pyproject = cls.nearest_pyproject(path) + if pyproject is None: + return () + table_data = ( + _pyproject_table(pyproject) + if ScanCache.active() is not None + else tomllib.loads(pyproject.read_text()) + ) + match table_data: + case {"tool": {"nominal-refactor-advisor": {"forbidden-imports": list(entries)}}}: + return tuple( + edge + for entry in entries + for edge in ForbiddenImportEdge.from_table_entry(pyproject, entry) + ) + return () + @classmethod def declared_names_for(cls, path: Path, key: str) -> frozenset[str]: """The qualified names listed under ``key`` in ``path``'s repository's table.""" diff --git a/nominal_refactor_advisor/hidden_imports.py b/nominal_refactor_advisor/hidden_imports.py index 66bbe2c4..acb3b5f4 100644 --- a/nominal_refactor_advisor/hidden_imports.py +++ b/nominal_refactor_advisor/hidden_imports.py @@ -19,9 +19,11 @@ from collections import defaultdict from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace +from pathlib import Path from nominal_refactor_advisor.ast_tools import ( ParsedModule, + ParsedModuleFact, ParsedModuleSet, ParsedModuleSetFact, ) @@ -35,6 +37,7 @@ node_contains_comment, ) from nominal_refactor_advisor.codemod_source_edits import NominalSourceEdit, SourceSpanEdit +from nominal_refactor_advisor.declared_root import DeclaredRoot, ForbiddenImportEdge from nominal_refactor_advisor.lexical_bindings import LEXICAL_SCOPE_BINDING_AUTHORITY from nominal_refactor_advisor.needed_input import NeededInput, NeedsInput from nominal_refactor_advisor.observation_families import ShapeFamily @@ -249,6 +252,22 @@ def require_static_promotable(self) -> None: raise NotImplementedError + def require_no_module_setup_before_import(self) -> None: + """Refuse promotion when module top-level code (including `if __name__ == "__main__":`) + mutates `sys.path` or `os.environ` before this import: promoting to the top import + block would execute the import before that script setup.""" + + setup = self.module.fact(_ModuleTopLevelSetupChanges).first_before( + self.statement.lineno + ) + if setup is not None: + changed_line, kind = setup + raise NeedsInput( + f"module setup changes `{kind}` at line {changed_line} before this import; " + "at the module's top it would run before that setup", + NeededInput.SOURCE_CHANGE, + ) + def require_promotable(self, scope: RuntimeBindings) -> None: """Raises, naming the input it needs, when moving this import to the module's top would change what a name means.""" @@ -323,6 +342,7 @@ class GuardedImport(HiddenImport): guard: ast.If def require_static_promotable(self) -> None: + self.require_no_module_setup_before_import() if not isinstance(self.statement, ast.ImportFrom) or any(alias.asname for alias in self.statement.names): raise NeedsInput( "only an unaliased guarded `from ... import` moves out of its guard", @@ -397,6 +417,7 @@ def block(self) -> list[ast.stmt]: ) def require_static_promotable(self) -> None: + self.require_no_module_setup_before_import() ancestors = self.ancestors within = ancestors[: ancestors.index(self.function)] if any(isinstance(ancestor, ast.ClassDef) for ancestor in within): @@ -417,16 +438,19 @@ def require_static_promotable(self) -> None: raise NeedsInput("another statement shares its lines", NeededInput.OPERATION) changed = next( ( - node.lineno + (node.lineno, kind) for node in ast.walk(self.function) - if isinstance(node, ast.stmt | ast.expr) and node.lineno < first and changes_import_path(node) + if isinstance(node, ast.stmt | ast.expr) + and node.lineno < first + and (kind := import_runtime_setup_change(node)) is not None ), None, ) if changed is not None: + changed_line, kind = changed raise NeedsInput( - f"it runs after `{self.function.name}` changes `sys.path` at line {changed}; at the " - "module's top it would run before, so the path setup moves to load time first", + f"it runs after `{self.function.name}` changes `{kind}` at line {changed_line}; at the " + "module's top it would run before, so the setup moves to load time first", NeededInput.SOURCE_CHANGE, ) others, imported = LEXICAL_SCOPE_BINDING_AUTHORITY.import_only_bindings(self.function.body) @@ -479,28 +503,166 @@ def source_edits( SYS_PATH_CHANGES = frozenset({"insert", "append", "extend", "remove", "pop", "clear"}) +OS_ENVIRON_CHANGES = frozenset({"setdefault", "update", "pop", "popitem", "clear"}) +OS_ENV_CALLS = frozenset({"putenv", "unsetenv"}) -def changes_import_path(node: ast.AST) -> bool: - """`sys.path.insert(...)` and its kin, or an assignment to `sys.path` or one - of its items: what an import after it may need in order to resolve.""" +def _is_sys_path(expr: ast.expr) -> bool: + return ( + isinstance(expr, ast.Attribute) + and expr.attr == "path" + and isinstance(expr.value, ast.Name) + and expr.value.id == "sys" + ) - def is_sys_path(expr: ast.expr) -> bool: - return ( - isinstance(expr, ast.Attribute) - and expr.attr == "path" - and isinstance(expr.value, ast.Name) - and expr.value.id == "sys" - ) + +def _is_os_environ(expr: ast.expr) -> bool: + return ( + isinstance(expr, ast.Attribute) + and expr.attr == "environ" + and isinstance(expr.value, ast.Name) + and expr.value.id == "os" + ) + + +def import_runtime_setup_change(node: ast.AST) -> str | None: + """Return ``'sys.path'`` or ``'os.environ'`` when ``node`` mutates import-path + or environment state that a later import can depend on.""" match node: - case ast.Call(func=ast.Attribute(value=target, attr=method)) if method in SYS_PATH_CHANGES: - return is_sys_path(target) + case ast.Call(func=ast.Attribute(value=target, attr=method)): + if method in SYS_PATH_CHANGES and _is_sys_path(target): + return "sys.path" + if method in OS_ENVIRON_CHANGES and _is_os_environ(target): + return "os.environ" + if method in OS_ENV_CALLS and isinstance(target, ast.Name) and target.id == "os": + return "os.environ" case ast.Assign(targets=targets): - return any(is_sys_path(t) or isinstance(t, ast.Subscript) and is_sys_path(t.value) for t in targets) + for target in targets: + if _is_sys_path(target) or isinstance(target, ast.Subscript) and _is_sys_path(target.value): + return "sys.path" + if isinstance(target, ast.Subscript) and _is_os_environ(target.value): + return "os.environ" case ast.AugAssign(target=target): - return is_sys_path(target) - return False + if _is_sys_path(target): + return "sys.path" + case ast.Delete(targets=targets): + for target in targets: + if isinstance(target, ast.Subscript) and _is_sys_path(target.value): + return "sys.path" + if isinstance(target, ast.Subscript) and _is_os_environ(target.value): + return "os.environ" + return None + + +def changes_import_path(node: ast.AST) -> bool: + """`sys.path.insert(...)` and its kin, or an assignment to `sys.path` or one + of its items: what an import after it may need in order to resolve.""" + + return import_runtime_setup_change(node) == "sys.path" + + +@dataclass(frozen=True) +class _ModuleTopLevelSetupChanges(ParsedModuleFact): + """Module top-level `sys.path` / `os.environ` mutations (including inside + `if __name__ == "__main__":` and other module-level control blocks), sorted + by line number.""" + + changes: tuple[tuple[int, str], ...] + + @classmethod + def derive(cls, parsed_module: ParsedModule) -> _ModuleTopLevelSetupChanges: + found: list[tuple[int, str]] = [] + + def walk(nodes: Iterable[ast.AST]) -> None: + for node in nodes: + if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef): + continue + if isinstance(node, ast.stmt | ast.expr): + kind = import_runtime_setup_change(node) + if kind is not None: + found.append((node.lineno, kind)) + walk(ast.iter_child_nodes(node)) + + walk(parsed_module.module.body) + found.sort() + return cls(tuple(found)) + + def first_before(self, line: int) -> tuple[int, str] | None: + for changed_line, kind in self.changes: + if changed_line < line: + return (changed_line, kind) + return None + + +def _forbidden_edges_for_paths( + file_paths: Iterable[str], +) -> tuple[ForbiddenImportEdge, ...]: + """Distinct declared forbidden import edges for the repositories containing ``file_paths``.""" + + seen_dirs: set[Path] = set() + seen_pyprojects: set[Path] = set() + edges: list[ForbiddenImportEdge] = [] + seen_edges: set[ForbiddenImportEdge] = set() + for raw_path in file_paths: + parent = Path(raw_path).parent + if parent in seen_dirs: + continue + seen_dirs.add(parent) + pyproject = DeclaredRoot.nearest_pyproject(parent) + if pyproject is None or pyproject in seen_pyprojects: + continue + seen_pyprojects.add(pyproject) + for edge in DeclaredRoot.forbidden_imports_for(pyproject): + if edge not in seen_edges: + seen_edges.add(edge) + edges.append(edge) + return tuple(edges) + + +def _forbidden_edge_violation( + importing_module: str, + targets: frozenset[str], + bindings: tuple[ImportedBinding, ...], + known: frozenset[str], + reachable_from: Callable[[str], frozenset[str]], + top_level_by_module: Mapping[str, tuple[str, ...]], + edges: tuple[ForbiddenImportEdge, ...], +) -> tuple[str, str, ForbiddenImportEdge] | None: + """Return ``(importer, loaded, edge)`` if promoting ``targets`` into + ``importing_module`` would make ``importer`` (``importing_module`` or a + module that already loads it) transitively load ``loaded`` across ``edge``.""" + + if not edges: + return None + affected_importers = {importing_module} + for candidate in known: + if candidate != importing_module and importing_module in reachable_from(candidate): + affected_importers.add(candidate) + active_edges = tuple( + (importer, edge) + for importer in sorted(affected_importers) + for edge in edges + if edge.applies_to(importer) + ) + if not active_edges: + return None + triggered = known_import_targets(targets, known) - {importing_module} + loaded_scanned: set[str] = set(triggered) + for started in triggered: + loaded_scanned.update(reachable_from(started)) + loaded_all: set[str] = set(loaded_scanned) + for binding in bindings: + if binding.module: + loaded_all.add(binding.module) + for loaded_mod in loaded_scanned: + loaded_all.update(top_level_by_module.get(loaded_mod, ())) + ordered_loaded = sorted(loaded_all) + for importer, edge in active_edges: + for loaded_mod in ordered_loaded: + if edge.forbids(loaded_mod): + return importer, loaded_mod, edge + return None class HiddenImportRefusal(ABC): @@ -550,6 +712,26 @@ def need(self) -> NeedsInput: ) +@dataclass(frozen=True) +class CrossesForbiddenImportEdge(HiddenImportRefusal): + """Promoting the import crosses a repository-declared architectural layer + boundary in `[tool.nominal-refactor-advisor] forbidden-imports`.""" + + hidden: HiddenImport + importer: str + loaded: str + edge: ForbiddenImportEdge + + @property + def need(self) -> NeedsInput: + return NeedsInput( + f"{self.hidden.location}: promoting this import makes `{self.importer}` load " + f"`{self.loaded}`, violating forbidden import edge " + f"`{self.edge.source_prefix}` -> `{self.edge.target_prefix}`", + NeededInput.SOURCE_CHANGE, + ) + + @dataclass(frozen=True) class UnpromotableImport(HiddenImportRefusal): """Moving the import would change what a name means, or no operation moves it.""" @@ -620,16 +802,23 @@ class HiddenImportPlan(ParsedModuleSetFact): def derive(cls, modules: ParsedModuleSet) -> HiddenImportPlan: graph = SourceModuleImportGraph.of_modules(modules) known = graph.known_module_names + top_level_by_module = { + module.module_name: top_level_imported_modules(module) + for module in modules + } unscanned_by_module = { - module.module_name: tuple( + module_name: tuple( sorted( imported - for imported in top_level_imported_modules(module) + for imported in imported_modules if imported not in known ) ) - for module in modules + for module_name, imported_modules in top_level_by_module.items() } + forbidden_edges = _forbidden_edges_for_paths( + module.file_path for module in modules + ) accepted: list[HiddenImport] = [] refused: list[HiddenImportRefusal] = [] scopes: dict[str, RuntimeBindings] = {} @@ -667,6 +856,18 @@ def derive(cls, modules: ParsedModuleSet) -> HiddenImportPlan: if bridge is not None: refused.append(UnscannedImportBridge(hidden, *bridge)) continue + violation = _forbidden_edge_violation( + module.module_name, + hidden.targets, + hidden.bindings, + known, + graph.reachable_modules, + top_level_by_module, + forbidden_edges, + ) + if violation is not None: + refused.append(CrossesForbiddenImportEdge(hidden, *violation)) + continue accepted.append(hidden) graph = graph.with_edges(module.module_name, hidden.targets) scope = scope.with_promoted(hidden.bindings) @@ -816,6 +1017,7 @@ class _CompactHiddenImportBaseline: unscanned_by_module: dict[str, tuple[str, ...]] initial_reach_mask: tuple[int | None, ...] referenced_export_members: dict[str, frozenset[str]] + forbidden_edges: tuple[ForbiddenImportEdge, ...] plan: CompactHiddenImportPlan @@ -851,7 +1053,19 @@ def from_projections( if ScanCache.active() is not None: base = _base_hidden_import_plan_slot()[0] known = frozenset(projection.module_name for projection in projections) - if base is not None and known == base.known and len(projections) == len(base.by_path): + forbidden_edges = _forbidden_edges_for_paths( + projection.file_path for projection in projections + ) + top_level_by_module = { + projection.module_name: projection.top_level_imported_modules + for projection in projections + } + if ( + base is not None + and known == base.known + and len(projections) == len(base.by_path) + and forbidden_edges == base.forbidden_edges + ): changed = [ p for p in projections @@ -1137,6 +1351,17 @@ def exports_has(module_name: str, member: str) -> bool: ): unpromotable_count += 1 continue + if forbidden_edges and _forbidden_edge_violation( + mod, + targets, + hidden.bindings, + known, + reachable_from, + top_level_by_module, + forbidden_edges, + ) is not None: + unpromotable_count += 1 + continue accepted_lines.append(hidden.lineno) target_mask = 0 for target in targets: @@ -1193,6 +1418,7 @@ def exports_has(module_name: str, member: str) -> bool: mod: frozenset(members) for mod, members in referenced_exports.items() }, + forbidden_edges=forbidden_edges, plan=built, ) return built @@ -1204,6 +1430,7 @@ def exports_has(module_name: str, member: str) -> bool: "CompactHiddenImport", "CompactHiddenImportModuleSummary", "CompactHiddenImportPlan", + "CrossesForbiddenImportEdge", "GuardedImport", "HiddenImport", "HiddenImportModuleFacts", diff --git a/tests/test_hidden_imports.py b/tests/test_hidden_imports.py index b99af2b5..f1a28ddc 100644 --- a/tests/test_hidden_imports.py +++ b/tests/test_hidden_imports.py @@ -25,6 +25,7 @@ from nominal_refactor_advisor.detectors._hidden_imports import HiddenImportDetector from nominal_refactor_advisor.hidden_imports import ( ClosesCycle, + CrossesForbiddenImportEdge, GuardedImport, HiddenImportPlan, LocalImport, @@ -386,3 +387,108 @@ def test_commented_type_checking_guard_is_not_promoted_to_dead_pass(tmp_path: Pa assert refusal.need.needs == (NeededInput.SOURCE_CHANGE,) assert _findings(tmp_path) == [] + +def test_module_level_script_setup_guards_local_import_promotion(tmp_path: Path): + """Reproduces Toad `tools/qt_drive.py`, `tools/drive_sweep.py`, and + `tools/physical_ui_remote.py`: module-level `sys.path` or `os.environ` + setup (bare or inside `if __name__ == '__main__':`) blocks promoting later + hidden imports above that setup.""" + + _write( + tmp_path, + { + "pkg/target.py": "VALUE = 7\n", + "pkg/env_script.py": ( + "import os\nimport sys\nfrom pathlib import Path\n\n" + "if __name__ == '__main__' and len(sys.argv) > 1:\n" + " os.environ['XDG_CONFIG_HOME'] = str(Path(sys.argv[1]))\n\n\n" + "def run() -> int:\n" + " from pkg.target import VALUE\n\n" + " return VALUE\n" + ), + "pkg/path_script.py": ( + "import sys\nfrom pathlib import Path\n\n" + "if __name__ == '__main__':\n" + " sys.path.insert(0, str(Path(__file__).parent))\n\n\n" + "def run() -> int:\n" + " from pkg.target import VALUE\n\n" + " return VALUE\n" + ), + }, + ) + plan = _plan(tmp_path) + assert plan.accepted == () + assert len(plan.refused) == 2 + reasons = {refusal.hidden.module.module_name: str(refusal.need) for refusal in plan.refused} + assert "changes `os.environ` at line 6" in reasons["pkg.env_script"] + assert "changes `sys.path` at line 5" in reasons["pkg.path_script"] + assert all( + isinstance(refusal, UnpromotableImport) and NeededInput.SOURCE_CHANGE in refusal.need.needs + for refusal in plan.refused + ) + assert _findings(tmp_path) == [] + + +def test_declared_forbidden_import_edges_block_direct_and_transitive_promotion( + tmp_path: Path, +): + """Repository-declared `[tool.nominal-refactor-advisor] forbidden-imports` + keeps architectural layer isolation (e.g. `toad.client` free of `textual` + and `toad.widgets`) even when no import cycle exists.""" + + _write( + tmp_path, + { + "pyproject.toml": ( + "[tool.nominal-refactor-advisor]\n" + "forbidden-imports = [\n" + " { from = 'pkg.client', to = ['textual', 'pkg.widgets'] },\n" + "]\n" + ), + "pkg/client/__init__.py": "", + "pkg/widgets/__init__.py": "", + "pkg/widgets/view.py": "class NativeHistory:\n pass\n", + "pkg/bridge.py": "import textual.app\n\nclass Bridge:\n pass\n", + "pkg/shared.py": ( + "def open_view():\n" + " from pkg.widgets.view import NativeHistory\n\n" + " return NativeHistory()\n" + ), + "pkg/client/entry.py": "import pkg.shared\n", + "pkg/client/details.py": ( + "from __future__ import annotations\n\n" + "from typing import TYPE_CHECKING\n\n" + "if TYPE_CHECKING:\n" + " from pkg.widgets.view import NativeHistory\n\n\n" + "def render(history: NativeHistory) -> object:\n" + " from pkg.bridge import Bridge\n\n" + " return (history, Bridge)\n" + ), + "pkg/app.py": ( + "def make_view():\n" + " from pkg.widgets.view import NativeHistory\n\n" + " return NativeHistory()\n" + ), + }, + ) + plan = _plan(tmp_path) + assert [hidden.module.module_name for hidden in plan.accepted] == ["pkg.app"] + by_mod = { + (refusal.hidden.module.module_name, refusal.hidden.statement.lineno): refusal + for refusal in plan.refused + } + assert len(by_mod) == 3 + for refusal in by_mod.values(): + assert isinstance(refusal, CrossesForbiddenImportEdge) + assert NeededInput.SOURCE_CHANGE in refusal.need.needs + assert by_mod[("pkg.client.details", 6)].loaded == "pkg.widgets.view" + assert by_mod[("pkg.client.details", 10)].loaded == "textual.app" + shared_refusal = by_mod[("pkg.shared", 2)] + assert shared_refusal.importer == "pkg.client.entry" + assert shared_refusal.loaded == "pkg.widgets.view" + findings = _findings(tmp_path) + assert [finding.title for finding in findings] == ["pkg.app hides 1 import(s) that close no cycle"] or [ + finding.summary for finding in findings + ] == ["`pkg.app` hides 1 import(s) that close no cycle."] + + diff --git a/tests/test_refactor_advisor.py b/tests/test_refactor_advisor.py index c6facb94..7fe5ec73 100644 --- a/tests/test_refactor_advisor.py +++ b/tests/test_refactor_advisor.py @@ -2481,6 +2481,83 @@ def test_synthesized_plan_apply_and_export_require_trajectory_proof( assert module_path.read_text(encoding="utf-8") == original_source +def test_synthesized_plan_out_emits_clean_frontier_when_sibling_needs_input( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + """When ready findings form a clean frontier branch alongside a `needs_input` + sibling, `--codemod-plan-out` writes that clean plan document and exits 0 + while still reporting the `needs_input` sibling in stdout.""" + + from nominal_refactor_advisor.cli import CodemodExecutionMode + from nominal_refactor_advisor.cli import CodemodPlanExecutionRequest + from nominal_refactor_advisor.cli import FindingRecipePlanSynthesisExecution + from nominal_refactor_advisor.codemod import FindingRecipePlan + from nominal_refactor_advisor.codemod import FindingRecipeSynthesisRecord + from nominal_refactor_advisor.codemod import FindingRecipeSynthesisReport + from nominal_refactor_advisor.codemod import RejectedRecipeEvaluation + from nominal_refactor_advisor.codemod_workflow import CodemodWorkflowScan + from nominal_refactor_advisor.needed_input import NeededInput + + module_path = tmp_path / "pkg/mod.py" + plan_path = tmp_path / "frontier-plan.json" + _write_module(tmp_path, "pkg/mod.py", "value = 1\n") + candidate = _direct_recipe_candidate( + detector_id="ready_fix", + file_path=module_path.as_posix(), + subject_name="value", + old_source="value = 1", + new_source="value = 2", + before=10, + after=1, + ) + modules = parse_python_modules(tmp_path) + snapshot = CodemodSourceSnapshot.from_modules(modules, ()) + batch_result = _direct_recipe_batch_result((candidate,), snapshot) + needs_input_finding = _finding_spec( + PatternId.FOREIGN_ABSENCE_PROBE, + "Sibling needs input", + "needs explicit owner choice", + "select owner", + "owner unchosen", + ).build("sibling_needs_input", "needs owner pick", ()) + needs_input_record = FindingRecipeSynthesisRecord( + finding=needs_input_finding, + evaluation=RejectedRecipeEvaluation( + evaluation_declaration_type=FindingRecipePlan, + reason="needs owner pick", + needs=(NeededInput.OWNER_PICK,), + ), + ) + records = (*batch_result.records, needs_input_record) + plan = FindingRecipePlan( + document=CodemodPlanDocument(recipes=batch_result.candidate_recipes), + trajectory_frontier=batch_result.trajectory_frontier, + report=FindingRecipeSynthesisReport(records), + ) + execution = FindingRecipePlanSynthesisExecution( + snapshot=snapshot, + execution_request=CodemodPlanExecutionRequest( + sequence=CodemodPlanSequence.from_document(plan.document), + mode=CodemodExecutionMode.NONE, + ), + plan_out=plan_path, + workflow_scan=CodemodWorkflowScan(modules=modules, findings=[]), + plan=plan, + ) + + exit_code = execution.run() + payload = json.loads(capsys.readouterr().out) + + assert exit_code == 0 + assert plan_path.exists() + written_plan = json.loads(plan_path.read_text(encoding="utf-8")) + assert len(written_plan["recipes"]) == 1 + assert written_plan["recipes"][0]["recipe_id"] == candidate.record.recipe_id + assert payload["synthesis_report"]["candidate_count"] == 1 + assert payload["synthesis_report"]["needs_input_count"] == 1 + + def test_semantic_descent_context_does_not_guess_an_authority_claim( tmp_path: Path, ) -> None: From f360456bd8aefb3dac427458f43d453a7d3f0e73 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Fri, 27 Nov 2026 22:45:09 -0500 Subject: [PATCH 2/2] Match parent-package load order in forbidden-imports test --- tests/test_hidden_imports.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_hidden_imports.py b/tests/test_hidden_imports.py index f1a28ddc..a5e1e911 100644 --- a/tests/test_hidden_imports.py +++ b/tests/test_hidden_imports.py @@ -481,11 +481,11 @@ def test_declared_forbidden_import_edges_block_direct_and_transitive_promotion( for refusal in by_mod.values(): assert isinstance(refusal, CrossesForbiddenImportEdge) assert NeededInput.SOURCE_CHANGE in refusal.need.needs - assert by_mod[("pkg.client.details", 6)].loaded == "pkg.widgets.view" + assert by_mod[("pkg.client.details", 6)].loaded == "pkg.widgets" assert by_mod[("pkg.client.details", 10)].loaded == "textual.app" shared_refusal = by_mod[("pkg.shared", 2)] assert shared_refusal.importer == "pkg.client.entry" - assert shared_refusal.loaded == "pkg.widgets.view" + assert shared_refusal.loaded == "pkg.widgets" findings = _findings(tmp_path) assert [finding.title for finding in findings] == ["pkg.app hides 1 import(s) that close no cycle"] or [ finding.summary for finding in findings