Coverage for src/governed_harness/runtime/guard.py: 91%

85 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""Fingerprints of what the ChangeSet leaves out (``governance.protectExcludedPaths``). 

2 

3The ChangeSet is computed over the workspace minus ``DEFAULT_EXCLUDES`` and symbolic links, so a 

4write to ``.git/hooks``, an installed dependency in ``venv`` or a file in ``dist`` was invisible 

5to the gate: an agent could leave a Git hook that runs when the person commits, or patch an 

6installed package so the tests pass. The guard fingerprints those places before and after each 

7agent invocation in IMPLEMENTATION; any difference is a ``CRITICAL`` finding. 

8 

9A fingerprint is the size, the modification time in nanoseconds and the SHA-256 of the first 

10``HEAD_BYTES`` of each file (the target for a symbolic link). It is cheap enough for a virtual 

11environment or ``node_modules`` and detects every write that changes size, time or the start of a 

12file; a write that restores all three is not detected. 

13""" 

14 

15from __future__ import annotations 

16 

17import fnmatch 

18import hashlib 

19import os 

20from collections.abc import Iterable 

21from dataclasses import dataclass 

22from pathlib import Path 

23 

24GUARDED_DIRECTORIES = frozenset( 

25 {".git", ".harness", ".venv", "venv", "node_modules", "dist", "build"} 

26) 

27"""Directories the ChangeSet excludes that the guard watches (caches such as ``__pycache__`` are 

28rewritten by every test run and are not watched).""" 

29 

30IGNORED_PATTERNS: tuple[str, ...] = ( 

31 # The harness's own state while the agent runs. 

32 ".harness/state.db", 

33 ".harness/state.db-*", 

34 ".harness/artifacts/*", 

35 ".harness/lease.json", 

36 ".harness/lease.json.*", 

37 # The digest cache of workspace.snapshotCache: the harness rewrites it around every agent 

38 # invocation, and a copy that does not match its seal in the state database is ignored. 

39 ".harness/cache/*", 

40 # Git rewrites its index on a read (git status) and keeps transient locks; objects only 

41 # matter once a ref points to them, and refs are watched. The chain-anchor notes are the 

42 # harness's own (governance.chainAnchor: git-note). 

43 ".git/index", 

44 "*.lock", 

45 ".git/objects/*", 

46 ".git/refs/notes/governed-harness", 

47 ".git/logs/refs/notes/*", 

48) 

49 

50PRUNED_DIRECTORIES = frozenset({".harness/artifacts", ".git/objects"}) 

51"""Ignored directories that are not walked at all (they can hold many files).""" 

52 

53HEAD_BYTES = 8192 

54 

55 

56@dataclass(frozen=True) 

57class GuardChange: 

58 path: str 

59 status: str # ADDED, MODIFIED or DELETED 

60 

61 

62def _ignored(relative: str) -> bool: 

63 return any(fnmatch.fnmatchcase(relative, pattern) for pattern in IGNORED_PATTERNS) 

64 

65 

66def _file_fingerprint(path: Path) -> str: 

67 stat = path.lstat() 

68 if path.is_symlink(): 

69 return f"link:{os.readlink(path)}" 

70 digest = hashlib.sha256() 

71 try: 

72 with path.open("rb") as handle: 

73 digest.update(handle.read(HEAD_BYTES)) 

74 except OSError: 

75 return f"unreadable:{stat.st_size}:{stat.st_mtime_ns}" 

76 return f"{stat.st_size}:{stat.st_mtime_ns}:{digest.hexdigest()}" 

77 

78 

79class ExcludedPathGuard: 

80 def __init__( 

81 self, 

82 root: Path, 

83 guarded: Iterable[str] = GUARDED_DIRECTORIES, 

84 *, 

85 include_ignored: bool = False, 

86 ) -> None: 

87 self.root = root.resolve(strict=True) 

88 self.guarded = frozenset(guarded) 

89 self.include_ignored = include_ignored 

90 """``workspace.snapshot: git`` (since 2.0): files ``.gitignore`` excludes leave the 

91 ChangeSet, so the guard also fingerprints the ignored files outside the directories it 

92 already watches and outside the caches every test run rewrites.""" 

93 

94 def fingerprint(self) -> dict[str, str]: 

95 """Fingerprints of every file below a guarded directory (at any depth) and of every 

96 symbolic link in the workspace, by workspace-relative path.""" 

97 prints: dict[str, str] = {} 

98 for directory, dirnames, filenames in os.walk(self.root, followlinks=False): 

99 current = Path(directory) 

100 inside = self._inside_guarded(current) 

101 self._prune(prints, current, dirnames) 

102 for name in filenames: 

103 path = current / name 

104 if inside or path.is_symlink(): 

105 self._add(prints, path) 

106 if self.include_ignored: 

107 self._add_ignored(prints) 

108 return dict(sorted(prints.items())) 

109 

110 def _prune(self, prints: dict[str, str], current: Path, dirnames: list[str]) -> None: 

111 """Fingerprint the symbolic links among ``dirnames`` and leave them, and the pruned 

112 directories, out of the walk.""" 

113 # A copy: the loop removes pruned names from dirnames, which os.walk reads. 

114 for name in list(dirnames): # NOSONAR(S7504) 

115 path = current / name 

116 if path.is_symlink(): 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true

117 self._add(prints, path) 

118 dirnames.remove(name) 

119 elif path.relative_to(self.root).as_posix() in PRUNED_DIRECTORIES: 

120 dirnames.remove(name) 

121 

122 def _add_ignored(self, prints: dict[str, str]) -> None: 

123 """Fingerprint the ignored files the walk of the guarded directories left out.""" 

124 from governed_harness.runtime.snapshots import ignored_outside_excludes 

125 

126 for relative in ignored_outside_excludes(self.root): 

127 path = self.root / relative 

128 if relative not in prints and not self._inside_guarded(path.parent): 128 ↛ 126line 128 didn't jump to line 126 because the condition on line 128 was always true

129 self._add(prints, path) 

130 

131 @staticmethod 

132 def compare(before: dict[str, str], after: dict[str, str]) -> tuple[GuardChange, ...]: 

133 changes: list[GuardChange] = [] 

134 for path in sorted(set(before) | set(after)): 

135 if path not in before: 

136 changes.append(GuardChange(path, "ADDED")) 

137 elif path not in after: 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true

138 changes.append(GuardChange(path, "DELETED")) 

139 elif before[path] != after[path]: 

140 changes.append(GuardChange(path, "MODIFIED")) 

141 return tuple(changes) 

142 

143 def _inside_guarded(self, directory: Path) -> bool: 

144 relative = directory.relative_to(self.root).parts 

145 return any(part in self.guarded for part in relative) 

146 

147 def _add(self, prints: dict[str, str], path: Path) -> None: 

148 relative = path.relative_to(self.root).as_posix() 

149 if _ignored(relative): 

150 return 

151 try: 

152 prints[relative] = _file_fingerprint(path) 

153 except OSError: 

154 return