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
smelt/config/models.py ADDED
@@ -0,0 +1,717 @@
1
+ import posixpath
2
+ import re
3
+ from typing import Annotated, Literal, Self
4
+
5
+ from pydantic import (
6
+ BaseModel,
7
+ ConfigDict,
8
+ Field,
9
+ field_validator,
10
+ model_validator,
11
+ )
12
+
13
+ type Policy = Literal["allow", "deny"]
14
+ type SeverityName = Literal["error", "warning", "hint", "off"]
15
+
16
+ _DOTTED_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$")
17
+ _RULE_CODE = re.compile(r"^[A-Z]+[0-9]+$")
18
+ _RULE_NAME = re.compile(r"^[a-z][a-z0-9]*(-[a-z0-9]+)*$")
19
+ _LAYER_PAIR = re.compile(r"^\s*([A-Za-z_][\w.]*)\s*->\s*([A-Za-z_][\w.]*)\s*$")
20
+ _FEATURE_LAYER = re.compile(r"^([A-Za-z_]\w*)\.([A-Za-z_]\w*)$")
21
+
22
+
23
+ class _Model(BaseModel):
24
+ model_config = ConfigDict(frozen=True, extra="forbid")
25
+
26
+
27
+ def _check_dotted(values: list[str]) -> list[str]:
28
+ for value in values:
29
+ if not _DOTTED_NAME.match(value):
30
+ msg = f'"{value}" is not a dotted module name'
31
+ raise ValueError(msg)
32
+ return values
33
+
34
+
35
+ class SourceExclusion(_Model):
36
+ path: str = Field(
37
+ description="Project-relative glob of source files deliberately excluded from analysis."
38
+ )
39
+ reason: str = Field(
40
+ description="Why this code is outside this architecture policy."
41
+ )
42
+
43
+ @field_validator("path", "reason")
44
+ @classmethod
45
+ def _not_blank(cls, value: str) -> str:
46
+ if not value.strip():
47
+ raise ValueError("must not be empty")
48
+ return value.strip()
49
+
50
+
51
+ class ProjectConfig(_Model):
52
+ """Which packages and tests smelt reads."""
53
+
54
+ root_packages: Annotated[
55
+ list[str],
56
+ Field(
57
+ default_factory=list,
58
+ description="Top-level packages to check; discovered from source_roots when omitted.",
59
+ ),
60
+ ]
61
+ source_roots: list[str] = Field(
62
+ default_factory=lambda: ["."],
63
+ description="Directories that contain the root packages, e.g. [src].",
64
+ )
65
+ test_roots: list[str] = Field(
66
+ default_factory=lambda: ["tests"],
67
+ description="Directories with the tests; with layout: mirror they must exist.",
68
+ )
69
+ exclude: list[str | SourceExclusion] = Field(
70
+ default_factory=list,
71
+ description="Path globs or {path, reason} entries smelt skips entirely. Strict coverage requires a reason for every exclusion.",
72
+ )
73
+ coverage: Literal["configured", "strict"] = Field(
74
+ default="configured",
75
+ description="strict: fail on uncovered or unclassified production files and exclusions without reasons, including Python workspace members.",
76
+ )
77
+ python_version: str | None = Field(
78
+ default=None,
79
+ pattern=r"^3\.[0-9]+$",
80
+ description="Explicit minimum supported Python version for version-aware conventions, e.g. 3.14. Overrides per-project requires-python metadata; never inferred from the running interpreter or .python-version.",
81
+ )
82
+
83
+ @property
84
+ def exclude_patterns(self) -> list[str]:
85
+ return [
86
+ entry if isinstance(entry, str) else entry.path for entry in self.exclude
87
+ ]
88
+
89
+ @field_validator("source_roots", "test_roots")
90
+ @classmethod
91
+ def _normalize_roots(cls, values: list[str]) -> list[str]:
92
+ return list(
93
+ dict.fromkeys(posixpath.normpath(v.replace("\\", "/")) for v in values)
94
+ )
95
+
96
+ @field_validator("root_packages")
97
+ @classmethod
98
+ def _root_packages_are_top_level(cls, values: list[str]) -> list[str]:
99
+ for value in _check_dotted(values):
100
+ if "." in value:
101
+ msg = f'"{value}" must be a top-level package name'
102
+ raise ValueError(msg)
103
+ return values
104
+
105
+
106
+ class FeaturesConfig(_Model):
107
+ root: str | None = Field(
108
+ default=None,
109
+ description="Package whose direct child packages are the features.",
110
+ )
111
+ pattern: str | None = Field(
112
+ default=None,
113
+ description='Dotted pattern ending in {feature}, e.g. "app.{feature}".',
114
+ )
115
+
116
+ @model_validator(mode="after")
117
+ def _exactly_one(self) -> Self:
118
+ if (self.root is None) == (self.pattern is None):
119
+ msg = "set exactly one of `root` or `pattern`"
120
+ raise ValueError(msg)
121
+ if self.root is not None:
122
+ _check_dotted([self.root])
123
+ if self.pattern is not None:
124
+ segments = self.pattern.split(".")
125
+ if segments.count("{feature}") != 1 or segments[-1] != "{feature}":
126
+ msg = (
127
+ f'pattern "{self.pattern}" must end with a "{{feature}}" segment, '
128
+ 'e.g. "gateway.{feature}"'
129
+ )
130
+ raise ValueError(msg)
131
+ if len(segments) < 2: # noqa: PLR2004
132
+ msg = "pattern needs a package before {feature}"
133
+ raise ValueError(msg)
134
+ _check_dotted(segments[:-1])
135
+ return self
136
+
137
+
138
+ class ThirdPartyPolicy(_Model):
139
+ default: Policy = "allow"
140
+ allow: list[str] = Field(default_factory=list)
141
+ deny: list[str] = Field(default_factory=list)
142
+
143
+ @model_validator(mode="before")
144
+ @classmethod
145
+ def _expand_short_form(cls, data: object) -> object:
146
+ if data in ("allow", "deny"):
147
+ return {"default": data}
148
+ return data
149
+
150
+ @model_validator(mode="after")
151
+ def _entries_match_default(self) -> Self:
152
+ if self.default == "allow" and self.allow:
153
+ msg = "`allow` is only valid with `default: deny`"
154
+ raise ValueError(msg)
155
+ if self.default == "deny" and self.deny:
156
+ msg = "`deny` is only valid with `default: allow`"
157
+ raise ValueError(msg)
158
+ _check_dotted([*self.allow, *self.deny])
159
+ return self
160
+
161
+
162
+ class LayerConfig(_Model):
163
+ path: str = Field(description="Dotted path of the layer package inside a feature.")
164
+ may_depend_on: list[str] = Field(
165
+ default_factory=list, description="Layers this layer may import."
166
+ )
167
+ third_party: ThirdPartyPolicy = Field(
168
+ default_factory=ThirdPartyPolicy,
169
+ description="Which third-party packages the layer may import (SMT103).",
170
+ )
171
+
172
+ @field_validator("path")
173
+ @classmethod
174
+ def _path_is_dotted(cls, value: str) -> str:
175
+ _check_dotted([value])
176
+ return value
177
+
178
+
179
+ class CrossFeatureAllowance(_Model):
180
+ source: str = Field(alias="from")
181
+ target: str = Field(alias="to")
182
+
183
+ @model_validator(mode="after")
184
+ def _feature_layers(self) -> Self:
185
+ for value in (self.source, self.target):
186
+ if not _FEATURE_LAYER.fullmatch(value):
187
+ msg = f'"{value}" must look like "feature.layer"'
188
+ raise ValueError(msg)
189
+ return self
190
+
191
+ def components(self) -> tuple[str, str, str, str]:
192
+ source_feature, source_layer = self.source.split(".")
193
+ target_feature, target_layer = self.target.split(".")
194
+ return source_feature, source_layer, target_feature, target_layer
195
+
196
+
197
+ class CrossFeatureConfig(_Model):
198
+ """Imports between features."""
199
+
200
+ default: Policy = Field(
201
+ default="deny", description="Whether features may import each other at all."
202
+ )
203
+ allow: list[str | CrossFeatureAllowance] = Field(
204
+ default_factory=list,
205
+ description='Allowed imports: "layer -> layer" for all features, or {from: feature.layer, to: feature.layer}.',
206
+ )
207
+
208
+ @field_validator("allow")
209
+ @classmethod
210
+ def _pairs_are_well_formed(
211
+ cls, values: list[str | CrossFeatureAllowance]
212
+ ) -> list[str | CrossFeatureAllowance]:
213
+ for value in values:
214
+ if isinstance(value, str) and not _LAYER_PAIR.match(value):
215
+ msg = f'"{value}" must look like "layer -> layer"'
216
+ raise ValueError(msg)
217
+ return values
218
+
219
+ def pairs(self) -> frozenset[tuple[str, str]]:
220
+ result: set[tuple[str, str]] = set()
221
+ for value in self.allow:
222
+ if not isinstance(value, str):
223
+ continue
224
+ match = _LAYER_PAIR.match(value)
225
+ if match:
226
+ result.add((match.group(1), match.group(2)))
227
+ return frozenset(result)
228
+
229
+ def allows(
230
+ self,
231
+ source_feature: str,
232
+ source_layer: str,
233
+ target_feature: str,
234
+ target_layer: str,
235
+ ) -> bool:
236
+ if (source_layer, target_layer) in self.pairs():
237
+ return True
238
+ return any(
239
+ isinstance(value, CrossFeatureAllowance)
240
+ and value.components()
241
+ == (source_feature, source_layer, target_feature, target_layer)
242
+ for value in self.allow
243
+ )
244
+
245
+ def labels(self) -> list[str]:
246
+ return [
247
+ value if isinstance(value, str) else f"{value.source} -> {value.target}"
248
+ for value in self.allow
249
+ ]
250
+
251
+ def entries(self) -> list[dict[str, str | None]]:
252
+ """Each allowance as fields; a ``None`` feature stands for every feature."""
253
+ found: list[dict[str, str | None]] = []
254
+ for value in self.allow:
255
+ features: tuple[str | None, str | None] = (None, None)
256
+ if isinstance(value, CrossFeatureAllowance):
257
+ source_feature, source_layer, target_feature, target_layer = (
258
+ value.components()
259
+ )
260
+ features = (source_feature, target_feature)
261
+ elif match := _LAYER_PAIR.match(value):
262
+ source_layer, target_layer = match.group(1), match.group(2)
263
+ else:
264
+ continue
265
+ found.append(
266
+ {
267
+ "source_feature": features[0],
268
+ "source_layer": source_layer,
269
+ "target_feature": features[1],
270
+ "target_layer": target_layer,
271
+ }
272
+ )
273
+ return found
274
+
275
+
276
+ type CycleScope = Literal["features", "layers", "siblings"]
277
+
278
+
279
+ def _all_cycle_scopes() -> list[CycleScope]:
280
+ return ["features", "layers", "siblings"]
281
+
282
+
283
+ class ImportsConfig(_Model):
284
+ """Which imports the dependency rules look at."""
285
+
286
+ type_checking: Literal["include", "ignore"] = Field(
287
+ default="include",
288
+ description="Whether imports under `if TYPE_CHECKING:` count.",
289
+ )
290
+ transitive: bool = Field(
291
+ default=False,
292
+ description="Also check indirect layer, feature, shared, composition-root and third-party dependencies through all reachable project modules. Reports a shortest import chain; external packages are leaves.",
293
+ )
294
+ cycles: list[CycleScope] = Field(
295
+ default_factory=_all_cycle_scopes, description="Where SMT104 looks for cycles."
296
+ )
297
+
298
+
299
+ class ArchitectureConfig(_Model):
300
+ """Features, layers and the modules around them."""
301
+
302
+ features: FeaturesConfig | None = Field(
303
+ default=None, description="Where the features (vertical slices) live."
304
+ )
305
+ shared: list[str] = Field(
306
+ default_factory=list,
307
+ description="Modules every feature may import; they must not import features.",
308
+ )
309
+ composition_root: list[str] = Field(
310
+ default_factory=list,
311
+ description="Modules that wire everything; nothing may import them.",
312
+ )
313
+ wiring: list[str] = Field(
314
+ default_factory=list,
315
+ description="Provider modules (whole-segment * allowed) that may import across layers and features; they keep their feature and layer.",
316
+ )
317
+ modules: dict[str, str] = Field(
318
+ default_factory=dict,
319
+ description="Packages outside the features mapped to a layer, e.g. {backend.platform: infrastructure}.",
320
+ )
321
+ layers: dict[str, LayerConfig] = Field(
322
+ default_factory=dict, description="The layers and what each may import."
323
+ )
324
+ cross_feature: CrossFeatureConfig = Field(
325
+ default_factory=CrossFeatureConfig, description="Imports between features."
326
+ )
327
+ imports: ImportsConfig = Field(
328
+ default_factory=ImportsConfig, description="Which imports count."
329
+ )
330
+
331
+ @field_validator("shared", "composition_root")
332
+ @classmethod
333
+ def _modules_are_dotted(cls, values: list[str]) -> list[str]:
334
+ return _check_dotted(values)
335
+
336
+ @field_validator("modules")
337
+ @classmethod
338
+ def _module_keys_are_dotted(cls, values: dict[str, str]) -> dict[str, str]:
339
+ _check_dotted(list(values))
340
+ return values
341
+
342
+ @field_validator("wiring")
343
+ @classmethod
344
+ def _wiring_patterns(cls, values: list[str]) -> list[str]:
345
+ for value in values:
346
+ if any(
347
+ segment != "*" and not _DOTTED_NAME.fullmatch(segment)
348
+ for segment in value.split(".")
349
+ ):
350
+ msg = f'"{value}" must be a dotted module pattern with whole-segment * wildcards'
351
+ raise ValueError(msg)
352
+ return values
353
+
354
+
355
+ class ImportStyleConfig(_Model):
356
+ style: Literal["relative", "absolute"] = Field(
357
+ default="relative",
358
+ description="relative: prefer relative first-party imports up to max_relative_level, absolute beyond it; absolute: always use absolute imports.",
359
+ )
360
+ max_relative_level: int = Field(
361
+ default=1,
362
+ ge=1,
363
+ description="Maximum dots in a relative import when style is relative. Cross-root and deeper imports stay absolute.",
364
+ )
365
+
366
+
367
+ type ModuleOrderSlot = Literal[
368
+ "docstring",
369
+ "future-imports",
370
+ "imports",
371
+ "dunder-assignments",
372
+ "type-vars",
373
+ "public",
374
+ "private",
375
+ "main-guard",
376
+ ]
377
+ type ClassOrderSlot = Literal[
378
+ "class-attributes", "init", "dunders", "public", "private"
379
+ ]
380
+
381
+
382
+ def _module_order() -> list[ModuleOrderSlot]:
383
+ return [
384
+ "docstring",
385
+ "future-imports",
386
+ "imports",
387
+ "dunder-assignments",
388
+ "type-vars",
389
+ "public",
390
+ "private",
391
+ "main-guard",
392
+ ]
393
+
394
+
395
+ def _class_order() -> list[ClassOrderSlot]:
396
+ return ["class-attributes", "init", "dunders", "public", "private"]
397
+
398
+
399
+ class OrderingConfig(_Model):
400
+ module: list[ModuleOrderSlot] = Field(default_factory=_module_order)
401
+ class_order: list[ClassOrderSlot] = Field(
402
+ default_factory=_class_order, alias="class"
403
+ )
404
+ constants_exempt: bool = Field(
405
+ default=False,
406
+ description="Treat private uppercase module constants like public definitions, preserving their relative order.",
407
+ )
408
+ fix: Literal["off", "safe-only"] = Field(
409
+ default="safe-only",
410
+ description="Permit bounded ordering fixes only when check --fix is explicitly requested. Plain check never writes source.",
411
+ )
412
+
413
+ @field_validator("module")
414
+ @classmethod
415
+ def _module_slots(cls, values: list[ModuleOrderSlot]) -> list[ModuleOrderSlot]:
416
+ if len(values) != len(set(values)) or set(values) != set(_module_order()):
417
+ raise ValueError(
418
+ "module order must contain every module category exactly once"
419
+ )
420
+ if values.index("public") > values.index("private"):
421
+ raise ValueError("public-definitions-first requires public before private")
422
+ if (
423
+ values[:3] != ["docstring", "future-imports", "imports"]
424
+ or values[-1] != "main-guard"
425
+ ):
426
+ raise ValueError(
427
+ "module order must start with docstring, future-imports, imports and end with main-guard"
428
+ )
429
+ return values
430
+
431
+ @field_validator("class_order")
432
+ @classmethod
433
+ def _class_slots(cls, values: list[ClassOrderSlot]) -> list[ClassOrderSlot]:
434
+ if len(values) != len(set(values)) or set(values) != set(_class_order()):
435
+ raise ValueError(
436
+ "class order must contain every class category exactly once"
437
+ )
438
+ if values.index("public") > values.index("private"):
439
+ raise ValueError("public-definitions-first requires public before private")
440
+ return values
441
+
442
+
443
+ class TypeDispatchConfig(_Model):
444
+ style: Literal["allow", "match"] = "match"
445
+ min_branches: int = Field(
446
+ default=3,
447
+ ge=2,
448
+ description="Minimum number of type-tested if/elif branches over the same simple name before SMT315 suggests match/case.",
449
+ )
450
+
451
+
452
+ class PackageContract(_Model):
453
+ """Opt-in module layout and entry points for matching packages."""
454
+
455
+ match: str = Field(
456
+ description="Dotted package pattern; a whole-segment * matches one package segment."
457
+ )
458
+ required: list[str] = Field(
459
+ default_factory=list,
460
+ description="Relative dotted modules or packages that must exist in every matching package (SMT307).",
461
+ )
462
+ public: list[str] | None = Field(
463
+ default=None,
464
+ description="Relative public module patterns (SMT107). '.' exposes the package facade; * matches one segment, ** any depth. Omitted: no interface restriction; []: private package. Each pattern must match analyzed code.",
465
+ )
466
+ imports: ImportStyleConfig | None = Field(
467
+ default=None,
468
+ description="Optional import style for code in this package. The most specific enclosing package contract wins.",
469
+ )
470
+ bundle_imports_at: int | None = Field(
471
+ default=None,
472
+ ge=2,
473
+ description="Suggest a package facade when one outside source module imports this many distinct implementation modules of the package (SMT108, hint).",
474
+ )
475
+ module_docstrings: Literal["allow", "forbid"] | None = Field(
476
+ default=None,
477
+ description="Optional module-docstring policy (SMT309). Function and class documentation is unaffected. The closest explicit package policy wins.",
478
+ )
479
+ future_annotations: Literal["allow", "forbid", "when-needed"] | None = Field(
480
+ default=None,
481
+ description="allow: preserve; forbid: reject the annotations future import (SMT310); when-needed: reject it for a declared Python 3.14+ minimum, otherwise conservatively suggest review when no postponement need is found (SMT311). No automatic rewriting.",
482
+ )
483
+ private_modules: Literal["allow", "forbid"] | None = Field(
484
+ default=None,
485
+ description="Optional naming convention (SMT312): forbid module and package names starting with _, except the special __init__.py and __main__.py files. Private functions and methods are unaffected. The closest explicit package policy wins.",
486
+ )
487
+ ordering: OrderingConfig | None = Field(
488
+ default=None,
489
+ description="Definition order for modules and classes. Dependencies and execution barriers take precedence over category priority; the closest explicit policy wins.",
490
+ )
491
+ type_dispatch: TypeDispatchConfig | None = Field(
492
+ default=None,
493
+ description="Optional SMT315 match/case preference for same-subject isinstance chains. Closest package policy wins; no automatic rewrite.",
494
+ )
495
+ rules: dict[str, SeverityName] = Field(
496
+ default_factory=dict,
497
+ description="Rule severities for production findings in this package. Use the same problem names or SMT codes as top-level rules; the closest package override wins. Options alone do not enable public-definitions-first.",
498
+ )
499
+
500
+ @field_validator("match")
501
+ @classmethod
502
+ def _package_pattern(cls, value: str) -> str:
503
+ if any(
504
+ segment != "*" and not _DOTTED_NAME.fullmatch(segment)
505
+ for segment in value.split(".")
506
+ ):
507
+ raise ValueError(
508
+ "must be a dotted package pattern with whole-segment * wildcards"
509
+ )
510
+ return value
511
+
512
+ @field_validator("required")
513
+ @classmethod
514
+ def _required_modules(cls, values: list[str]) -> list[str]:
515
+ return list(dict.fromkeys(_check_dotted(values)))
516
+
517
+ @field_validator("public")
518
+ @classmethod
519
+ def _public_modules(cls, values: list[str] | None) -> list[str] | None:
520
+ if values is None:
521
+ return None
522
+ for value in values:
523
+ if value == ".":
524
+ continue
525
+ if any(
526
+ segment not in ("*", "**") and not _DOTTED_NAME.fullmatch(segment)
527
+ for segment in value.split(".")
528
+ ):
529
+ raise ValueError(
530
+ "public entries must be relative dotted module patterns or '.'"
531
+ )
532
+ return list(dict.fromkeys(values))
533
+
534
+ @model_validator(mode="after")
535
+ def _has_contract(self) -> Self:
536
+ if (
537
+ not self.required
538
+ and self.public is None
539
+ and self.imports is None
540
+ and self.bundle_imports_at is None
541
+ and self.module_docstrings is None
542
+ and self.future_annotations is None
543
+ and self.private_modules is None
544
+ and self.ordering is None
545
+ and self.type_dispatch is None
546
+ and not self.rules
547
+ ):
548
+ raise ValueError("set at least one package contract policy")
549
+ return self
550
+
551
+
552
+ class StructureConfig(_Model):
553
+ """Naming rules for packages and modules."""
554
+
555
+ forbidden_names: list[str] = Field(
556
+ default_factory=list, description="Package and module names to avoid (SMT302)."
557
+ )
558
+ contracts: dict[str, PackageContract] = Field(
559
+ default_factory=dict,
560
+ description="Named package contracts: required modules and optional public entry points.",
561
+ )
562
+
563
+ @field_validator("contracts")
564
+ @classmethod
565
+ def _contract_names(
566
+ cls, values: dict[str, PackageContract]
567
+ ) -> dict[str, PackageContract]:
568
+ if any(not name.strip() for name in values):
569
+ raise ValueError("contract names must not be empty")
570
+ return values
571
+
572
+
573
+ class TestsConfig(_Model):
574
+ """Test placement and genuine parameters for test analyses."""
575
+
576
+ layout: Literal["mirror", "none"] = Field(
577
+ default="none",
578
+ description="mirror: every test file must mirror a source module.",
579
+ )
580
+ mirror: str = Field(
581
+ default="{path}/test_{module}.py",
582
+ description="Test path relative to the test root; placeholders {root}, {path}, {module}.",
583
+ )
584
+ unmirrored: list[str] = Field(
585
+ default_factory=list,
586
+ description='Test path globs exempt from mirroring, e.g. ["tests/e2e/**"].',
587
+ )
588
+ mirror_suffixes: bool = Field(
589
+ default=False, description="Also allow test_<module>_<topic>.py."
590
+ )
591
+ quality_exclude: list[str] = Field(
592
+ default_factory=list,
593
+ description="Project-relative globs excluded from test-quality checks, independently of test mirroring.",
594
+ )
595
+ forbid_mocks_in: list[str] = Field(
596
+ default_factory=list,
597
+ description="Project-relative test globs forbidding recognized unittest.mock, pytest-mock and MonkeyPatch attribute replacement, including fixtures (SMT421). Environment/mapping setup is not counted as MonkeyPatch mocking.",
598
+ )
599
+ max_patches_per_test: int | None = Field(
600
+ default=None,
601
+ ge=0,
602
+ description="Maximum recognized patch calls per collected test, including decorators (SMT423). Nested helpers and fixtures are not attributed to callers.",
603
+ )
604
+ assertion_helpers: list[str] = Field(
605
+ default_factory=list,
606
+ description="Qualified callable names accepted as assertion evidence, e.g. tests.assertions.assert_user.",
607
+ )
608
+ timeout_helpers: list[str] = Field(
609
+ default_factory=list,
610
+ description="Qualified context/wrapper helpers known to bound async waits, e.g. tests.timing.deadline. They do not supply assertion evidence or bound synchronous subprocess calls.",
611
+ )
612
+
613
+ @field_validator("quality_exclude", "forbid_mocks_in")
614
+ @classmethod
615
+ def _quality_patterns(cls, values: list[str]) -> list[str]:
616
+ result: list[str] = []
617
+ for value in values:
618
+ pattern = value.strip().replace("\\", "/")
619
+ if (
620
+ not pattern
621
+ or pattern.startswith("/")
622
+ or re.match(r"^[A-Za-z]:", pattern)
623
+ or ".." in pattern.split("/")
624
+ ):
625
+ raise ValueError(
626
+ "test quality globs must be nonempty project-relative paths without '..'"
627
+ )
628
+ result.append(posixpath.normpath(pattern))
629
+ return list(dict.fromkeys(result))
630
+
631
+ @field_validator("assertion_helpers", "timeout_helpers")
632
+ @classmethod
633
+ def _assertion_helpers(cls, values: list[str]) -> list[str]:
634
+ return _check_dotted(values)
635
+
636
+ @field_validator("mirror")
637
+ @classmethod
638
+ def _mirror_is_a_file_pattern(cls, value: str) -> str:
639
+ unknown = set(re.findall(r"\{[^}]*\}", value)) - {
640
+ "{path}",
641
+ "{module}",
642
+ "{root}",
643
+ }
644
+ if unknown:
645
+ msg = f'mirror "{value}" has unknown placeholders: {", ".join(sorted(unknown))}'
646
+ raise ValueError(msg)
647
+ if value.count("{module}") != 1 or not value.endswith(".py"):
648
+ msg = f'mirror "{value}" needs one "{{module}}" and must end with ".py"'
649
+ raise ValueError(msg)
650
+ if (
651
+ value.startswith("/")
652
+ or value.count("{path}") > 1
653
+ or value.count("{root}") > 1
654
+ ):
655
+ msg = f'mirror "{value}" must be relative, with {{path}} and {{root}} at most once'
656
+ raise ValueError(msg)
657
+ return value
658
+
659
+
660
+ class IgnoreEntry(_Model):
661
+ rule: str
662
+ modules: list[str] = Field(default_factory=list)
663
+ paths: list[str] = Field(default_factory=list)
664
+ reason: str
665
+
666
+ @model_validator(mode="after")
667
+ def _has_scope(self) -> Self:
668
+ if not self.modules and not self.paths:
669
+ msg = "an ignore entry needs `modules` or `paths`"
670
+ raise ValueError(msg)
671
+ if not self.reason.strip():
672
+ msg = "`reason` must not be empty"
673
+ raise ValueError(msg)
674
+ return self
675
+
676
+
677
+ class SuppressionsConfig(_Model):
678
+ """Inline `# smelt: ignore[CODE] -- reason` comments."""
679
+
680
+ require_reason: bool = True
681
+
682
+
683
+ class SmeltConfig(_Model):
684
+ version: Literal[1]
685
+ project: ProjectConfig
686
+ architecture: ArchitectureConfig = Field(default_factory=ArchitectureConfig)
687
+ structure: StructureConfig = Field(default_factory=StructureConfig)
688
+ tests: TestsConfig = Field(default_factory=TestsConfig)
689
+ rules: dict[str, SeverityName] = Field(
690
+ default_factory=dict,
691
+ description="Explicit checks by problem name or stable SMT code. A severity enables the check; off disables it. No additional boolean switch is required for fixed-pattern rules.",
692
+ )
693
+ ignore: list[IgnoreEntry] = Field(
694
+ default_factory=list, description="Rules to skip for modules or paths."
695
+ )
696
+ suppressions: SuppressionsConfig = Field(
697
+ default_factory=SuppressionsConfig,
698
+ description="Inline `# smelt: ignore` rules.",
699
+ )
700
+ debt: str | None = Field(
701
+ default=None,
702
+ description="Debt file with known violations, e.g. .smelt/debt.json.",
703
+ )
704
+
705
+ @field_validator("rules")
706
+ @classmethod
707
+ def _rule_codes_are_well_formed(
708
+ cls, values: dict[str, SeverityName]
709
+ ) -> dict[str, SeverityName]:
710
+ for key in values:
711
+ if not (_RULE_CODE.match(key) or _RULE_NAME.match(key)):
712
+ msg = (
713
+ f'"{key}" is not a rule code like "SMT101" '
714
+ 'or a rule name like "layer-boundary"'
715
+ )
716
+ raise ValueError(msg)
717
+ return values