Coverage for src/governed_harness/checks/model.py: 100%
71 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""What a deterministic check returns, and the ChangeSet diff it reads.
3The checks of this package are pure: they read source text and a unified diff and return
4``Issue`` values. They never run a command, never write a record and never read the network; the
5validators in ``governed_harness.validators.agent_results`` turn issues into findings."""
7from __future__ import annotations
9import re
10from dataclasses import dataclass, field
12from governed_harness.domain.enums import FindingSeverity
15@dataclass(frozen=True)
16class Issue:
17 """One problem a check found. ``rule_id`` is stable (``<check>.<rule>``)."""
19 rule_id: str
20 severity: FindingSeverity
21 message: str
22 path: str | None = None
23 line: int | None = None
24 category: str = "verification"
25 recommendation: str | None = None
28@dataclass(frozen=True)
29class DiffLine:
30 number: int
31 """Line number in the new file for an added line, in the old file for a removed one."""
32 text: str
35@dataclass
36class DiffFile:
37 """One file of a unified diff: its paths and its added and removed lines."""
39 old_path: str | None
40 new_path: str | None
41 added: list[DiffLine] = field(default_factory=list)
42 removed: list[DiffLine] = field(default_factory=list)
44 @property
45 def path(self) -> str:
46 return self.new_path or self.old_path or ""
48 @property
49 def is_added(self) -> bool:
50 return self.old_path is None
52 @property
53 def is_deleted(self) -> bool:
54 return self.new_path is None
57_HUNK = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@")
60def _side(value: str, prefix: str) -> str | None:
61 value = value.split("\t", 1)[0].strip()
62 if value == "/dev/null":
63 return None
64 return value[len(prefix) :] if value.startswith(prefix) else value
67def parse_unified_diff(text: str) -> list[DiffFile]:
68 """The files of a unified diff (the ChangeSet diff), with numbered added and removed
69 lines. Binary entries and unknown lines are skipped."""
70 files: list[DiffFile] = []
71 current: DiffFile | None = None
72 old_line = new_line = 0
73 pending_old: str | None = None
74 lines = text.splitlines()
75 index = 0
76 while index < len(lines):
77 line = lines[index]
78 if (
79 line.startswith("--- ")
80 and index + 1 < len(lines)
81 and lines[index + 1].startswith("+++ ")
82 ):
83 pending_old = _side(line[4:], "a/")
84 current = DiffFile(old_path=pending_old, new_path=_side(lines[index + 1][4:], "b/"))
85 files.append(current)
86 index += 2
87 continue
88 match = _HUNK.match(line)
89 if match and current is not None:
90 old_line, new_line = int(match.group(1)), int(match.group(2))
91 elif current is not None and line.startswith("+"):
92 current.added.append(DiffLine(new_line, line[1:]))
93 new_line += 1
94 elif current is not None and line.startswith("-"):
95 current.removed.append(DiffLine(old_line, line[1:]))
96 old_line += 1
97 elif current is not None and line.startswith(" "):
98 old_line += 1
99 new_line += 1
100 index += 1
101 return files
104# One alternation per test-file convention; a public constant, kept as a single pattern.
105TEST_PATH = re.compile(
106 r"(^|/)(tests?|__tests__|spec)/|(^|/)test_[^/]*\.py$|_test\.py$|\.test\.[jt]sx?$|\.spec\.[jt]sx?$|(^|/)conftest\.py$" # NOSONAR(S5843) # noqa: E501
107)
110def is_test_path(path: str) -> bool:
111 """Whether a workspace path is a test file or lives in a test directory."""
112 return bool(TEST_PATH.search(path.replace("\\", "/")))