smelt-cli 0.2.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. smelt/__init__.py +6 -0
  2. smelt/__main__.py +5 -0
  3. smelt/analysis/__init__.py +45 -0
  4. smelt/analysis/annotations.py +105 -0
  5. smelt/analysis/cache.py +168 -0
  6. smelt/analysis/context.py +147 -0
  7. smelt/analysis/contracts.py +210 -0
  8. smelt/analysis/coverage.py +377 -0
  9. smelt/analysis/definition_blocks.py +569 -0
  10. smelt/analysis/enum_values.py +217 -0
  11. smelt/analysis/errors.py +11 -0
  12. smelt/analysis/exports.py +166 -0
  13. smelt/analysis/files.py +279 -0
  14. smelt/analysis/function_usage.py +123 -0
  15. smelt/analysis/graphs.py +77 -0
  16. smelt/analysis/identity.py +64 -0
  17. smelt/analysis/import_cache.py +98 -0
  18. smelt/analysis/imports.py +452 -0
  19. smelt/analysis/literals.py +17 -0
  20. smelt/analysis/member_state.py +108 -0
  21. smelt/analysis/members.py +975 -0
  22. smelt/analysis/ordering.py +399 -0
  23. smelt/analysis/ordering_rewrite.py +232 -0
  24. smelt/analysis/package_exports.py +58 -0
  25. smelt/analysis/parsing.py +126 -0
  26. smelt/analysis/python_version.py +164 -0
  27. smelt/analysis/retained.py +84 -0
  28. smelt/analysis/syntax.py +109 -0
  29. smelt/analysis/test_awaits.py +91 -0
  30. smelt/analysis/test_cases.py +84 -0
  31. smelt/analysis/test_deadlines.py +90 -0
  32. smelt/analysis/test_outcomes.py +71 -0
  33. smelt/analysis/test_subprocesses.py +107 -0
  34. smelt/analysis/test_syntax.py +1425 -0
  35. smelt/analysis/test_timing.py +76 -0
  36. smelt/analysis/type_dispatch.py +193 -0
  37. smelt/analysis/workspace.py +146 -0
  38. smelt/cli/__init__.py +3 -0
  39. smelt/cli/app.py +300 -0
  40. smelt/cli/commands/__init__.py +62 -0
  41. smelt/cli/commands/adopt.py +274 -0
  42. smelt/cli/commands/check.py +151 -0
  43. smelt/cli/commands/discover.py +51 -0
  44. smelt/cli/commands/info.py +112 -0
  45. smelt/cli/session.py +163 -0
  46. smelt/cli/session_slots.py +43 -0
  47. smelt/cli/support.py +90 -0
  48. smelt/config/__init__.py +36 -0
  49. smelt/config/discovery.py +93 -0
  50. smelt/config/errors.py +51 -0
  51. smelt/config/loader.py +282 -0
  52. smelt/config/models.py +717 -0
  53. smelt/config/patterns.py +47 -0
  54. smelt/config/schema.py +23 -0
  55. smelt/config/source.py +56 -0
  56. smelt/config/validation.py +180 -0
  57. smelt/diagnostics/__init__.py +0 -0
  58. smelt/diagnostics/debt.py +226 -0
  59. smelt/diagnostics/dedupe.py +41 -0
  60. smelt/diagnostics/groups.py +109 -0
  61. smelt/diagnostics/render/__init__.py +0 -0
  62. smelt/diagnostics/render/machine.py +237 -0
  63. smelt/diagnostics/render/text.py +321 -0
  64. smelt/diagnostics/report.py +104 -0
  65. smelt/diagnostics/suppressions.py +80 -0
  66. smelt/diagnostics/violation.py +120 -0
  67. smelt/docs.py +98 -0
  68. smelt/engine/__init__.py +0 -0
  69. smelt/engine/briefing.py +630 -0
  70. smelt/engine/cache.py +65 -0
  71. smelt/engine/changes.py +260 -0
  72. smelt/engine/check.py +724 -0
  73. smelt/engine/coverage.py +151 -0
  74. smelt/engine/evaluation.py +291 -0
  75. smelt/engine/file_checks.py +94 -0
  76. smelt/engine/git_source.py +140 -0
  77. smelt/engine/inference.py +854 -0
  78. smelt/engine/mirror_inference.py +95 -0
  79. smelt/engine/native_git.py +190 -0
  80. smelt/engine/ordering_fixes.py +132 -0
  81. smelt/engine/paths.py +163 -0
  82. smelt/engine/result_cache.py +208 -0
  83. smelt/engine/rule_settings.py +164 -0
  84. smelt/engine/schema.py +58 -0
  85. smelt/engine/staged.py +75 -0
  86. smelt/engine/workspace.py +5 -0
  87. smelt/model/__init__.py +9 -0
  88. smelt/model/architecture.py +234 -0
  89. smelt/py.typed +0 -0
  90. smelt/rules/__init__.py +0 -0
  91. smelt/rules/activation.py +129 -0
  92. smelt/rules/base.py +131 -0
  93. smelt/rules/catalog.json +600 -0
  94. smelt/rules/common.py +164 -0
  95. smelt/rules/dependencies/__init__.py +0 -0
  96. smelt/rules/dependencies/composition_root.py +86 -0
  97. smelt/rules/dependencies/cycles.py +329 -0
  98. smelt/rules/dependencies/fanout.py +81 -0
  99. smelt/rules/dependencies/features.py +165 -0
  100. smelt/rules/dependencies/interfaces.py +84 -0
  101. smelt/rules/dependencies/layers.py +138 -0
  102. smelt/rules/dependencies/third_party.py +132 -0
  103. smelt/rules/member_names.py +13 -0
  104. smelt/rules/meta.py +74 -0
  105. smelt/rules/registry.py +132 -0
  106. smelt/rules/structure/__init__.py +0 -0
  107. smelt/rules/structure/assignments.py +114 -0
  108. smelt/rules/structure/contracts.py +71 -0
  109. smelt/rules/structure/coverage.py +100 -0
  110. smelt/rules/structure/enum_values.py +50 -0
  111. smelt/rules/structure/headers.py +143 -0
  112. smelt/rules/structure/import_style.py +145 -0
  113. smelt/rules/structure/layout.py +202 -0
  114. smelt/rules/structure/members.py +116 -0
  115. smelt/rules/structure/naming.py +132 -0
  116. smelt/rules/structure/ordering.py +83 -0
  117. smelt/rules/structure/package_imports.py +117 -0
  118. smelt/rules/structure/type_dispatch.py +79 -0
  119. smelt/rules/testing/__init__.py +0 -0
  120. smelt/rules/testing/awaits.py +46 -0
  121. smelt/rules/testing/cases.py +47 -0
  122. smelt/rules/testing/location.py +537 -0
  123. smelt/rules/testing/mocking.py +140 -0
  124. smelt/rules/testing/outcomes.py +119 -0
  125. smelt/rules/testing/private_access.py +93 -0
  126. smelt/rules/testing/public_attributes.py +62 -0
  127. smelt/rules/testing/public_functions.py +52 -0
  128. smelt/rules/testing/timing.py +62 -0
  129. smelt_cli-0.2.0.data/scripts/smelt.exe +0 -0
  130. smelt_cli-0.2.0.dist-info/METADATA +103 -0
  131. smelt_cli-0.2.0.dist-info/RECORD +133 -0
  132. smelt_cli-0.2.0.dist-info/WHEEL +4 -0
  133. smelt_cli-0.2.0.dist-info/sboms/smelt-cli.cyclonedx.json +5462 -0
@@ -0,0 +1,145 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ from typing import TYPE_CHECKING
5
+
6
+ from smelt.analysis.context import AnalysisContext, Index
7
+ from smelt.analysis.parsing import resolve_relative, type_checking_lines
8
+ from smelt.diagnostics.violation import Category, Severity, Violation
9
+ from smelt.rules.activation import POLICIES
10
+ from smelt.rules.base import BaseRule, RuleDoc
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Iterator
14
+
15
+ from smelt.analysis.files import SourceFile
16
+ from smelt.config.models import ImportStyleConfig
17
+
18
+
19
+ class ImportStyle(BaseRule):
20
+ activation = POLICIES["SMT308"]
21
+ code = "SMT308"
22
+ name = "import-style"
23
+ category = Category.STRUCTURE
24
+ default_severity = Severity.ERROR
25
+ requires = frozenset({Index.SYNTAX})
26
+ doc = RuleDoc(
27
+ summary="An import does not follow the package's declared relative/absolute style.",
28
+ rationale=(
29
+ "A predictable import style makes ownership easier to read. With relative "
30
+ "style and max_relative_level: 1, local imports use one dot; parent and "
31
+ "cross-root imports stay absolute. Deeper relative imports can be explicitly "
32
+ "allowed. The closest package contract supplies the style. No style is "
33
+ "enforced without an explicit contract, and this rule never changes bindings."
34
+ ),
35
+ bad="# app/storage/service.py, relative style with maximum 1\nfrom app.storage.models import Record\nfrom ..domain import Entity",
36
+ good="# app/storage/service.py\nfrom .models import Record\nfrom app.domain import Entity",
37
+ fix=(
38
+ "Use a relative import within the configured dot limit, otherwise use "
39
+ "an absolute import. Preserve aliases and update references if converting "
40
+ "an import statement changes its binding. There is no automatic rewrite."
41
+ ),
42
+ config=("structure.contracts", "architecture.imports.type_checking"),
43
+ )
44
+
45
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
46
+ for source in ctx.files.sources.values():
47
+ contract = ctx.contracts.style_for(source.module)
48
+ if contract is None or contract.spec.imports is None:
49
+ continue
50
+ tree = ctx.asts.parse(source.path)
51
+ guarded = type_checking_lines(tree)
52
+ for node in ast.walk(tree):
53
+ if not isinstance(node, ast.Import | ast.ImportFrom):
54
+ continue
55
+ if (
56
+ node.lineno in guarded
57
+ and ctx.config.architecture.imports.type_checking == "ignore"
58
+ ):
59
+ continue
60
+ yield from self._statement(
61
+ ctx, source, node, contract.spec.imports, contract.name
62
+ )
63
+
64
+ def _statement(
65
+ self,
66
+ ctx: AnalysisContext,
67
+ source: SourceFile,
68
+ node: ast.Import | ast.ImportFrom,
69
+ policy: ImportStyleConfig,
70
+ contract: str,
71
+ ) -> Iterator[Violation]:
72
+ package = (
73
+ source.module if source.is_package else source.module.rpartition(".")[0]
74
+ )
75
+ if isinstance(node, ast.ImportFrom):
76
+ targets = [
77
+ resolve_relative(
78
+ source.module,
79
+ is_package=source.is_package,
80
+ level=node.level,
81
+ target=node.module,
82
+ )
83
+ ]
84
+ current_level = node.level
85
+ else:
86
+ # Relative imports bind a child of a package. Importing the package
87
+ # object itself must be compared against its parent, not itself.
88
+ targets = [alias.name for alias in node.names]
89
+ current_level = 0
90
+ for target in targets:
91
+ if not ctx.model.is_first_party(target):
92
+ continue
93
+ base = (
94
+ target
95
+ if isinstance(node, ast.ImportFrom)
96
+ else target.rpartition(".")[0]
97
+ )
98
+ relative = _relative_base(package, base)
99
+ wants_relative = (
100
+ policy.style == "relative"
101
+ and relative is not None
102
+ and relative[0] <= policy.max_relative_level
103
+ )
104
+ if wants_relative and 0 < current_level <= policy.max_relative_level:
105
+ continue
106
+ if not wants_relative and current_level == 0:
107
+ continue
108
+ expected_style = "relative" if wants_relative else "absolute"
109
+ hint = (
110
+ f"Use from {relative[1]} import ...; preserve names and aliases."
111
+ if wants_relative and relative is not None
112
+ else f"Use an absolute import from {target}."
113
+ )
114
+ yield self.violation(
115
+ f'contract "{contract}" expects an {expected_style} import of {target}',
116
+ path=source.path,
117
+ line=node.lineno,
118
+ column=node.col_offset + 1,
119
+ end_line=node.end_lineno,
120
+ end_column=(node.end_col_offset or node.col_offset) + 1,
121
+ source_module=source.module,
122
+ target_module=target,
123
+ expected={
124
+ "contract": contract,
125
+ "style": expected_style,
126
+ "max_relative_level": policy.max_relative_level,
127
+ "relative_base": relative[1]
128
+ if wants_relative and relative
129
+ else None,
130
+ },
131
+ hint=hint,
132
+ )
133
+
134
+
135
+ def _relative_base(package: str, target: str) -> tuple[int, str] | None:
136
+ source_parts, target_parts = package.split("."), target.split(".") if target else []
137
+ common = 0
138
+ for source_part, target_part in zip(source_parts, target_parts, strict=False):
139
+ if source_part != target_part:
140
+ break
141
+ common += 1
142
+ if common == 0:
143
+ return None
144
+ level = len(source_parts) - common + 1
145
+ return level, "." * level + ".".join(target_parts[common:])
@@ -0,0 +1,202 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from smelt.analysis.context import AnalysisContext, Index
6
+ from smelt.diagnostics.violation import Category, Severity, Violation
7
+ from smelt.model import ModuleKind, is_within
8
+ from smelt.rules.base import BaseRule, RuleDoc
9
+ from smelt.rules.common import display_module_path, join, last_segment
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Iterator
13
+
14
+ from smelt.analysis.files import FileIndex, PackageDir
15
+ from smelt.model import ArchitectureModel
16
+
17
+
18
+ def package_location(files: FileIndex, package: PackageDir) -> str:
19
+ init = files.sources.get(package.module)
20
+ return init.path if init is not None else package.path
21
+
22
+
23
+ def _child_packages(files: FileIndex, parent: str) -> list[PackageDir]:
24
+ prefix = f"{parent}."
25
+ return [
26
+ package
27
+ for name, package in sorted(files.packages.items())
28
+ if name.startswith(prefix) and "." not in name[len(prefix) :]
29
+ ]
30
+
31
+
32
+ class UnknownLayer(BaseRule):
33
+ enabled_by_default = True
34
+ code = "SMT301"
35
+ name = "unknown-layer"
36
+ category = Category.STRUCTURE
37
+ default_severity = Severity.ERROR
38
+ requires = frozenset({Index.FILES})
39
+ doc = RuleDoc(
40
+ summary="A feature contains a package or module outside the declared layers.",
41
+ rationale=(
42
+ "Code outside the layer grid is invisible to every layer rule: voice/models/ "
43
+ "or voice/helpers.py can import anything and be imported by anything. A "
44
+ "feature's __init__.py is fine, and not every feature needs every layer."
45
+ ),
46
+ bad=(
47
+ "voice/\n domain/\n application/\n models/ # not a layer\n"
48
+ " helpers.py # in no layer"
49
+ ),
50
+ good="voice/\n domain/\n models.py\n application/",
51
+ fix=(
52
+ "Move the code into a declared layer, or declare its package as a layer "
53
+ "if the architecture has a distinct responsibility for it."
54
+ ),
55
+ config=("architecture.layers",),
56
+ )
57
+
58
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
59
+ model = ctx.model
60
+ paths = [layer.path.split(".") for layer in model.layers.values()]
61
+ for container in model.grid_containers():
62
+ yield from self._check_children(ctx, container, container, paths)
63
+
64
+ def _check_children(
65
+ self,
66
+ ctx: AnalysisContext,
67
+ container: str,
68
+ parent: str,
69
+ paths: list[list[str]],
70
+ ) -> Iterator[Violation]:
71
+ model = ctx.model
72
+ if model.has_features:
73
+ yield from self._loose_modules(ctx, parent)
74
+ for package in _child_packages(ctx.files, parent):
75
+ info = model.info(package.module)
76
+ if info is not None and (
77
+ info.wiring
78
+ or info.kind in (ModuleKind.SHARED, ModuleKind.COMPOSITION_ROOT)
79
+ ):
80
+ continue
81
+ segment = last_segment(package.module)
82
+ rests = [path[1:] for path in paths if path[0] == segment]
83
+ if any(not rest for rest in rests):
84
+ continue
85
+ if rests:
86
+ yield from self._check_children(ctx, container, package.module, rests)
87
+ continue
88
+ owner = info.feature if info and info.feature else container
89
+ layers = list(model.layers)
90
+ yield self.violation(
91
+ f"{owner} contains package {segment}, which is not a declared layer "
92
+ f"({join(layers)})",
93
+ path=package_location(ctx.files, package),
94
+ source_module=package.module,
95
+ feature=info.feature if info else None,
96
+ expected={"layers": layers},
97
+ hint=(
98
+ f"Move the modules of {display_module_path(model, package.module, package=True)} "
99
+ "into a layer, or declare the package under architecture.layers."
100
+ ),
101
+ )
102
+
103
+ def _loose_modules(self, ctx: AnalysisContext, parent: str) -> Iterator[Violation]:
104
+ model = ctx.model
105
+ layers = list(model.layers)
106
+ for name, source in sorted(ctx.files.sources.items()):
107
+ if source.is_package or name.rsplit(".", 1)[0] != parent:
108
+ continue
109
+ info = model.info(name)
110
+ if info is None or info.layer is not None or info.wiring:
111
+ continue
112
+ if info.kind in (ModuleKind.SHARED, ModuleKind.COMPOSITION_ROOT):
113
+ continue
114
+ owner = info.feature or parent
115
+ yield self.violation(
116
+ f"{owner} contains module {last_segment(name)}.py, which is in no layer "
117
+ f"({join(layers)})",
118
+ path=source.path,
119
+ source_module=name,
120
+ feature=info.feature,
121
+ expected={"layers": layers},
122
+ hint=(
123
+ f"Move {display_module_path(model, name)} into a layer of {owner}, "
124
+ "such as infrastructure for configuration and external services."
125
+ ),
126
+ )
127
+
128
+
129
+ class UnclassifiedModule(BaseRule):
130
+ code = "SMT305"
131
+ name = "unclassified-module"
132
+ category = Category.STRUCTURE
133
+ default_severity = Severity.WARNING
134
+ requires = frozenset({Index.FILES})
135
+ doc = RuleDoc(
136
+ summary="A module maps to no feature, layer, shared set or composition root.",
137
+ rationale=(
138
+ "Unclassified modules are exempt from layer and feature boundary checks: a domain module "
139
+ "may import them. Composition-root/wiring restrictions and configured cycle checks still apply. Central code such as a "
140
+ "database or storage package belongs to a layer via architecture.modules. "
141
+ "Root packages with no classified module at all (libraries) are skipped."
142
+ ),
143
+ bad="gateway/\n platform/db.py # neither shared, a layer nor a feature",
144
+ good="# smelt.yaml\narchitecture:\n modules:\n gateway.platform: infrastructure",
145
+ fix=(
146
+ "Give the package a layer under architecture.modules, list it in "
147
+ "architecture.shared or composition_root, or move it into a feature."
148
+ ),
149
+ config=(
150
+ "architecture.modules",
151
+ "architecture.shared",
152
+ "architecture.composition_root",
153
+ ),
154
+ )
155
+
156
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
157
+ model = ctx.model
158
+ if not model.layers and not model.has_features:
159
+ return
160
+ # A root package with nothing classified is a library outside the
161
+ # architecture (e.g. a workspace member): check it for cycles only.
162
+ described = {
163
+ name.split(".", 1)[0]
164
+ for name in ctx.files.sources
165
+ if (info := model.info(name)) is not None
166
+ and (info.kind is not ModuleKind.UNCLASSIFIED or info.wiring)
167
+ }
168
+ for name, source in sorted(ctx.files.sources.items()):
169
+ info = model.info(name)
170
+ if source.is_package or info is None:
171
+ continue
172
+ if info.kind is not ModuleKind.UNCLASSIFIED or info.wiring:
173
+ continue
174
+ if name.split(".", 1)[0] not in described:
175
+ continue
176
+ package = _top_package(model, name)
177
+ yield self.violation(
178
+ f"{name} is not part of a feature, layer, shared or composition root",
179
+ path=source.path,
180
+ source_module=name,
181
+ hint=(
182
+ f"Give {package} a layer under architecture.modules "
183
+ f"(e.g. {package}: infrastructure), or list it in shared or "
184
+ "composition_root."
185
+ ),
186
+ )
187
+
188
+
189
+ def _top_package(model: ArchitectureModel, module: str) -> str:
190
+ """The package directly below the root package, or the module itself."""
191
+ parts = module.split(".")
192
+ if all(
193
+ info.kind is ModuleKind.UNCLASSIFIED
194
+ for name, info in model.modules.items()
195
+ if is_within(name, parts[0])
196
+ ):
197
+ return parts[0]
198
+ if parts[0] in model.config.project.root_packages and len(parts) > 2: # noqa: PLR2004
199
+ candidate = ".".join(parts[:2])
200
+ if model.is_package(candidate):
201
+ return candidate
202
+ return module
@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from smelt.analysis.context import AnalysisContext, Index
6
+ from smelt.diagnostics.violation import Category, Severity, Violation
7
+ from smelt.rules.base import BaseRule, RuleDoc
8
+ from smelt.rules.member_names import private_name
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterator
12
+
13
+
14
+ class InternalPublicMember(BaseRule):
15
+ member_local = True
16
+ code = "SMT316"
17
+ name = "internal-public-member"
18
+ category = Category.STRUCTURE
19
+ default_severity = Severity.WARNING
20
+ requires = frozenset({Index.MEMBERS})
21
+ doc = RuleDoc(
22
+ summary="A public module function or instance method has no observed use outside its module or class.",
23
+ rationale=(
24
+ "An implementation helper should not advertise a public interface solely because it lacks a leading underscore. This opt-in package review includes unused definitions and internally used sync/async functions and ordinary instance methods. Imports and module escapes preserve module functions; known test accesses also count as external use, leaving test-only public functions to SMT429. Explicit module __all__ exports and decorated functions are preserved. Methods on decorated, inherited or subclassed classes, special/private methods, properties and class/static methods are excluded. For methods, even unresolved same-named attribute accesses outside the owning class conservatively preserve visibility. External libraries, frameworks, dynamic reflection and unscanned callers cannot be ruled out. This finding asks for review and does not prove a rename is safe."
25
+ " Excluded files, unselected packages and external consumers are unassessed; findings expose usage_scope so absence of observed callers is not mistaken for a whole-project proof."
26
+ ),
27
+ bad="class Browser:\n def emit(self, event): ...\n def run(self):\n self.emit('ready')\nBrowser().run()",
28
+ good="class Browser:\n def _emit(self, event): ...\n def run(self):\n self._emit('ready')\nBrowser().run()",
29
+ fix="Review the supported interface and callers. For a genuine internal helper, add a leading underscore and update calls and callback references. Resolve existing private-name collisions before renaming. Preserve deliberate public APIs with __all__ for module functions or append `# smelt: ignore[SMT316] -- <specific API reason>` to the reported definition. Keep the concrete reason beside the code; Smelt cannot verify its truth. No automatic rename is performed.",
30
+ config=("rules", "structure.contracts", "project.test_roots"),
31
+ )
32
+
33
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
34
+ for member in ctx.member_usage.members:
35
+ node = member.node
36
+ if (
37
+ node.name.startswith("_")
38
+ or member.kind == "staticmethod"
39
+ or member.external_use
40
+ ):
41
+ continue
42
+ qualified = (
43
+ f"{member.owner.name}.{node.name}" if member.owner else node.name
44
+ )
45
+ suggested_name = private_name(node.name, member.occupied_names)
46
+ yield self.violation(
47
+ f"{qualified} is public, but has no observed use outside its {'class' if member.owner else 'module'}",
48
+ path=member.path,
49
+ line=node.lineno,
50
+ column=node.col_offset + 1,
51
+ source_module=member.module,
52
+ target_module=f"{member.module}.{qualified}",
53
+ expected={
54
+ "kind": member.kind,
55
+ "class": member.owner.name if member.owner else None,
56
+ "member": node.name,
57
+ "suggested_name": suggested_name,
58
+ "usage_scope": ctx.member_usage.usage_scope,
59
+ "observed_usage": "internal-only"
60
+ if member.internal_references
61
+ else "unused",
62
+ "internal_references": list(member.internal_references),
63
+ "automatic_rename": False,
64
+ },
65
+ hint=f"Review making {qualified} private as {suggested_name}; excluded files (including maintainer scripts), unselected packages and external consumers were not assessed. Check those callers before renaming. For a deliberate public API, append `# smelt: ignore[SMT316] -- <specific API reason>` to this definition.",
66
+ )
67
+
68
+
69
+ class InternalStaticHelper(BaseRule):
70
+ member_local = True
71
+ code = "SMT317"
72
+ name = "internal-static-helper"
73
+ category = Category.STRUCTURE
74
+ default_severity = Severity.HINT
75
+ requires = frozenset({Index.MEMBERS})
76
+ doc = RuleDoc(
77
+ summary="An internal static helper can be reviewed for extraction to a private module function.",
78
+ rationale=(
79
+ "A helper that needs neither instance nor class state is often easier to find and reuse as a private module function. This package convention reviews direct sync/async methods carrying only the recognized builtin staticmethod decorator, including import aliases. Known or unresolved external same-named attribute access preserves static APIs. Classes with inheritance, subclasses or decorators, additional method decorators, special methods, __class__/super references and detected class-namespace dependencies are excluded. This is a placement preference, not proof of equivalent runtime behavior; external/dynamic consumers and definition-time dependencies still need review."
80
+ " Excluded files, unselected packages and external consumers are unassessed; findings expose usage_scope so absence of observed callers is not mistaken for a whole-project proof."
81
+ ),
82
+ bad="class Browser:\n @staticmethod\n def _normalize(value):\n return value.strip()\n def send(self, value):\n return self._normalize(value)",
83
+ good="def _normalize(value):\n return value.strip()\n\nclass Browser:\n def send(self, value):\n return _normalize(value)",
84
+ fix="Move the helper to module scope with a leading underscore, remove @staticmethod, and update class/instance-qualified calls and callback references. Preserve annotations, defaults, evaluation order and dependencies; choose a distinct name if the module already binds it. Keep deliberate static APIs with a closest package rule set to off or reasoned suppression. No automatic extraction is performed.",
85
+ config=("rules", "structure.contracts", "project.test_roots"),
86
+ )
87
+
88
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
89
+ for member in ctx.member_usage.members:
90
+ if (
91
+ member.kind != "staticmethod"
92
+ or member.external_use
93
+ or member.class_dependencies
94
+ or member.node.name.startswith("__")
95
+ ):
96
+ continue
97
+ node = member.node
98
+ name = private_name(node.name, member.module_names)
99
+ yield self.violation(
100
+ f"{member.owner.name if member.owner else ''}.{node.name} is an internal static helper; prefer a private module function",
101
+ path=member.path,
102
+ line=node.lineno,
103
+ column=node.col_offset + 1,
104
+ source_module=member.module,
105
+ target_module=f"{member.module}.{member.owner.name if member.owner else ''}.{node.name}",
106
+ expected={
107
+ "class": member.owner.name if member.owner else None,
108
+ "method": node.name,
109
+ "suggested_name": name,
110
+ "usage_scope": ctx.member_usage.usage_scope,
111
+ "destination": member.module,
112
+ "internal_references": list(member.internal_references),
113
+ "automatic_extraction": False,
114
+ },
115
+ hint=f"Review moving this helper to {name} at module scope, preserving defaults and annotations. Excluded files (including maintainer scripts), unselected packages and external consumers were not assessed; check those callers first.",
116
+ )
@@ -0,0 +1,132 @@
1
+ from __future__ import annotations
2
+
3
+ from itertools import chain
4
+ from typing import TYPE_CHECKING
5
+
6
+ from smelt.analysis.context import AnalysisContext, Index
7
+ from smelt.diagnostics.violation import Category, Severity, Violation
8
+ from smelt.rules.activation import POLICIES
9
+ from smelt.rules.base import BaseRule, RuleDoc
10
+ from smelt.rules.common import last_segment
11
+ from smelt.rules.structure.layout import package_location
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Iterator
15
+
16
+
17
+ class ForbiddenPackageName(BaseRule):
18
+ activation = POLICIES["SMT302"]
19
+ code = "SMT302"
20
+ name = "forbidden-package-name"
21
+ category = Category.STRUCTURE
22
+ default_severity = Severity.ERROR
23
+ requires = frozenset({Index.FILES})
24
+ doc = RuleDoc(
25
+ summary="A package or module name is listed in structure.forbidden_names.",
26
+ rationale=(
27
+ "Names like utils or helpers describe nothing, so everything fits in them. "
28
+ "They grow into grab bags that every layer imports."
29
+ ),
30
+ bad="voice/application/utils.py",
31
+ good="voice/application/durations.py",
32
+ fix="Name the module after what it does, or move each function next to its callers.",
33
+ config=("structure.forbidden_names",),
34
+ )
35
+
36
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
37
+ forbidden = set(ctx.config.structure.forbidden_names)
38
+ if not forbidden:
39
+ return
40
+ files = ctx.files
41
+ model = ctx.model
42
+ for name, package in sorted(files.packages.items()):
43
+ if last_segment(name) in forbidden:
44
+ info = model.info(name)
45
+ yield self.violation(
46
+ f'package name "{last_segment(name)}" is not allowed ({name})',
47
+ path=package_location(files, package),
48
+ source_module=name,
49
+ feature=info.feature if info else None,
50
+ layer=info.layer if info else None,
51
+ expected={"forbidden_names": sorted(forbidden)},
52
+ hint="Name the package after what it does.",
53
+ )
54
+ for name, source in sorted(files.sources.items()):
55
+ if source.is_package or last_segment(name) not in forbidden:
56
+ continue
57
+ info = model.info(name)
58
+ yield self.violation(
59
+ f'module name "{last_segment(name)}" is not allowed ({name})',
60
+ path=source.path,
61
+ source_module=name,
62
+ feature=info.feature if info else None,
63
+ layer=info.layer if info else None,
64
+ expected={"forbidden_names": sorted(forbidden)},
65
+ hint="Name the module after what it does, or move its functions next to their callers.",
66
+ )
67
+
68
+
69
+ class NoPrivateModules(BaseRule):
70
+ activation = POLICIES["SMT312"]
71
+ code = "SMT312"
72
+ name = "no-private-modules"
73
+ category = Category.STRUCTURE
74
+ default_severity = Severity.ERROR
75
+ requires = frozenset({Index.FILES})
76
+ doc = RuleDoc(
77
+ summary="A module or package has an underscore prefix forbidden by its naming policy.",
78
+ rationale=(
79
+ "Some projects use descriptive module names and keep private helpers "
80
+ "inside them. This opt-in naming convention rejects _service.py and "
81
+ "_internal/ even when they export public symbols. __init__.py and "
82
+ "__main__.py retain their Python-defined roles. Function, method, "
83
+ "class and attribute names are outside this rule. Architecture API "
84
+ "contracts apply independently of the spelling of a module name."
85
+ ),
86
+ bad="app/_service.py\napp/_internal/store.py",
87
+ good="app/service.py\napp/storage/store.py\n\n# Inside service.py:\ndef run(): ...\ndef _prepare(): ...",
88
+ fix=(
89
+ "Choose a descriptive module or package name without a leading "
90
+ "underscore, then update imports and deliberate facade exports. "
91
+ "A more specific package can explicitly allow the convention. "
92
+ "No files or symbols are renamed automatically."
93
+ ),
94
+ config=("structure.contracts",),
95
+ example_language="text",
96
+ )
97
+
98
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
99
+ files = ctx.files
100
+ entries = chain(
101
+ (
102
+ (name, package_location(files, package), "package")
103
+ for name, package in sorted(files.packages.items())
104
+ ),
105
+ (
106
+ (name, source.path, "module")
107
+ for name, source in sorted(files.sources.items())
108
+ if not source.is_package and last_segment(name) != "__main__"
109
+ ),
110
+ )
111
+ for name, path, kind in entries:
112
+ segment = last_segment(name)
113
+ if not segment.startswith("_"):
114
+ continue
115
+ contract = ctx.contracts.policy_for(name, "private_modules")
116
+ if contract is None or contract.spec.private_modules != "forbid":
117
+ continue
118
+ info = ctx.model.info(name)
119
+ yield self.violation(
120
+ f'contract "{contract.name}" forbids underscore-prefixed {kind} name "{segment}" ({name})',
121
+ path=path,
122
+ source_module=name,
123
+ feature=info.feature if info else None,
124
+ layer=info.layer if info else None,
125
+ expected={
126
+ "contract": contract.name,
127
+ "private_modules": "forbid",
128
+ "kind": kind,
129
+ "name": segment,
130
+ },
131
+ hint=f"Rename the {kind} after its responsibility without a leading underscore; update imports and facade exports. Private helpers inside a normal module may keep their underscore prefix.",
132
+ )
@@ -0,0 +1,83 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ from typing import TYPE_CHECKING
5
+
6
+ from smelt.analysis.context import AnalysisContext, Index
7
+ from smelt.diagnostics.violation import Category, Severity, Violation
8
+ from smelt.rules.base import BaseRule, RuleDoc
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterator
12
+
13
+
14
+ class PublicDefinitionsFirst(BaseRule):
15
+ code = "SMT313"
16
+ name = "public-definitions-first"
17
+ category = Category.STRUCTURE
18
+ default_severity = Severity.ERROR
19
+ requires = frozenset({Index.ORDERING})
20
+ doc = RuleDoc(
21
+ summary="Definitions are out of public-first order within modeled execution boundaries.",
22
+ rationale=(
23
+ "Public interfaces should be easy to find. A stable topological order "
24
+ "prioritizes configured categories while preserving category order, "
25
+ "definition-time reads, rebinding and execution barriers. Function bodies "
26
+ "are deferred; decorators, defaults, assignments and eager annotations "
27
+ "are not. Future imports and declared Python 3.14+ targets defer annotations. "
28
+ "Overload/property families remain atomic. Unknown execution is pinned."
29
+ ),
30
+ bad="def _load():\n return 1\n\ndef get():\n return _load()",
31
+ good="def get():\n return _load()\n\ndef _load():\n return 1",
32
+ fix=(
33
+ "Review the expected order and execution barriers. Explicit check --fix "
34
+ "can apply bounded moves where the package permits safe-only fixes. "
35
+ "Imports, unknown execution and a misplaced main guard require manual "
36
+ "review. Names and visibility are never rewritten by ordering."
37
+ " Refused sections identify the triggering expression and its source "
38
+ "location in fix_blocker and fix_reason; the safety boundary stays in place."
39
+ ),
40
+ config=("rules", "structure.contracts", "project.python_version"),
41
+ )
42
+
43
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
44
+ for result in ctx.ordering.files.values():
45
+ for issue in result.issues:
46
+ section = issue.section
47
+ reason = issue.reason or (section.fix_reason if section else None)
48
+ blocker = issue.fix_node or (
49
+ section.fix_blocker.node
50
+ if section and section.fix_blocker
51
+ else None
52
+ )
53
+ location = (
54
+ {
55
+ "path": result.path,
56
+ "line": blocker.lineno,
57
+ "column": blocker.col_offset + 1,
58
+ "expression": ast.unparse(blocker).splitlines()[0],
59
+ }
60
+ if blocker is not None
61
+ else None
62
+ )
63
+ if reason and location:
64
+ reason += f" ({result.path}:{location['line']}:{location['column']}: {location['expression']})"
65
+ yield self.violation(
66
+ issue.message,
67
+ path=result.path,
68
+ line=issue.line,
69
+ source_module=result.module,
70
+ expected={
71
+ "contract": result.contract,
72
+ "scope": issue.scope,
73
+ "ordering_edges": list(issue.edges),
74
+ "section": section.key if section else None,
75
+ "original": section.original if section else None,
76
+ "order": section.expected if section else None,
77
+ "fixable": section is not None and reason is None,
78
+ "fix_reason": reason,
79
+ "fix_blocker": location,
80
+ "deferred_annotations": result.deferred,
81
+ },
82
+ hint=f"Keep execution boundaries and prerequisite definitions in place. {reason or 'Use the expected order; bounded fixes require explicit --fix.'}",
83
+ )