diffguard-ai 0.1.0__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.
Files changed (49) hide show
  1. diffguard/__init__.py +39 -0
  2. diffguard/__main__.py +4 -0
  3. diffguard/baselines/__init__.py +0 -0
  4. diffguard/baselines/manager.py +97 -0
  5. diffguard/cli/__init__.py +1 -0
  6. diffguard/cli/main.py +323 -0
  7. diffguard/core/__init__.py +0 -0
  8. diffguard/core/enums.py +103 -0
  9. diffguard/core/exceptions.py +57 -0
  10. diffguard/core/interfaces.py +20 -0
  11. diffguard/core/models.py +301 -0
  12. diffguard/engine/__init__.py +0 -0
  13. diffguard/engine/evaluator.py +42 -0
  14. diffguard/engine/orchestrator.py +74 -0
  15. diffguard/engine/registry.py +142 -0
  16. diffguard/engine/scanner.py +141 -0
  17. diffguard/git/__init__.py +0 -0
  18. diffguard/git/client.py +179 -0
  19. diffguard/git/diff_parser.py +298 -0
  20. diffguard/git/repository.py +174 -0
  21. diffguard/policies/__init__.py +0 -0
  22. diffguard/policies/loader.py +75 -0
  23. diffguard/policies/schema.py +292 -0
  24. diffguard/py.typed +0 -0
  25. diffguard/reporting/__init__.py +0 -0
  26. diffguard/reporting/json_report.py +104 -0
  27. diffguard/reporting/markdown_report.py +96 -0
  28. diffguard/reporting/text_report.py +43 -0
  29. diffguard/rules/__init__.py +0 -0
  30. diffguard/rules/base.py +248 -0
  31. diffguard/rules/configuration.py +98 -0
  32. diffguard/rules/dangerous_patterns.py +290 -0
  33. diffguard/rules/dependencies.py +375 -0
  34. diffguard/rules/filetypes.py +49 -0
  35. diffguard/rules/scope.py +108 -0
  36. diffguard/rules/secret_patterns.py +195 -0
  37. diffguard/rules/secrets.py +118 -0
  38. diffguard/rules/test_removal.py +253 -0
  39. diffguard/suppressions/__init__.py +0 -0
  40. diffguard/suppressions/manager.py +81 -0
  41. diffguard/utils/__init__.py +0 -0
  42. diffguard/utils/logging.py +23 -0
  43. diffguard/utils/paths.py +131 -0
  44. diffguard/version.py +1 -0
  45. diffguard_ai-0.1.0.dist-info/METADATA +141 -0
  46. diffguard_ai-0.1.0.dist-info/RECORD +49 -0
  47. diffguard_ai-0.1.0.dist-info/WHEEL +4 -0
  48. diffguard_ai-0.1.0.dist-info/entry_points.txt +2 -0
  49. diffguard_ai-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,375 @@
1
+ """Dependency-change detection by parsing manifests before and after the change.
2
+
3
+ Supported: requirements*.txt, pyproject.toml (PEP 621, PEP 735, Poetry), Pipfile,
4
+ package.json, package-lock.json, poetry.lock, uv.lock. Other lock files
5
+ (yarn.lock, pnpm-lock.yaml, Pipfile.lock, ...) are not parsed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import posixpath
12
+ import re
13
+ import tomllib
14
+ from collections.abc import Callable, Mapping
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ from diffguard.core.enums import Category, ChangeType, Confidence, Severity
19
+ from diffguard.core.models import FileChange, Finding, RuleMetadata
20
+ from diffguard.rules.base import OptionReader, Rule, RuleContext, RuleSettings
21
+
22
+ DepKey = tuple[str, str] # (group, name)
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class DepEntry:
27
+ spec: str
28
+ line: int | None = None
29
+
30
+
31
+ class ManifestParseError(Exception):
32
+ pass
33
+
34
+
35
+ def normalize_name(name: str) -> str:
36
+ return re.sub(r"[-_.]+", "-", name).lower()
37
+
38
+
39
+ _REQ_RE = re.compile(r"^\s*([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)\s*(?:\[[^\]]*\])?\s*(.*?)\s*$")
40
+
41
+
42
+ def _split_requirement(spec: str) -> tuple[str, str] | None:
43
+ match = _REQ_RE.match(spec)
44
+ if match is None:
45
+ return None
46
+ rest = match.group(2)
47
+ if rest and rest[0] not in "<>=!~;@(":
48
+ return None
49
+ return normalize_name(match.group(1)), rest.strip()
50
+
51
+
52
+ def parse_requirements_txt(text: str) -> dict[DepKey, DepEntry]:
53
+ out: dict[DepKey, DepEntry] = {}
54
+ bad: list[str] = []
55
+ for lineno, raw in enumerate(text.splitlines(), start=1):
56
+ line = re.sub(r"(^|\s)#.*$", "", raw).strip().rstrip("\\").strip()
57
+ if not line:
58
+ continue
59
+ if line.startswith(("-r", "-c", "--")) or line.startswith("-i"):
60
+ continue
61
+ if line.startswith(("-e ", "--editable")):
62
+ target = line.split(None, 1)[1] if " " in line else ""
63
+ egg = re.search(r"[#&]egg=([A-Za-z0-9._-]+)", target)
64
+ name = normalize_name(egg.group(1)) if egg else f"editable:{target}"
65
+ out[("main", name)] = DepEntry(f"-e {target}", lineno)
66
+ continue
67
+ if "://" in line and " @ " not in line:
68
+ egg = re.search(r"[#&]egg=([A-Za-z0-9._-]+)", line)
69
+ name = normalize_name(egg.group(1)) if egg else f"url:{line}"
70
+ out[("main", name)] = DepEntry(line, lineno)
71
+ continue
72
+ parts = _split_requirement(line)
73
+ if parts is None:
74
+ bad.append(f"line {lineno}: cannot parse {raw.strip()[:60]!r}")
75
+ continue
76
+ out[("main", parts[0])] = DepEntry(parts[1], lineno)
77
+ if bad:
78
+ raise ManifestParseError("; ".join(bad[:5]))
79
+ return out
80
+
81
+
82
+ def _add_pep508(out: dict[DepKey, DepEntry], group: str, specs: object) -> None:
83
+ if not isinstance(specs, list):
84
+ return
85
+ for item in specs:
86
+ if not isinstance(item, str):
87
+ continue # PEP 735 include-group tables
88
+ parts = _split_requirement(item)
89
+ if parts is None:
90
+ raise ManifestParseError(f"cannot parse requirement {item[:60]!r}")
91
+ out[(group, parts[0])] = DepEntry(parts[1])
92
+
93
+
94
+ def _poetry_spec(value: object) -> str:
95
+ if isinstance(value, str):
96
+ return value
97
+ if isinstance(value, dict):
98
+ for key in ("version", "git", "path", "url"):
99
+ if key in value:
100
+ return f"{key}:{value[key]}" if key != "version" else str(value[key])
101
+ return "{}"
102
+ if isinstance(value, list):
103
+ return " | ".join(_poetry_spec(v) for v in value)
104
+ return str(value)
105
+
106
+
107
+ def _add_table(out: dict[DepKey, DepEntry], group: str, table: object, skip: frozenset[str]) -> None:
108
+ if not isinstance(table, dict):
109
+ return
110
+ for name, value in table.items():
111
+ if name.lower() in skip:
112
+ continue
113
+ out[(group, normalize_name(name))] = DepEntry(_poetry_spec(value))
114
+
115
+
116
+ def parse_pyproject(text: str) -> dict[DepKey, DepEntry]:
117
+ data = tomllib.loads(text)
118
+ out: dict[DepKey, DepEntry] = {}
119
+ project = data.get("project", {})
120
+ _add_pep508(out, "main", project.get("dependencies"))
121
+ for group, specs in (project.get("optional-dependencies") or {}).items():
122
+ _add_pep508(out, f"optional:{group}", specs)
123
+ for group, specs in (data.get("dependency-groups") or {}).items():
124
+ _add_pep508(out, f"group:{group}", specs)
125
+ _add_pep508(out, "build", data.get("build-system", {}).get("requires"))
126
+ poetry = data.get("tool", {}).get("poetry", {})
127
+ skip = frozenset({"python"})
128
+ _add_table(out, "main", poetry.get("dependencies"), skip)
129
+ _add_table(out, "dev", poetry.get("dev-dependencies"), skip)
130
+ for group, body in (poetry.get("group") or {}).items():
131
+ if isinstance(body, dict):
132
+ _add_table(out, f"group:{group}", body.get("dependencies"), skip)
133
+ return out
134
+
135
+
136
+ def parse_pipfile(text: str) -> dict[DepKey, DepEntry]:
137
+ data = tomllib.loads(text)
138
+ out: dict[DepKey, DepEntry] = {}
139
+ _add_table(out, "main", data.get("packages"), frozenset())
140
+ _add_table(out, "dev", data.get("dev-packages"), frozenset())
141
+ return out
142
+
143
+
144
+ def parse_package_json(text: str) -> dict[DepKey, DepEntry]:
145
+ data = json.loads(text)
146
+ if not isinstance(data, dict):
147
+ raise ManifestParseError("package.json must contain an object")
148
+ out: dict[DepKey, DepEntry] = {}
149
+ for section in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"):
150
+ table = data.get(section)
151
+ if isinstance(table, dict):
152
+ for name, spec in table.items():
153
+ out[(section, name)] = DepEntry(str(spec))
154
+ return out
155
+
156
+
157
+ def parse_package_lock(text: str) -> dict[DepKey, DepEntry]:
158
+ data = json.loads(text)
159
+ if not isinstance(data, dict):
160
+ raise ManifestParseError("package-lock.json must contain an object")
161
+ out: dict[DepKey, DepEntry] = {}
162
+ packages = data.get("packages")
163
+ if isinstance(packages, dict):
164
+ for path, meta in packages.items():
165
+ if path == "" or not isinstance(meta, dict):
166
+ continue
167
+ parts = [p for p in path.split("node_modules/") if p]
168
+ out[("lock", " > ".join(p.strip("/") for p in parts))] = DepEntry(str(meta.get("version", "?")))
169
+ return out
170
+
171
+ def walk(table: object, prefix: tuple[str, ...]) -> None:
172
+ if not isinstance(table, dict):
173
+ return
174
+ for name, meta in table.items():
175
+ if not isinstance(meta, dict):
176
+ continue
177
+ chain = (*prefix, name)
178
+ out[("lock", " > ".join(chain))] = DepEntry(str(meta.get("version", "?")))
179
+ walk(meta.get("dependencies"), chain)
180
+
181
+ walk(data.get("dependencies"), ())
182
+ return out
183
+
184
+
185
+ def parse_toml_lock(text: str) -> dict[DepKey, DepEntry]:
186
+ """poetry.lock / uv.lock. A package may be locked at several versions (resolution
187
+ markers); the spec is the sorted set of versions so comparisons are stable."""
188
+ data = tomllib.loads(text)
189
+ versions: dict[str, set[str]] = {}
190
+ for pkg in data.get("package", []):
191
+ if isinstance(pkg, dict) and "name" in pkg:
192
+ versions.setdefault(normalize_name(str(pkg["name"])), set()).add(str(pkg.get("version", "?")))
193
+ return {("lock", name): DepEntry(" | ".join(sorted(v))) for name, v in versions.items()}
194
+
195
+
196
+ Parser = Callable[[str], dict[DepKey, DepEntry]]
197
+
198
+
199
+ def manifest_parser(path: str) -> tuple[Parser, bool] | None:
200
+ """Return ``(parser, is_lockfile)`` for a manifest path, else ``None``."""
201
+ base = posixpath.basename(path).lower()
202
+ parts = path.lower().split("/")
203
+ if base.endswith(".txt") and (
204
+ base.startswith(("requirements", "constraints"))
205
+ or base.endswith("-requirements.txt")
206
+ or "requirements" in parts[:-1]
207
+ ):
208
+ return parse_requirements_txt, False
209
+ return {
210
+ "pyproject.toml": (parse_pyproject, False),
211
+ "pipfile": (parse_pipfile, False),
212
+ "package.json": (parse_package_json, False),
213
+ "package-lock.json": (parse_package_lock, True),
214
+ "poetry.lock": (parse_toml_lock, True),
215
+ "uv.lock": (parse_toml_lock, True),
216
+ }.get(base)
217
+
218
+
219
+ class DependenciesRule(Rule):
220
+ metadata = RuleMetadata(
221
+ name="dependency_changes",
222
+ description="Detects added, removed and changed dependencies by parsing manifests "
223
+ "before and after the change.",
224
+ category=Category.DEPENDENCY,
225
+ default_severity=Severity.WARNING,
226
+ checks={
227
+ "DG-DEP-001": "Dependency added",
228
+ "DG-DEP-002": "Dependency removed",
229
+ "DG-DEP-003": "Dependency version changed",
230
+ "DG-DEP-004": "Manifest changed but contents unavailable",
231
+ "DG-DEP-005": "Manifest could not be parsed",
232
+ "DG-DEP-006": "Additional dependency changes omitted",
233
+ },
234
+ )
235
+
236
+ def validate_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
237
+ r = OptionReader(options)
238
+ allowed = tuple(normalize_name(n) for n in r.strings("allowed_additions"))
239
+ limit = r.integer("max_findings_per_file", 50)
240
+ lockfiles = r.boolean("include_lockfiles", True)
241
+ r.finish()
242
+ return {
243
+ "allowed_additions": frozenset(allowed),
244
+ "max_findings_per_file": limit,
245
+ "include_lockfiles": lockfiles,
246
+ }
247
+
248
+ def evaluate(self, ctx: RuleContext, settings: RuleSettings) -> list[Finding]:
249
+ findings: list[Finding] = []
250
+ for change in ctx.diff.files:
251
+ found = manifest_parser(change.path)
252
+ if found is None or change.is_binary:
253
+ continue
254
+ parser, is_lock = found
255
+ if is_lock and not settings.options["include_lockfiles"]:
256
+ continue
257
+ findings.extend(self._analyze(ctx, settings, change, parser))
258
+ return findings
259
+
260
+ def _analyze(
261
+ self, ctx: RuleContext, settings: RuleSettings, change: FileChange, parser: Parser
262
+ ) -> list[Finding]:
263
+ path = change.path
264
+ if change.change_type is ChangeType.MODE_CHANGED:
265
+ return []
266
+ old_text: str | None = ""
267
+ new_text: str | None = ""
268
+ if change.change_type is not ChangeType.ADDED:
269
+ old_text = ctx.reader.read(change, "old")
270
+ if change.change_type is not ChangeType.DELETED:
271
+ new_text = ctx.reader.read(change, "new")
272
+ if old_text is None or new_text is None:
273
+ return [
274
+ self.finding(
275
+ settings,
276
+ "DG-DEP-004",
277
+ message=f"Dependency manifest changed but its contents could not be read: {path}",
278
+ explanation="diffguard could not obtain the full file before/after the change "
279
+ "(for example when scanning a bare diff), so dependency changes were not analyzed.",
280
+ remediation="Review this manifest manually, or scan using a Git repository "
281
+ "(working tree, --staged or --base) so full contents are available.",
282
+ file_path=path,
283
+ confidence=Confidence.HIGH,
284
+ key="unavailable",
285
+ )
286
+ ]
287
+ try:
288
+ old = parser(old_text) if old_text.strip() else {}
289
+ new = parser(new_text) if new_text.strip() else {}
290
+ except (ManifestParseError, ValueError) as exc: # includes JSON/TOML decode errors
291
+ return [
292
+ self.finding(
293
+ settings,
294
+ "DG-DEP-005",
295
+ message=f"Dependency manifest could not be parsed: {path}",
296
+ explanation=f"Parsing failed, so dependency changes were not analyzed: {str(exc)[:200]}",
297
+ remediation="Fix the syntax error, or review the manifest manually.",
298
+ file_path=path,
299
+ confidence=Confidence.HIGH,
300
+ key="parse-error",
301
+ )
302
+ ]
303
+
304
+ allowed: frozenset[str] = settings.options["allowed_additions"]
305
+ items: list[Finding] = []
306
+ for key in sorted(set(old) | set(new)):
307
+ group, name = key
308
+ before, after = old.get(key), new.get(key)
309
+ label = f"{name} [{group}]"
310
+ if before is None and after is not None:
311
+ if normalize_name(name) in allowed:
312
+ continue
313
+ items.append(
314
+ self.finding(
315
+ settings,
316
+ "DG-DEP-001",
317
+ message=f"Dependency added: {label} {after.spec}".rstrip(),
318
+ explanation="New dependencies expand the supply-chain attack surface and may "
319
+ "carry licensing or maintenance costs.",
320
+ remediation="Confirm the dependency is needed for this task and vetted. If "
321
+ "approved, list it under options.allowed_additions.",
322
+ file_path=path,
323
+ line=after.line,
324
+ evidence=f"+ {name} {after.spec}".rstrip(),
325
+ confidence=Confidence.HIGH,
326
+ key=f"added:{group}:{name}:{after.spec}",
327
+ )
328
+ )
329
+ elif before is not None and after is None:
330
+ items.append(
331
+ self.finding(
332
+ settings,
333
+ "DG-DEP-002",
334
+ message=f"Dependency removed: {label}",
335
+ explanation="Removing a dependency can break functionality or drop a "
336
+ "security-relevant library.",
337
+ remediation="Confirm nothing still uses it and the removal is part of the task.",
338
+ file_path=path,
339
+ evidence=f"- {name} {before.spec}".rstrip(),
340
+ confidence=Confidence.HIGH,
341
+ key=f"removed:{group}:{name}",
342
+ )
343
+ )
344
+ elif before is not None and after is not None and before.spec != after.spec:
345
+ items.append(
346
+ self.finding(
347
+ settings,
348
+ "DG-DEP-003",
349
+ message=f"Dependency version changed: {label}: {before.spec or '(any)'} -> {after.spec or '(any)'}",
350
+ explanation="Version changes can introduce breaking changes or vulnerabilities.",
351
+ remediation="Confirm the new version is intended and reviewed.",
352
+ file_path=path,
353
+ line=after.line,
354
+ evidence=f"{name}: {before.spec} -> {after.spec}",
355
+ confidence=Confidence.HIGH,
356
+ key=f"changed:{group}:{name}:{after.spec}",
357
+ )
358
+ )
359
+ limit: int = settings.options["max_findings_per_file"]
360
+ if len(items) > limit:
361
+ omitted = len(items) - limit
362
+ items = items[:limit]
363
+ items.append(
364
+ self.finding(
365
+ settings,
366
+ "DG-DEP-006",
367
+ message=f"{omitted} additional dependency changes omitted in {path}",
368
+ explanation=f"Reporting is capped at {limit} findings per manifest.",
369
+ remediation="Review the manifest diff directly.",
370
+ file_path=path,
371
+ key="omitted",
372
+ confidence=Confidence.HIGH,
373
+ )
374
+ )
375
+ return items
@@ -0,0 +1,49 @@
1
+ """File-type helpers shared by rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import posixpath
6
+
7
+ _EXTENSIONS: dict[str, str] = {
8
+ ".py": "python", ".pyi": "python",
9
+ ".js": "js", ".jsx": "js", ".ts": "js", ".tsx": "js", ".mjs": "js", ".cjs": "js",
10
+ ".go": "go",
11
+ ".java": "java", ".kt": "java", ".cs": "java", ".scala": "java", ".rs": "java",
12
+ ".rb": "ruby",
13
+ ".php": "php",
14
+ ".sh": "shell", ".bash": "shell", ".zsh": "shell", ".ps1": "shell",
15
+ ".yml": "config", ".yaml": "config", ".toml": "config", ".ini": "config",
16
+ ".cfg": "config", ".conf": "config", ".json": "config", ".properties": "config",
17
+ ".tf": "config", ".env": "config",
18
+ } # fmt: skip
19
+
20
+ DEFAULT_TEST_PATHS = (
21
+ "tests/**", "test/**", "**/tests/**", "**/test/**", "**/__tests__/**",
22
+ "**/test_*.py", "**/*_test.py", "**/*_test.go",
23
+ "**/*.test.js", "**/*.test.jsx", "**/*.test.ts", "**/*.test.tsx",
24
+ "**/*.spec.js", "**/*.spec.jsx", "**/*.spec.ts", "**/*.spec.tsx",
25
+ ) # fmt: skip
26
+
27
+ ALL_GROUPS = frozenset({"python", "js", "go", "java", "ruby", "php", "shell", "config"})
28
+
29
+ _COMMENT_PREFIXES: dict[str, tuple[str, ...]] = {
30
+ "python": ("#",), "ruby": ("#",), "shell": ("#",), "config": ("#",),
31
+ "js": ("//", "/*", "*"), "go": ("//", "/*", "*"), "java": ("//", "/*", "*"),
32
+ "php": ("//", "#", "/*", "*"),
33
+ } # fmt: skip
34
+
35
+
36
+ def language_group(path: str) -> str | None:
37
+ """Coarse language/format group for ``path`` or ``None`` for docs/unknown files."""
38
+ base = posixpath.basename(path)
39
+ lower = base.lower()
40
+ if lower.startswith("dockerfile") or lower in ("makefile", "gnumakefile"):
41
+ return "shell"
42
+ if lower.startswith(".env"):
43
+ return "config"
44
+ return _EXTENSIONS.get(posixpath.splitext(lower)[1])
45
+
46
+
47
+ def is_comment(line: str, group: str) -> bool:
48
+ stripped = line.lstrip()
49
+ return stripped.startswith(_COMMENT_PREFIXES.get(group, ()))
@@ -0,0 +1,108 @@
1
+ """Scope enforcement: allowed paths, protected paths, size limits, policy tampering."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ from diffguard.core.enums import Category, ChangeType, Confidence, Severity
9
+ from diffguard.core.models import Finding, RuleMetadata
10
+ from diffguard.rules.base import OptionReader, Rule, RuleContext, RuleSettings
11
+ from diffguard.utils.paths import first_match, matches_any
12
+
13
+
14
+ class ScopeRule(Rule):
15
+ metadata = RuleMetadata(
16
+ name="scope",
17
+ description="Enforces the task's allowed paths, protected paths and changed-line limit.",
18
+ category=Category.SCOPE,
19
+ default_severity=Severity.ERROR,
20
+ checks={
21
+ "DG-SCOPE-001": "File outside allowed paths",
22
+ "DG-SCOPE-002": "Protected path modified",
23
+ "DG-SCOPE-003": "Changed-line limit exceeded",
24
+ "DG-SCOPE-004": "Policy or baseline file modified",
25
+ },
26
+ )
27
+
28
+ def validate_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
29
+ OptionReader(options).finish()
30
+ return {}
31
+
32
+ def evaluate(self, ctx: RuleContext, settings: RuleSettings) -> list[Finding]:
33
+ task = ctx.task
34
+ findings: list[Finding] = []
35
+ for change in ctx.diff.files:
36
+ for path in change.touched_paths:
37
+ role = ""
38
+ if change.change_type is ChangeType.RENAMED:
39
+ role = " (rename source)" if path == change.old_path else " (rename destination)"
40
+ protected = first_match(path, task.protected_paths)
41
+ if protected is not None:
42
+ findings.append(
43
+ self.finding(
44
+ settings,
45
+ "DG-SCOPE-002",
46
+ message=f"Protected path modified: {path}{role}",
47
+ explanation="This path is declared protected for the task; changes to it "
48
+ "require explicit human authorization.",
49
+ remediation="Revert the change to this path, or move it to a separate, "
50
+ "human-reviewed change. If it is legitimately in scope, adjust "
51
+ "task.protected_paths in the policy.",
52
+ file_path=path,
53
+ evidence=f"matched protected pattern '{protected}'",
54
+ confidence=Confidence.HIGH,
55
+ key=f"protected:{change.change_type}",
56
+ )
57
+ )
58
+ elif task.allowed_paths and not matches_any(path, task.allowed_paths):
59
+ findings.append(
60
+ self.finding(
61
+ settings,
62
+ "DG-SCOPE-001",
63
+ message=f"File outside the task's allowed paths: {path}{role}",
64
+ explanation="The task only permits changes under: "
65
+ + ", ".join(task.allowed_paths)
66
+ + ".",
67
+ remediation="Revert changes outside the allowed paths, or extend "
68
+ "task.allowed_paths if the change is intentional.",
69
+ file_path=path,
70
+ confidence=Confidence.HIGH,
71
+ key=f"outside:{change.change_type}",
72
+ )
73
+ )
74
+ if any(p in ctx.protected_files for p in change.touched_paths):
75
+ path = next(p for p in change.touched_paths if p in ctx.protected_files)
76
+ findings.append(
77
+ self.finding(
78
+ settings,
79
+ "DG-SCOPE-004",
80
+ message=f"Policy or baseline file modified: {path}",
81
+ explanation="A change that edits the rules or baseline that govern it can "
82
+ "weaken enforcement from within.",
83
+ remediation="Make policy and baseline changes in a separate change reviewed "
84
+ "by a human, and scan with a policy taken from the trusted base branch.",
85
+ file_path=path,
86
+ confidence=Confidence.HIGH,
87
+ key="policy-file",
88
+ )
89
+ )
90
+ limit = task.max_changed_lines
91
+ if limit is not None:
92
+ total = ctx.diff.lines_added + ctx.diff.lines_removed
93
+ if total > limit:
94
+ findings.append(
95
+ self.finding(
96
+ settings,
97
+ "DG-SCOPE-003",
98
+ message=f"Change touches {total} lines; the limit is {limit}",
99
+ explanation="Large changes are hard to review and more likely to exceed "
100
+ "the intended task.",
101
+ remediation="Split the work into smaller changes or raise "
102
+ "task.max_changed_lines if the size is justified.",
103
+ evidence=f"added+removed lines = {total}",
104
+ confidence=Confidence.HIGH,
105
+ key="max-changed-lines",
106
+ )
107
+ )
108
+ return findings