scopeproof 0.1.4__py3-none-any.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.
scopeproof/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """ScopeProof package."""
2
+
3
+ __version__ = "0.1.4"
scopeproof/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ from scopeproof.cli import app
2
+
3
+
4
+ if __name__ == "__main__":
5
+ app()
6
+
@@ -0,0 +1,2 @@
1
+ """ScopeProof checks."""
2
+
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import PurePosixPath
4
+
5
+ from scopeproof.config import ProjectConfig
6
+ from scopeproof.indexer.python_ast import index_python_source
7
+ from scopeproof.models import ChangedFile, FAIL, PASS, CheckIssue, CheckResult, Symbol
8
+ from scopeproof.paths import matches_any
9
+
10
+
11
+ def result_from_issues(
12
+ *,
13
+ check_id: str,
14
+ title: str,
15
+ pass_summary: str,
16
+ issue_summary: str,
17
+ issues: list[CheckIssue],
18
+ fail_enabled: bool,
19
+ ) -> CheckResult:
20
+ if not issues:
21
+ return CheckResult(check_id, title, PASS, pass_summary, [])
22
+ severity = FAIL if fail_enabled else "WARN"
23
+ normalized = [
24
+ CheckIssue(
25
+ severity=severity,
26
+ message=issue.message,
27
+ path=issue.path,
28
+ line=issue.line,
29
+ suggestion=issue.suggestion,
30
+ evidence=issue.evidence,
31
+ )
32
+ for issue in issues
33
+ ]
34
+ return CheckResult(check_id, title, severity, issue_summary, normalized)
35
+
36
+
37
+ def is_project_excluded(path: str, config: ProjectConfig) -> bool:
38
+ return matches_any(path, config.paths.exclude)
39
+
40
+
41
+ def is_support_file(path: str) -> bool:
42
+ return (
43
+ path.startswith("tests/")
44
+ or path.startswith("docs/")
45
+ or path == "README.md"
46
+ or path.endswith(".md")
47
+ )
48
+
49
+
50
+ def is_production_python_file(path: str) -> bool:
51
+ name = PurePosixPath(path).name
52
+ return (
53
+ path.endswith(".py")
54
+ and not path.startswith("tests/")
55
+ and not path.startswith("docs/")
56
+ and name not in {"setup.py", "conftest.py", "__init__.py"}
57
+ )
58
+
59
+
60
+ def added_files(changed_files: list[ChangedFile]) -> list[ChangedFile]:
61
+ return [item for item in changed_files if item.status in {"A", "C"}]
62
+
63
+
64
+ def new_public_symbols(
65
+ *,
66
+ changed_files: list[ChangedFile],
67
+ current_symbols: list[Symbol],
68
+ base_symbols: list[Symbol],
69
+ include_tests: bool = True,
70
+ ) -> list[Symbol]:
71
+ changed_by_path = {item.path: item for item in changed_files if item.path.endswith(".py")}
72
+ base_keys = {
73
+ (symbol.path, symbol.kind, symbol.name, symbol.parent)
74
+ for symbol in base_symbols
75
+ if symbol.is_public
76
+ }
77
+ new_symbols = []
78
+ for symbol in current_symbols:
79
+ changed = changed_by_path.get(symbol.path)
80
+ if changed is None or not symbol.is_public:
81
+ continue
82
+ if not include_tests and symbol.path.startswith("tests/"):
83
+ continue
84
+ if changed.status in {"A", "C"}:
85
+ new_symbols.append(symbol)
86
+ continue
87
+ key = (symbol.path, symbol.kind, symbol.name, symbol.parent)
88
+ if key not in base_keys:
89
+ new_symbols.append(symbol)
90
+ return new_symbols
91
+
92
+
93
+ def base_symbols_for_changed_files(
94
+ changed_files: list[ChangedFile],
95
+ base_sources: dict[str, str],
96
+ ) -> list[Symbol]:
97
+ symbols: list[Symbol] = []
98
+ for changed in changed_files:
99
+ source = base_sources.get(changed.path)
100
+ if not source or not changed.path.endswith(".py"):
101
+ continue
102
+ file_symbols, _ = index_python_source(source, changed.path)
103
+ symbols.extend(file_symbols)
104
+ return symbols
105
+
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from scopeproof.checks.base import is_project_excluded, result_from_issues
4
+ from scopeproof.config import ProjectConfig
5
+ from scopeproof.models import ChangedFile, CheckIssue
6
+
7
+
8
+ def check_changed_file_growth(
9
+ changed_files: list[ChangedFile],
10
+ config: ProjectConfig,
11
+ ) -> object:
12
+ counted_files = [
13
+ changed for changed in changed_files if not is_project_excluded(changed.path, config)
14
+ ]
15
+ limit = config.rules.max_changed_files_per_task
16
+ issues: list[CheckIssue] = []
17
+ if len(counted_files) > limit:
18
+ issues.append(
19
+ CheckIssue(
20
+ severity="WARN",
21
+ message=f"This task changed {len(counted_files)} files; configured limit is {limit}.",
22
+ suggestion="Reduce file churn, or split the task into smaller focused changes.",
23
+ evidence={"changed_files": [item.path for item in counted_files]},
24
+ )
25
+ )
26
+
27
+ return result_from_issues(
28
+ check_id="changed_file_growth",
29
+ title="Changed file growth",
30
+ pass_summary="Changed file count is within the configured limit.",
31
+ issue_summary=f"{len(issues)} changed-file growth issue(s) detected.",
32
+ issues=issues,
33
+ fail_enabled=config.rules.fail_on_changed_file_growth,
34
+ )
35
+
@@ -0,0 +1,92 @@
1
+ from __future__ import annotations
2
+
3
+ from scopeproof.checks.base import new_public_symbols, result_from_issues
4
+ from scopeproof.config import ProjectConfig
5
+ from scopeproof.indexer.symbols import (
6
+ compatible_kinds,
7
+ normalize_symbol_name,
8
+ symbol_similarity,
9
+ token_overlap_ratio,
10
+ )
11
+ from scopeproof.models import ChangedFile, CheckIssue, Symbol
12
+
13
+
14
+ def _is_duplicate_candidate(new_symbol: Symbol, existing: Symbol, threshold: float) -> tuple[bool, float]:
15
+ if not compatible_kinds(new_symbol, existing):
16
+ return False, 0.0
17
+ left = normalize_symbol_name(new_symbol.name)
18
+ right = normalize_symbol_name(existing.name)
19
+ similarity = symbol_similarity(new_symbol, existing)
20
+ substring_match = (
21
+ (left in right or right in left)
22
+ and min(len(left), len(right)) >= 4
23
+ and abs(len(left) - len(right)) <= 12
24
+ )
25
+ overlap_match = token_overlap_ratio(left, right) >= 0.75 and len(set(left.split())) >= 2
26
+ return similarity >= threshold or substring_match or overlap_match, similarity
27
+
28
+
29
+ def check_duplicate_symbol(
30
+ changed_files: list[ChangedFile],
31
+ current_symbols: list[Symbol],
32
+ base_symbols: list[Symbol],
33
+ config: ProjectConfig,
34
+ ) -> object:
35
+ issues: list[CheckIssue] = []
36
+ new_symbols = new_public_symbols(
37
+ changed_files=changed_files,
38
+ current_symbols=current_symbols,
39
+ base_symbols=base_symbols,
40
+ include_tests=False,
41
+ )
42
+ new_keys = {(symbol.path, symbol.kind, symbol.name, symbol.parent) for symbol in new_symbols}
43
+ existing_symbols = [
44
+ symbol
45
+ for symbol in current_symbols
46
+ if symbol.is_public
47
+ and not symbol.path.startswith("tests/")
48
+ and (symbol.path, symbol.kind, symbol.name, symbol.parent) not in new_keys
49
+ ]
50
+
51
+ for new_symbol in new_symbols:
52
+ best: tuple[Symbol, float] | None = None
53
+ for existing in existing_symbols:
54
+ is_candidate, similarity = _is_duplicate_candidate(
55
+ new_symbol,
56
+ existing,
57
+ config.rules.duplicate_symbol_similarity,
58
+ )
59
+ if is_candidate and (best is None or similarity > best[1]):
60
+ best = (existing, similarity)
61
+ if best is None:
62
+ continue
63
+ existing, similarity = best
64
+ issues.append(
65
+ CheckIssue(
66
+ severity="WARN",
67
+ message=(
68
+ f"New {new_symbol.kind} {new_symbol.name} is similar to existing "
69
+ f"{existing.kind} {existing.name}."
70
+ ),
71
+ path=new_symbol.path,
72
+ line=new_symbol.line,
73
+ suggestion=(
74
+ f"Extend the existing {existing.name} {existing.kind} unless a separate "
75
+ "abstraction is intentionally required."
76
+ ),
77
+ evidence={
78
+ "similarity": round(similarity, 3),
79
+ "existing_path": existing.path,
80
+ "existing_line": existing.line,
81
+ },
82
+ )
83
+ )
84
+
85
+ return result_from_issues(
86
+ check_id="duplicate_symbol",
87
+ title="Duplicate symbol",
88
+ pass_summary="No duplicate-looking public symbols detected.",
89
+ issue_summary=f"{len(issues)} duplicate-looking symbol(s) detected.",
90
+ issues=issues,
91
+ fail_enabled=config.rules.fail_on_duplicate_symbol,
92
+ )
@@ -0,0 +1,163 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import PurePosixPath
4
+
5
+ from scopeproof.checks.base import (
6
+ added_files,
7
+ is_production_python_file,
8
+ is_project_excluded,
9
+ result_from_issues,
10
+ )
11
+ from scopeproof.config import ExtensionPoint, ProjectConfig, TaskConfig
12
+ from scopeproof.models import ChangedFile, CheckIssue
13
+ from scopeproof.paths import matches_any
14
+
15
+ SUSPICIOUS_MODULE_WORDS = (
16
+ "service",
17
+ "manager",
18
+ "helper",
19
+ "utils",
20
+ "util",
21
+ "new",
22
+ "v2",
23
+ "legacy",
24
+ )
25
+
26
+
27
+ def _matching_extension_points(goal: str, extension_points: list[ExtensionPoint]) -> list[ExtensionPoint]:
28
+ normalized_goal = goal.casefold()
29
+ if not normalized_goal:
30
+ return []
31
+ return [
32
+ point
33
+ for point in extension_points
34
+ if any(keyword.casefold() in normalized_goal for keyword in point.keywords)
35
+ ]
36
+
37
+
38
+ def _has_changed_adr(changed_files: list[ChangedFile], config: ProjectConfig) -> bool:
39
+ return any(matches_any(changed.path, config.rules.adr_paths) for changed in changed_files)
40
+
41
+
42
+ def _is_suspicious_module(path: str) -> bool:
43
+ name = PurePosixPath(path).stem.casefold()
44
+ return any(word in name for word in SUSPICIOUS_MODULE_WORDS)
45
+
46
+
47
+ def _is_modify_only(task: TaskConfig) -> bool:
48
+ if task.expected_change_type and task.expected_change_type.casefold() in {
49
+ "modify-only",
50
+ "modify_only",
51
+ }:
52
+ return True
53
+ return any("modify-only" in item.casefold() for item in task.expected_behavior)
54
+
55
+
56
+ def check_module_sprawl(
57
+ changed_files: list[ChangedFile],
58
+ config: ProjectConfig,
59
+ task: TaskConfig,
60
+ ) -> object:
61
+ issues: list[CheckIssue] = []
62
+ relevant_changed = [
63
+ changed for changed in changed_files if not is_project_excluded(changed.path, config)
64
+ ]
65
+ added = added_files(relevant_changed)
66
+ production_added = [
67
+ changed for changed in added if is_production_python_file(changed.path)
68
+ ]
69
+
70
+ if len(added) > config.rules.max_new_files_per_task:
71
+ issues.append(
72
+ CheckIssue(
73
+ severity="WARN",
74
+ message=(
75
+ f"This task added {len(added)} files; configured limit is "
76
+ f"{config.rules.max_new_files_per_task}."
77
+ ),
78
+ suggestion="Reduce new file count or split the task into smaller changes.",
79
+ evidence={"added_files": [item.path for item in added]},
80
+ )
81
+ )
82
+
83
+ matched_points = _matching_extension_points(task.goal, config.extension_points)
84
+ modify_only = _is_modify_only(task)
85
+ for point in matched_points:
86
+ for changed in production_added:
87
+ allowed_under_extension = not point.allow_new_files_under or matches_any(
88
+ changed.path,
89
+ point.allow_new_files_under,
90
+ )
91
+ if not allowed_under_extension:
92
+ issues.append(
93
+ CheckIssue(
94
+ severity="WARN",
95
+ message=(
96
+ f'New file {changed.path} was added, but task goal matches '
97
+ f'extension point "{point.name}".'
98
+ ),
99
+ path=changed.path,
100
+ suggestion=(
101
+ "Extend the existing extension point unless this new module is "
102
+ "intentional. If intentional, add an ADR under docs/adr/."
103
+ ),
104
+ evidence={
105
+ "extension_point": point.name,
106
+ "allow_new_files_under": point.allow_new_files_under,
107
+ },
108
+ )
109
+ )
110
+ if point.prefer_existing_paths and task.prefer_modify and (
111
+ modify_only or not allowed_under_extension
112
+ ):
113
+ issues.append(
114
+ CheckIssue(
115
+ severity="WARN",
116
+ message=(
117
+ f'New production module was added while extension point "{point.name}" '
118
+ "has preferred files to modify."
119
+ ),
120
+ path=changed.path,
121
+ suggestion="Prefer extending the existing interface before creating a new module.",
122
+ evidence={
123
+ "prefer_existing_paths": point.prefer_existing_paths,
124
+ "prefer_modify": task.prefer_modify,
125
+ "modify_only": modify_only,
126
+ },
127
+ )
128
+ )
129
+
130
+ has_adr = _has_changed_adr(relevant_changed, config)
131
+ for changed in production_added:
132
+ if _is_suspicious_module(changed.path) and not has_adr:
133
+ issues.append(
134
+ CheckIssue(
135
+ severity="WARN",
136
+ message="Suspicious new production module name added without an ADR.",
137
+ path=changed.path,
138
+ suggestion=(
139
+ "Extend an existing abstraction, rename the module to its concrete role, "
140
+ "or add an ADR if the new abstraction is intentional."
141
+ ),
142
+ evidence={"suspicious_words": list(SUSPICIOUS_MODULE_WORDS)},
143
+ )
144
+ )
145
+
146
+ if config.rules.require_adr_for_new_module and production_added and not has_adr:
147
+ issues.append(
148
+ CheckIssue(
149
+ severity="WARN",
150
+ message="A new production module was added but no ADR changed.",
151
+ suggestion="Add an ADR under the configured ADR paths if this module is intentional.",
152
+ evidence={"adr_paths": config.rules.adr_paths},
153
+ )
154
+ )
155
+
156
+ return result_from_issues(
157
+ check_id="module_sprawl",
158
+ title="Module sprawl",
159
+ pass_summary="No module sprawl detected.",
160
+ issue_summary=f"{len(issues)} potential needless module/new-file issue(s) detected.",
161
+ issues=issues,
162
+ fail_enabled=config.rules.fail_on_module_sprawl,
163
+ )
@@ -0,0 +1,104 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path, PurePosixPath
4
+
5
+ from scopeproof.checks.base import added_files, is_production_python_file, result_from_issues
6
+ from scopeproof.models import ChangedFile, CheckIssue, ImportEdge, Symbol
7
+
8
+ ENTRYPOINT_NAMES = {"cli.py", "__main__.py", "main.py", "__init__.py"}
9
+
10
+
11
+ def _module_suffixes(path: str) -> list[str]:
12
+ without_suffix = PurePosixPath(path).with_suffix("")
13
+ parts = list(without_suffix.parts)
14
+ if parts and parts[0] == "src":
15
+ parts = parts[1:]
16
+ modules = [".".join(parts[index:]) for index in range(len(parts))]
17
+ return [module for module in modules if module]
18
+
19
+
20
+ def _import_references_file(path: str, imports: list[ImportEdge]) -> bool:
21
+ suffixes = _module_suffixes(path)
22
+ for edge in imports:
23
+ if edge.importer_path == path:
24
+ continue
25
+ imported = edge.imported_module.lstrip(".")
26
+ if any(imported == suffix or imported.endswith(f".{suffix}") for suffix in suffixes):
27
+ return True
28
+ if edge.imported_name and edge.imported_name in {suffix.split(".")[-1] for suffix in suffixes}:
29
+ return True
30
+ return False
31
+
32
+
33
+ def _test_references_file(
34
+ repo_root: Path,
35
+ path: str,
36
+ symbols: list[Symbol],
37
+ test_sources: dict[str, str] | None,
38
+ ) -> bool:
39
+ module_names = {suffix.split(".")[-1] for suffix in _module_suffixes(path)}
40
+ symbol_names = {
41
+ symbol.name
42
+ for symbol in symbols
43
+ if symbol.path == path and symbol.is_public and symbol.kind != "method"
44
+ }
45
+ needles = module_names | symbol_names
46
+ if not needles:
47
+ return False
48
+ if test_sources is None:
49
+ sources = {}
50
+ for test_path in repo_root.rglob("tests/**/*.py"):
51
+ try:
52
+ sources[str(test_path.relative_to(repo_root)).replace("\\", "/")] = (
53
+ test_path.read_text(encoding="utf-8")
54
+ )
55
+ except UnicodeDecodeError:
56
+ continue
57
+ else:
58
+ sources = {
59
+ source_path: source
60
+ for source_path, source in test_sources.items()
61
+ if source_path.startswith("tests/") and source_path.endswith(".py")
62
+ }
63
+ for source in sources.values():
64
+ if any(needle in source for needle in needles):
65
+ return True
66
+ return False
67
+
68
+
69
+ def check_orphan_new_file(
70
+ changed_files: list[ChangedFile],
71
+ imports: list[ImportEdge],
72
+ current_symbols: list[Symbol],
73
+ repo_root: Path,
74
+ fail_enabled: bool,
75
+ test_sources: dict[str, str] | None = None,
76
+ ) -> object:
77
+ issues: list[CheckIssue] = []
78
+ for changed in added_files(changed_files):
79
+ if not is_production_python_file(changed.path):
80
+ continue
81
+ if PurePosixPath(changed.path).name in ENTRYPOINT_NAMES:
82
+ continue
83
+ if _import_references_file(changed.path, imports):
84
+ continue
85
+ if _test_references_file(repo_root, changed.path, current_symbols, test_sources):
86
+ continue
87
+ issues.append(
88
+ CheckIssue(
89
+ severity="WARN",
90
+ message="New production Python file is not imported or referenced by tests.",
91
+ path=changed.path,
92
+ suggestion="Wire the file into the package, add tests that use it, or remove it.",
93
+ evidence={"module_suffixes": _module_suffixes(changed.path)},
94
+ )
95
+ )
96
+
97
+ return result_from_issues(
98
+ check_id="orphan_new_file",
99
+ title="Orphan new file",
100
+ pass_summary="No orphan new production files detected.",
101
+ issue_summary=f"{len(issues)} orphan new production file(s) detected.",
102
+ issues=issues,
103
+ fail_enabled=fail_enabled,
104
+ )
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ from pathlib import Path
5
+
6
+ from scopeproof.models import ChangedFile, CheckIssue, CheckResult, FAIL, PASS
7
+
8
+
9
+ def check_parse_error(
10
+ changed_files: list[ChangedFile],
11
+ repo_root: Path,
12
+ sources: dict[str, str] | None = None,
13
+ ) -> CheckResult:
14
+ issues: list[CheckIssue] = []
15
+ for changed in changed_files:
16
+ if not changed.path.endswith(".py") or changed.status == "D":
17
+ continue
18
+ source = sources.get(changed.path) if sources is not None else None
19
+ path = repo_root / changed.path
20
+ if source is None:
21
+ if not path.exists():
22
+ continue
23
+ try:
24
+ source = path.read_text(encoding="utf-8")
25
+ except UnicodeDecodeError as exc:
26
+ issues.append(
27
+ CheckIssue(
28
+ severity=FAIL,
29
+ message=f"Could not decode Python file as UTF-8: {exc.reason}",
30
+ path=changed.path,
31
+ suggestion="Save the file as UTF-8 or exclude it from Python analysis.",
32
+ )
33
+ )
34
+ continue
35
+ try:
36
+ ast.parse(source)
37
+ except SyntaxError as exc:
38
+ issues.append(
39
+ CheckIssue(
40
+ severity=FAIL,
41
+ message=f"Python syntax error: {exc.msg}",
42
+ path=changed.path,
43
+ line=exc.lineno,
44
+ suggestion="Fix the syntax error before relying on symbol-level checks.",
45
+ evidence={"offset": exc.offset, "text": exc.text.strip() if exc.text else None},
46
+ )
47
+ )
48
+
49
+ if not issues:
50
+ return CheckResult(
51
+ "parse_error",
52
+ "Parse error",
53
+ PASS,
54
+ "Changed Python files parsed successfully.",
55
+ [],
56
+ )
57
+ return CheckResult(
58
+ "parse_error",
59
+ "Parse error",
60
+ FAIL,
61
+ f"{len(issues)} changed Python file(s) could not be parsed.",
62
+ issues,
63
+ )
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from scopeproof.checks.base import new_public_symbols, result_from_issues
4
+ from scopeproof.config import ProjectConfig
5
+ from scopeproof.models import ChangedFile, CheckIssue, Symbol
6
+
7
+
8
+ def check_public_api_growth(
9
+ changed_files: list[ChangedFile],
10
+ current_symbols: list[Symbol],
11
+ base_symbols: list[Symbol],
12
+ config: ProjectConfig,
13
+ ) -> object:
14
+ new_symbols = new_public_symbols(
15
+ changed_files=changed_files,
16
+ current_symbols=current_symbols,
17
+ base_symbols=base_symbols,
18
+ include_tests=False,
19
+ )
20
+ issues: list[CheckIssue] = []
21
+ limit = config.rules.max_new_public_symbols_per_task
22
+ if len(new_symbols) > limit:
23
+ issues.append(
24
+ CheckIssue(
25
+ severity="WARN",
26
+ message=f"This task added {len(new_symbols)} public symbols; configured limit is {limit}.",
27
+ suggestion=(
28
+ "Reduce public API growth. Prefer private helpers, extend existing abstractions, "
29
+ "or split the task into smaller changes."
30
+ ),
31
+ evidence={"new_symbols": [f"{symbol.path}::{symbol.name}" for symbol in new_symbols]},
32
+ )
33
+ )
34
+
35
+ return result_from_issues(
36
+ check_id="public_api_growth",
37
+ title="Public API growth",
38
+ pass_summary="Public API growth is within the configured limit.",
39
+ issue_summary=f"{len(issues)} public API growth issue(s) detected.",
40
+ issues=issues,
41
+ fail_enabled=config.rules.fail_on_public_api_growth,
42
+ )
43
+