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,630 @@
1
+ from __future__ import annotations
2
+
3
+ import textwrap
4
+ from dataclasses import dataclass, field
5
+ from pathlib import PurePosixPath
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from smelt.analysis.coverage import is_governed
9
+ from smelt.config.errors import did_you_mean
10
+ from smelt.config.loader import LoadedConfig
11
+ from smelt.config.patterns import module_matches
12
+ from smelt.diagnostics.violation import Severity
13
+ from smelt.engine.coverage import policy_hash
14
+ from smelt.engine.rule_settings import RuleSettings
15
+ from smelt.model import ModuleKind, is_within
16
+ from smelt.rules.registry import build_rule_set
17
+ from smelt.rules.testing.location import mirror_path
18
+
19
+ if TYPE_CHECKING:
20
+ from smelt.analysis.context import AnalysisContext
21
+ from smelt.config.models import ThirdPartyPolicy
22
+ from smelt.diagnostics.report import Report
23
+ from smelt.model import ArchitectureModel, ModuleInfo
24
+
25
+
26
+ class TargetError(ValueError):
27
+ pass
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Target:
32
+ kind: str # project | feature | module | package
33
+ feature: str | None = None
34
+ module: str | None = None
35
+ path: str | None = None
36
+ planned: bool = False
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class LayerBrief:
41
+ name: str
42
+ package: str | None
43
+ may_depend_on: tuple[str, ...]
44
+ third_party: str | None
45
+
46
+ def to_json(self) -> dict[str, Any]:
47
+ return {
48
+ "name": self.name,
49
+ "package": self.package,
50
+ "may_depend_on": list(self.may_depend_on),
51
+ "third_party": self.third_party,
52
+ }
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Briefing:
57
+ target: Target
58
+ package: str | None
59
+ module_kind: ModuleKind | None
60
+ layer: str | None
61
+ features: tuple[str, ...]
62
+ layers: tuple[LayerBrief, ...]
63
+ cross_feature: str | None
64
+ shared: tuple[str, ...]
65
+ composition_root: tuple[str, ...]
66
+ wiring: tuple[str, ...]
67
+ central: bool
68
+ tests: tuple[str, ...]
69
+ is_wiring: bool = False
70
+ boundary_policy: str = ""
71
+ transitive: bool = False
72
+ type_checking: str = "include"
73
+ cycles: tuple[str, ...] = ()
74
+ # cross_feature as fields: default and allow entries, None feature = every feature
75
+ cross_feature_policy: dict[str, Any] | None = None
76
+ policy_hash: str = ""
77
+ analysis_error: str | None = None
78
+ violations: dict[str, int] = field(default_factory=dict)
79
+ violation_codes: tuple[str, ...] = ()
80
+ coverage: dict[str, Any] = field(default_factory=dict)
81
+ contracts: list[dict[str, Any]] = field(default_factory=list)
82
+ import_style: dict[str, Any] | None = None
83
+ header_policy: dict[str, Any] = field(default_factory=dict)
84
+ naming_policy: dict[str, Any] = field(default_factory=dict)
85
+ ordering_policy: dict[str, Any] | None = None
86
+ python_target: dict[str, Any] = field(default_factory=dict)
87
+ test_policy: dict[str, Any] = field(default_factory=dict)
88
+ type_dispatch_policy: dict[str, Any] | None = None
89
+ rules: dict[str, str] = field(default_factory=dict)
90
+
91
+ def to_json(self) -> dict[str, Any]:
92
+ return {
93
+ "schema_version": 1,
94
+ "scope": self.target.kind,
95
+ "feature": self.target.feature,
96
+ "module": self.target.module,
97
+ "path": self.target.path,
98
+ "package": self.package,
99
+ "module_kind": self.module_kind.value if self.module_kind else None,
100
+ "layer": self.layer,
101
+ "central": self.central,
102
+ "is_wiring": self.is_wiring,
103
+ "planned": self.target.planned,
104
+ "boundary_policy": self.boundary_policy,
105
+ "coverage": self.coverage,
106
+ "contracts": self.contracts,
107
+ "import_style": self.import_style,
108
+ "header_policy": self.header_policy,
109
+ "naming_policy": self.naming_policy,
110
+ "ordering_policy": self.ordering_policy,
111
+ "python_target": self.python_target,
112
+ "test_policy": self.test_policy,
113
+ "type_dispatch_policy": self.type_dispatch_policy,
114
+ "rules": self.rules,
115
+ "policy_hash": self.policy_hash,
116
+ "imports": {
117
+ "transitive": self.transitive,
118
+ "type_checking": self.type_checking,
119
+ "cycles": list(self.cycles),
120
+ },
121
+ "features": list(self.features),
122
+ "layers": [layer.to_json() for layer in self.layers],
123
+ "cross_feature": self.cross_feature,
124
+ "cross_feature_policy": self.cross_feature_policy,
125
+ "shared": list(self.shared),
126
+ "composition_root": list(self.composition_root),
127
+ "wiring": list(self.wiring),
128
+ "tests": list(self.tests),
129
+ "violations": None
130
+ if self.analysis_error
131
+ else {**self.violations, "codes": list(self.violation_codes)},
132
+ "analysis_error": self.analysis_error,
133
+ }
134
+
135
+
136
+ def resolve_target(ctx: AnalysisContext, raw: str | None) -> Target:
137
+ """A feature name or a project-relative path (file or directory)."""
138
+ if raw is None or raw.strip("/") in ("", "."):
139
+ return Target("project")
140
+ model = ctx.model
141
+ if raw in model.features:
142
+ return Target("feature", feature=raw)
143
+ path = raw.strip("/")
144
+ files = ctx.files
145
+ module_path = files.path_for_module(raw)
146
+ if module_path is not None:
147
+ path = module_path
148
+ source = files.source_for_path(path)
149
+ if source is not None:
150
+ info = model.info(source.module)
151
+ feature = info.feature if info else None
152
+ return Target("module", feature=feature, module=source.module, path=path)
153
+ for package in files.packages.values():
154
+ if package.path == path:
155
+ info = model.info(package.module)
156
+ feature = info.feature if info else None
157
+ return Target("package", feature, package.module, path)
158
+ inventory = next(
159
+ (
160
+ entry
161
+ for entry in ctx.coverage.entries
162
+ if entry.path == path or entry.module == raw
163
+ ),
164
+ None,
165
+ )
166
+ if inventory is not None:
167
+ return Target("module", module=inventory.module, path=inventory.path)
168
+ planned = PurePosixPath(path)
169
+ if not (ctx.root / path).exists() and planned.suffix == ".py":
170
+ for parent in planned.parents:
171
+ ancestor = next(
172
+ (p for p in files.packages.values() if p.path == str(parent)), None
173
+ )
174
+ if ancestor is None:
175
+ continue
176
+ segments = planned.relative_to(parent).with_suffix("").parts
177
+ if all(segment.isidentifier() for segment in segments):
178
+ module = ".".join((ancestor.module, *segments))
179
+ info = model.info(module)
180
+ return Target(
181
+ "module", info.feature if info else None, module, path, planned=True
182
+ )
183
+ candidates = [*model.features, *(p.path for p in files.packages.values())]
184
+ msg = (
185
+ f'"{raw}" is neither a feature nor a source path{did_you_mean(raw, candidates)}'
186
+ )
187
+ if model.features:
188
+ msg += f"; features: {', '.join(sorted(model.features))}"
189
+ raise TargetError(msg)
190
+
191
+
192
+ def build_briefing(
193
+ ctx: AnalysisContext,
194
+ target: Target,
195
+ report: Report | None,
196
+ *,
197
+ analysis_error: str | None = None,
198
+ ) -> Briefing:
199
+ model = ctx.model
200
+ arch = ctx.config.architecture
201
+ info = model.info(target.module) if target.module else None
202
+ package = None
203
+ if target.feature is not None:
204
+ package = model.feature_package_for(target.feature)
205
+ layers = tuple(
206
+ LayerBrief(
207
+ name,
208
+ model.layer_package(target.feature, name)
209
+ if target.feature is not None or not model.has_features
210
+ else None,
211
+ tuple(layer.may_depend_on),
212
+ _third_party(layer.third_party),
213
+ )
214
+ for name, layer in model.layers.items()
215
+ )
216
+ scoped = (
217
+ [v for v in report.violations if _violation_in(ctx, v.path, target)]
218
+ if report
219
+ else []
220
+ )
221
+ exempt = bool(info and (info.wiring or info.kind is ModuleKind.COMPOSITION_ROOT))
222
+ cross_feature = _cross_feature(model) if model.has_features else None
223
+ coverage = _coverage_brief(ctx, target)
224
+ target_path = target.path or ctx.files.path_for_module(package or "")
225
+ if info and (info.central or info.kind is ModuleKind.SHARED):
226
+ cross_feature = "none (must not import features)"
227
+ elif exempt:
228
+ cross_feature = "allowed (wiring/composition-root exception)"
229
+ return Briefing(
230
+ target=target,
231
+ package=package,
232
+ module_kind=info.kind if info else None,
233
+ layer=info.layer if info else None,
234
+ features=tuple(sorted(model.features)),
235
+ layers=layers,
236
+ cross_feature=cross_feature,
237
+ shared=tuple(arch.shared),
238
+ composition_root=tuple(arch.composition_root),
239
+ wiring=_wiring(ctx, package or target.module),
240
+ central=bool(info and info.central),
241
+ tests=_tests(ctx, target),
242
+ is_wiring=bool(info and info.wiring),
243
+ boundary_policy=_covered_policy(info, coverage),
244
+ transitive=arch.imports.transitive,
245
+ type_checking=arch.imports.type_checking,
246
+ cycles=tuple(arch.imports.cycles),
247
+ cross_feature_policy={
248
+ "default": arch.cross_feature.default,
249
+ "allow": arch.cross_feature.entries(),
250
+ }
251
+ if model.has_features
252
+ else None,
253
+ policy_hash=policy_hash(ctx.config),
254
+ analysis_error=analysis_error,
255
+ violations={
256
+ "errors": sum(v.severity is Severity.ERROR for v in scoped),
257
+ "warnings": sum(v.severity is Severity.WARNING for v in scoped),
258
+ "hints": sum(v.severity is Severity.HINT for v in scoped),
259
+ },
260
+ violation_codes=tuple(sorted({v.code for v in scoped})),
261
+ coverage=coverage,
262
+ contracts=ctx.contracts.describe(target.module or package),
263
+ import_style=ctx.contracts.style_brief(target.module or package),
264
+ header_policy=ctx.contracts.header_brief(target.module or package),
265
+ naming_policy=ctx.contracts.naming_brief(target.module or package),
266
+ ordering_policy=ctx.contracts.ordering_brief(target.module or package),
267
+ test_policy=ctx.config.tests.model_dump(mode="json"),
268
+ type_dispatch_policy=ctx.contracts.dispatch_brief(target.module or package),
269
+ rules=_rule_brief(ctx, target.module or package),
270
+ python_target=ctx.python_targets.for_path(
271
+ ctx.root / target_path if target_path else None
272
+ ).to_json(),
273
+ )
274
+
275
+
276
+ def render_briefing(briefing: Briefing, ctx: AnalysisContext) -> str:
277
+ lines = _header(briefing, ctx)
278
+ lines.append("")
279
+ lines.append(
280
+ textwrap.fill(
281
+ briefing.boundary_policy,
282
+ width=88,
283
+ initial_indent="Policy: ",
284
+ subsequent_indent=" ",
285
+ )
286
+ )
287
+ coverage = briefing.coverage
288
+ lines.append(
289
+ textwrap.fill(
290
+ f"Coverage: {coverage.get('mode', 'configured')}; "
291
+ + (
292
+ f"{coverage['status']}. {coverage.get('reason', '')}"
293
+ if "status" in coverage
294
+ else f"{'complete' if coverage.get('complete') else 'incomplete'} policy assignment for {coverage.get('files', 0)} source files."
295
+ ),
296
+ width=88,
297
+ )
298
+ )
299
+ lines.append(
300
+ "Imports: direct and transitive dependencies checked (layers, features, shared, composition roots, third-party)"
301
+ if briefing.transitive
302
+ else "Imports: direct only (indirect chains require architecture.imports.transitive: true)"
303
+ )
304
+ lines.extend(_contract_lines(briefing))
305
+ lines.append("")
306
+ if briefing.module_kind is ModuleKind.UNCLASSIFIED:
307
+ lines.extend((*_wrap_tests(briefing.tests), "", _violation_line(briefing)))
308
+ return "\n".join(lines) + "\n"
309
+ if briefing.layers:
310
+ lines.extend(_layer_lines(briefing))
311
+ if briefing.cross_feature is not None:
312
+ lines.append(f"Cross-feature: {briefing.cross_feature}")
313
+ if briefing.shared:
314
+ lines.append(
315
+ f"Shared: {', '.join(briefing.shared)} (must not import features)"
316
+ )
317
+ if briefing.composition_root:
318
+ lines.append(f"Composition root: {', '.join(briefing.composition_root)}")
319
+ if briefing.wiring:
320
+ lines.append(f"Wiring: {', '.join(briefing.wiring)}")
321
+ lines.extend(("", *_wrap_tests(briefing.tests), "", _violation_line(briefing)))
322
+ return "\n".join(lines) + "\n"
323
+
324
+
325
+ def _rule_brief(ctx: AnalysisContext, module: str | None) -> dict[str, str]:
326
+ rules = build_rule_set()
327
+ policy = RuleSettings(rules, LoadedConfig(ctx.config, ctx.root / "smelt.yaml"))
328
+ return {
329
+ rule.name: severity.value
330
+ if (severity := policy.severity(rule, ctx, module))
331
+ else "off"
332
+ for rule in rules.rules
333
+ }
334
+
335
+
336
+ def _coverage_brief(ctx: AnalysisContext, target: Target) -> dict[str, Any]:
337
+ mode = ctx.config.project.coverage
338
+ if target.planned:
339
+ governed = is_governed(
340
+ ctx.model.info(target.module or ""), layers_declared=bool(ctx.model.layers)
341
+ )
342
+ return {
343
+ "mode": mode,
344
+ "status": "planned",
345
+ "policy_status": "governed" if governed else "unclassified",
346
+ "reason": "Planned placement; no source has been analyzed at this path yet.",
347
+ }
348
+ if target.path:
349
+ entry = ctx.coverage.for_path(target.path)
350
+ if entry is not None:
351
+ return {"mode": mode, **entry.to_json()}
352
+ entries = [
353
+ entry
354
+ for entry in ctx.coverage.entries
355
+ if target.feature is None or entry.feature == target.feature
356
+ ]
357
+ return {
358
+ "mode": mode,
359
+ "complete": ctx.coverage.complete
360
+ if target.feature is None
361
+ else all(
362
+ entry.status in ("governed", "facade", "excluded") for entry in entries
363
+ ),
364
+ "files": len(entries),
365
+ }
366
+
367
+
368
+ def _covered_policy(info: ModuleInfo | None, coverage: dict[str, Any]) -> str:
369
+ if coverage.get("status") == "uncovered":
370
+ return "This file is outside the analyzed packages. Select its package and source root, then assign an architecture role before implementing here."
371
+ if coverage.get("status") == "excluded":
372
+ return "This file is explicitly outside the analyzed policy. Review its exclusion reason before using it for new production code."
373
+ if coverage.get("status") == "facade":
374
+ return "Package facade: keep implementation and assembly in classified modules. Named exports retain their providers' restrictions when transitive import checking is enabled."
375
+ if (
376
+ coverage.get("status") == "planned"
377
+ and coverage.get("policy_status") == "unclassified"
378
+ ):
379
+ return "This planned placement has no architecture role. Choose a declared layer or explicitly assign the intended package before implementing here."
380
+ return _boundary_policy(info)
381
+
382
+
383
+ def _violation_in(ctx: AnalysisContext, path: str | None, target: Target) -> bool:
384
+ if path is None:
385
+ return False
386
+ if target.kind == "project":
387
+ return True
388
+ if target.path is not None:
389
+ return path == target.path or path.startswith(f"{target.path}/")
390
+ if target.feature is None:
391
+ return False
392
+ package = ctx.files.packages.get(ctx.model.feature_package_for(target.feature))
393
+ return package is not None and path.startswith(f"{package.path}/")
394
+
395
+
396
+ def _third_party(policy: ThirdPartyPolicy) -> str:
397
+ if policy.default == "deny":
398
+ return f"only {', '.join(policy.allow)}" if policy.allow else "none"
399
+ return f"not {', '.join(policy.deny)}" if policy.deny else "all allowed"
400
+
401
+
402
+ def _boundary_policy(info: ModuleInfo | None) -> str: # noqa: PLR0911
403
+ if info is None:
404
+ return "Layer and feature boundaries apply as configured; wiring and composition roots have exceptions."
405
+ if info.kind is ModuleKind.COMPOSITION_ROOT:
406
+ return "May import across layers and features; ordinary modules must not import the composition root."
407
+ if info.wiring:
408
+ access = (
409
+ "May import across layer boundaries; must not import features. "
410
+ if info.central or info.kind is ModuleKind.SHARED
411
+ else "May import across layers and features. "
412
+ )
413
+ return (
414
+ access + "Third-party policy still applies to assigned layers. "
415
+ "Only composition roots, other wiring modules and its package facade may import wiring."
416
+ )
417
+ if info.kind is ModuleKind.UNCLASSIFIED:
418
+ return (
419
+ "Layer and feature boundaries are not enforced for this module. "
420
+ "Composition-root/wiring import restrictions (SMT106) and configured cycle checks (SMT104) still apply. "
421
+ "Give its package a layer under architecture.modules, or list it in shared or composition_root."
422
+ )
423
+ if info.central:
424
+ return "The assigned layer's boundaries apply; central modules must not import features."
425
+ if info.kind is ModuleKind.SHARED:
426
+ return "Shared modules must not import features; composition-root/wiring restrictions and cycle checks still apply."
427
+ return "Layer, cross-feature and composition-root/wiring restrictions apply as configured."
428
+
429
+
430
+ def _cross_feature(model: ArchitectureModel) -> str:
431
+ cross = model.config.architecture.cross_feature
432
+ if cross.default == "allow":
433
+ return "allowed"
434
+ pairs = [label.replace(" -> ", " → ") for label in cross.labels()]
435
+ return f"only {', '.join(pairs)}" if pairs else "none"
436
+
437
+
438
+ def _wiring(ctx: AnalysisContext, package: str | None) -> tuple[str, ...]:
439
+ """The wiring patterns that cover modules of ``package`` (all without one)."""
440
+ wiring = ctx.config.architecture.wiring
441
+ if package is None:
442
+ return tuple(wiring)
443
+ modules = [m for m in ctx.files.sources if is_within(m, package)]
444
+ return tuple(p for p in wiring if any(module_matches(p, m) for m in modules))
445
+
446
+
447
+ def _tests(ctx: AnalysisContext, target: Target) -> tuple[str, ...]:
448
+ tests = ctx.config.tests
449
+ if tests.layout != "mirror":
450
+ return ("no layout enforced",)
451
+ source = ctx.files.sources.get(target.module or "")
452
+ if target.module and (
453
+ target.planned or (source is not None and not source.is_package)
454
+ ):
455
+ path = mirror_path(ctx, target.module)
456
+ return (f"mirror at {path}",) if path else ("mirror the source tree",)
457
+ if target.feature is not None:
458
+ package = ctx.model.feature_package_for(target.feature)
459
+ path = mirror_path(ctx, f"{package}.<layer>.<module>")
460
+ if path:
461
+ return (f"mirror at {path}",)
462
+ if target.kind == "package" and target.module:
463
+ path = mirror_path(ctx, f"{target.module}.<module>")
464
+ if path:
465
+ return (f"mirror at {path}",)
466
+ return (f"mirror the source tree ({tests.mirror})",)
467
+
468
+
469
+ def _contract_lines(briefing: Briefing) -> list[str]:
470
+ lines = [
471
+ f"Rule: {name}: {severity}"
472
+ for name, severity in briefing.rules.items()
473
+ if severity != "off"
474
+ ]
475
+ if briefing.type_dispatch_policy:
476
+ policy = briefing.type_dispatch_policy
477
+ lines.append(
478
+ f"Type dispatch: {policy['style']} from {policy['min_branches']} branches ({policy['contract']})"
479
+ )
480
+ if briefing.test_policy:
481
+ policy = briefing.test_policy
482
+ if (
483
+ policy.get("forbid_mocks_in")
484
+ or policy.get("max_patches_per_test") is not None
485
+ ):
486
+ lines.append(
487
+ f"Test quality: path/patch policies; mocks forbidden in {policy['forbid_mocks_in']}; maximum patches {policy['max_patches_per_test']}; excluded {policy['quality_exclude']}"
488
+ )
489
+ if briefing.ordering_policy:
490
+ policy = briefing.ordering_policy
491
+ lines.append(
492
+ f"Definition ordering options ({policy['contract']}); module: {', '.join(policy['module'])}; class: {', '.join(policy['class'])}"
493
+ )
494
+ minimum = briefing.python_target.get("minimum")
495
+ if minimum:
496
+ lines.append(f"Minimum Python: {minimum} ({briefing.python_target['source']})")
497
+ for contract in briefing.contracts:
498
+ required = ", ".join(contract["required"]) or "none"
499
+ public = contract["public"]
500
+ entry_points = (
501
+ "unrestricted"
502
+ if public is None
503
+ else ", ".join(public) or "none (private package)"
504
+ )
505
+ lines.append(f"Contract {contract['name']} ({contract['package']}):")
506
+ lines.append(f" Required: {required}")
507
+ lines.append(f" Public: {entry_points}")
508
+ if "imports" in contract:
509
+ style = contract["imports"]
510
+ lines.append(
511
+ f" Import style: {style['style']}; maximum relative level {style['max_relative_level']}"
512
+ )
513
+ if contract["target_public"] is not None:
514
+ visibility = "public" if contract["target_public"] else "private"
515
+ lines.append(
516
+ f" Target: {visibility} to callers outside {contract['package']}"
517
+ )
518
+ missing = sorted(set(contract["missing"] + contract["missing_public"]))
519
+ if missing:
520
+ lines.append(f" Missing: {', '.join(missing)}")
521
+ if "bundle_imports_at" in contract:
522
+ lines.append(
523
+ f" Bundling hint: from {contract['bundle_imports_at']} distinct modules per outside caller"
524
+ )
525
+ lines.extend(
526
+ f" {key}: {contract[key]}"
527
+ for key in ("module_docstrings", "future_annotations", "private_modules")
528
+ if key in contract
529
+ )
530
+ if briefing.import_style:
531
+ style = briefing.import_style
532
+ lines.append(
533
+ f"Import style: {style['style']}, maximum relative level {style['max_relative_level']} ({style['contract']})"
534
+ )
535
+ return lines
536
+
537
+
538
+ def _header(briefing: Briefing, ctx: AnalysisContext) -> list[str]:
539
+ target = briefing.target
540
+ lines: list[str] = []
541
+ match target.kind:
542
+ case "feature":
543
+ lines.append(f"Feature: {target.feature} ({briefing.package})")
544
+ case "project":
545
+ roots = ", ".join(ctx.config.project.root_packages)
546
+ lines.append(f"Project: {roots}")
547
+ if briefing.features:
548
+ lines.append(f"Features: {', '.join(briefing.features)}")
549
+ case _:
550
+ planned = " [planned]" if target.planned else ""
551
+ lines.append(f"Module: {target.module} ({target.path}){planned}")
552
+ lines.append(_placement(briefing))
553
+ return lines
554
+
555
+
556
+ def _placement(briefing: Briefing) -> str:
557
+ match briefing.module_kind:
558
+ case ModuleKind.SHARED:
559
+ return "Kind: shared (importable by all features, must not import features)"
560
+ case ModuleKind.COMPOSITION_ROOT:
561
+ return "Kind: composition root (wires concrete implementations)"
562
+ case ModuleKind.FEATURE if briefing.central:
563
+ return (
564
+ f"Kind: central module in layer {briefing.layer} "
565
+ "(outside the features, must not import them)"
566
+ )
567
+ case ModuleKind.FEATURE if briefing.layer is not None:
568
+ feature = briefing.target.feature
569
+ where = f"feature {feature}, " if feature else ""
570
+ return f"Kind: {where}layer {briefing.layer}"
571
+ case ModuleKind.FEATURE:
572
+ return f"Kind: feature {briefing.target.feature}, outside any layer"
573
+ case _:
574
+ return "Kind: unclassified (outside features, layers, shared and composition root)"
575
+
576
+
577
+ def _layer_lines(briefing: Briefing) -> list[str]:
578
+ name_width = max(len(layer.name) for layer in briefing.layers) + 2
579
+ deps = {
580
+ layer.name: " → " + (", ".join(layer.may_depend_on) or "(nothing)")
581
+ for layer in briefing.layers
582
+ }
583
+ dep_width = max(len(text) for text in deps.values()) + 2
584
+ exempt = briefing.is_wiring or briefing.module_kind is ModuleKind.COMPOSITION_ROOT
585
+ lines = [
586
+ "Layers (project defaults; this module may cross layer boundaries):"
587
+ if exempt
588
+ else "Layers:"
589
+ ]
590
+ for layer in briefing.layers:
591
+ marker = "*" if layer.name == briefing.layer else " "
592
+ row = f" {marker}{layer.name:<{name_width - 2}}{deps[layer.name]}"
593
+ if layer.third_party is not None:
594
+ row = f"{row:<{name_width + dep_width}}third-party: {layer.third_party}"
595
+ lines.append(row.rstrip())
596
+ return lines
597
+
598
+
599
+ def _wrap_tests(parts: tuple[str, ...], width: int = 88) -> list[str]:
600
+ prefix = "Tests: "
601
+ lines: list[str] = []
602
+ current = prefix
603
+ for index, part in enumerate(parts):
604
+ text = part + ("," if index < len(parts) - 1 else "")
605
+ candidate = text if current.strip() in ("", "Tests:") else f" {text}"
606
+ if current != prefix and len(current) + len(candidate) > width:
607
+ lines.append(current)
608
+ current = " " * len(prefix) + text
609
+ else:
610
+ current += text if current == prefix else candidate
611
+ lines.append(current)
612
+ return lines
613
+
614
+
615
+ def _violation_line(briefing: Briefing) -> str:
616
+ if briefing.analysis_error:
617
+ return f"Current violations: unavailable ({briefing.analysis_error})"
618
+ counts = briefing.violations
619
+ parts = [
620
+ f"{count} {label if count == 1 else label + 's'}"
621
+ for label, count in (
622
+ ("error", counts.get("errors", 0)),
623
+ ("warning", counts.get("warnings", 0)),
624
+ ("hint", counts.get("hints", 0)),
625
+ )
626
+ if count
627
+ ]
628
+ if not parts:
629
+ return "Current violations: none"
630
+ return f"Current violations: {', '.join(parts)} ({', '.join(briefing.violation_codes)})"
smelt/engine/cache.py ADDED
@@ -0,0 +1,65 @@
1
+ """Whole-analysis reuse around rule execution, separate from per-file facts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from pydantic import TypeAdapter
9
+
10
+ from smelt.analysis.workspace import workspace_members
11
+ from smelt.diagnostics.violation import Violation # noqa: TC001 - runtime cache schema
12
+
13
+ if TYPE_CHECKING:
14
+ from smelt.analysis.context import AnalysisContext
15
+ from smelt.diagnostics.violation import Severity
16
+ from smelt.rules.base import Rule
17
+
18
+
19
+ @dataclass
20
+ class CachedAnalysis:
21
+ violations: list[Violation]
22
+ suppressed: int
23
+ coverage: dict[str, Any]
24
+ modules: int
25
+ paths: list[str]
26
+ dependencies: dict[str, str] = field(default_factory=dict)
27
+
28
+
29
+ ANALYSIS = TypeAdapter(CachedAnalysis)
30
+
31
+
32
+ def analysis_inputs(
33
+ ctx: AnalysisContext,
34
+ active: list[tuple[Rule, Severity]],
35
+ selection: tuple[str, ...],
36
+ ) -> object:
37
+ """Inventory and contents, including facts that can affect unchanged modules."""
38
+ return [
39
+ ctx.config.model_dump(mode="json"),
40
+ [(rule.code, severity.value) for rule, severity in active],
41
+ selection,
42
+ [
43
+ [
44
+ source.module,
45
+ source.path,
46
+ source.is_package,
47
+ ctx.files.content_id(source.path),
48
+ ctx.python_targets.for_path(source.absolute).to_json(),
49
+ ]
50
+ for source in sorted(
51
+ ctx.files.sources.values(), key=lambda source: source.path
52
+ )
53
+ ],
54
+ [
55
+ [path, test.test_root, ctx.files.content_id(path)]
56
+ for path, test in sorted(ctx.files.tests.items())
57
+ ],
58
+ [
59
+ [name, [(part.path, part.source_root, part.has_init) for part in parts]]
60
+ for name, parts in sorted(ctx.files.package_parts.items())
61
+ ],
62
+ [entry.to_json() for entry in ctx.coverage.entries],
63
+ ctx.coverage.summary(),
64
+ [member.to_json() for member in workspace_members(ctx.root, store=ctx.store)],
65
+ ]