Coverage for little_loops / parallel / file_hints.py: 97%
125 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
1"""File hint extraction for overlap detection in parallel processing.
3Extracts file paths, directories, and scopes from issue content to predict
4potential file modifications before dispatch.
5"""
7from __future__ import annotations
9import re
10from dataclasses import dataclass, field
11from typing import TYPE_CHECKING
13if TYPE_CHECKING:
14 from little_loops.config import DependencyMappingConfig
16# File path patterns - adapted from workflow_sequence_analyzer.py
17# Match paths with common source code extensions
18# NOTE: Order matters! Longer extensions must come before shorter ones (tsx before ts, jsx before js)
19FILE_PATH_PATTERN = re.compile(
20 r"(?:^|[\s`\"'(\[])([a-zA-Z0-9_./\-]+\.(?:tsx|jsx|json|yaml|yml|toml|scss|html|cpp|hpp|py|ts|js|md|sh|css|go|rs|java|c|h))",
21 re.MULTILINE,
22)
24# Directory path patterns (paths ending with / followed by whitespace/delimiter)
25# This ensures we only capture explicit directory references, not prefixes of file paths
26DIR_PATH_PATTERN = re.compile(
27 r"(?:^|[\s`\"'(\[])([a-zA-Z0-9_./\-]+/)(?=[\s`\"')\],$]|$)",
28 re.MULTILINE,
29)
31# Component/scope patterns from issue content
32# Matches: "scope: sidebar", "Component: auth", "module: api"
33SCOPE_PATTERN = re.compile(
34 r"(?:scope|component|module|directory|folder)[:\s]+[`\"']?([a-zA-Z0-9_./\-]+)[`\"']?",
35 re.IGNORECASE,
36)
38# Overlap detection thresholds
39MIN_OVERLAP_FILES = 2 # Minimum overlapping files to trigger overlap
40OVERLAP_RATIO_THRESHOLD = 0.25 # Minimum ratio of overlapping files to smaller set
41MIN_DIRECTORY_DEPTH = 2 # Minimum path segments for directory overlap (e.g., src/components/ = 2)
43# Common infrastructure files excluded from overlap detection.
44# These appear incidentally in many issues but are rarely the actual conflict.
45COMMON_FILES_EXCLUDE = frozenset(
46 {
47 "__init__.py",
48 "pyproject.toml",
49 "setup.py",
50 "setup.cfg",
51 "CHANGELOG.md",
52 "README.md",
53 "conftest.py",
54 }
55)
58@dataclass
59class FileHints:
60 """Extracted file hints from issue content.
62 Attributes:
63 files: Specific file paths mentioned
64 directories: Directory paths mentioned
65 scopes: Component/scope identifiers
66 issue_id: Source issue ID
67 """
69 files: set[str] = field(default_factory=set)
70 directories: set[str] = field(default_factory=set)
71 scopes: set[str] = field(default_factory=set)
72 issue_id: str = ""
74 @property
75 def all_paths(self) -> set[str]:
76 """All paths (files and directories) combined."""
77 return self.files | self.directories
79 @property
80 def is_empty(self) -> bool:
81 """Check if no hints were extracted."""
82 return not self.files and not self.directories and not self.scopes
84 def overlaps_with(
85 self,
86 other: FileHints,
87 *,
88 config: DependencyMappingConfig | None = None,
89 ) -> bool:
90 """Check if this hint set overlaps with another.
92 Uses graduated thresholds rather than binary matching:
93 - Common infrastructure files are excluded from file checks
94 - File overlap requires minimum count or ratio threshold
95 - Directory overlap requires minimum path depth
96 - Scope matches are kept as-is (intentional semantic signals)
98 Args:
99 other: FileHints to compare against
100 config: Optional dependency mapping config for custom thresholds.
101 Falls back to module-level constants when not provided.
102 """
103 # Empty hints don't overlap
104 if self.is_empty or other.is_empty:
105 return False
107 # Resolve thresholds from config or module constants
108 min_files = config.overlap_min_files if config else MIN_OVERLAP_FILES
109 ratio_threshold = config.overlap_min_ratio if config else OVERLAP_RATIO_THRESHOLD
110 min_depth = config.min_directory_depth if config else MIN_DIRECTORY_DEPTH
111 exclude_files = frozenset(config.exclude_common_files) if config else COMMON_FILES_EXCLUDE
113 # Filter common infrastructure files
114 self_files = {f for f in self.files if not _is_common_file(f, exclude_files)}
115 other_files = {f for f in other.files if not _is_common_file(f, exclude_files)}
117 # Exact file matches with thresholds
118 shared_files = self_files & other_files
119 if shared_files:
120 smaller_set = min(len(self_files), len(other_files))
121 if smaller_set > 0:
122 ratio = len(shared_files) / smaller_set
123 if len(shared_files) >= min_files or ratio >= ratio_threshold:
124 return True
126 # Directory overlaps (depth check in _directories_overlap)
127 for d1 in self.directories:
128 for d2 in other.directories:
129 if _directories_overlap(d1, d2, min_depth=min_depth):
130 return True
132 # File in directory (depth check in _file_in_directory)
133 for f in self_files:
134 for d in other.directories:
135 if _file_in_directory(f, d, min_depth=min_depth):
136 return True
137 for f in other_files:
138 for d in self.directories:
139 if _file_in_directory(f, d, min_depth=min_depth):
140 return True
142 # Scope matches
143 if self.scopes & other.scopes:
144 return True
146 return False
148 def get_overlapping_paths(
149 self,
150 other: FileHints,
151 *,
152 config: DependencyMappingConfig | None = None,
153 ) -> set[str]:
154 """Get specific paths that overlap between two hint sets.
156 Unlike overlaps_with() which returns bool, this returns the
157 actual file/directory paths causing the overlap. Applies the
158 same filtering and thresholds as overlaps_with().
160 Args:
161 other: FileHints to compare against
162 config: Optional dependency mapping config for custom thresholds.
163 Falls back to module-level constants when not provided.
164 """
165 if self.is_empty or other.is_empty:
166 return set()
168 overlapping: set[str] = set()
170 # Resolve thresholds from config or module constants
171 min_files = config.overlap_min_files if config else MIN_OVERLAP_FILES
172 ratio_threshold = config.overlap_min_ratio if config else OVERLAP_RATIO_THRESHOLD
173 min_depth = config.min_directory_depth if config else MIN_DIRECTORY_DEPTH
174 exclude_files = frozenset(config.exclude_common_files) if config else COMMON_FILES_EXCLUDE
176 # Filter common infrastructure files
177 self_files = {f for f in self.files if not _is_common_file(f, exclude_files)}
178 other_files = {f for f in other.files if not _is_common_file(f, exclude_files)}
180 # Exact file matches (only if they meet thresholds)
181 shared_files = self_files & other_files
182 if shared_files:
183 smaller_set = min(len(self_files), len(other_files))
184 if smaller_set > 0:
185 ratio = len(shared_files) / smaller_set
186 if len(shared_files) >= min_files or ratio >= ratio_threshold:
187 overlapping.update(shared_files)
189 # Directory overlaps (depth check in _directories_overlap)
190 for d1 in self.directories:
191 for d2 in other.directories:
192 if _directories_overlap(d1, d2, min_depth=min_depth):
193 overlapping.add(d1 if len(d1) <= len(d2) else d2)
195 # File in directory (depth check in _file_in_directory)
196 for f in self_files:
197 for d in other.directories:
198 if _file_in_directory(f, d, min_depth=min_depth):
199 overlapping.add(f)
200 for f in other_files:
201 for d in self.directories:
202 if _file_in_directory(f, d, min_depth=min_depth):
203 overlapping.add(f)
205 return overlapping
208def _is_common_file(
209 path: str,
210 exclude_files: frozenset[str] = COMMON_FILES_EXCLUDE,
211) -> bool:
212 """Check if a file is a common infrastructure file to exclude from overlap."""
213 basename = path.rsplit("/", 1)[-1] if "/" in path else path
214 return basename in exclude_files
217def _directories_overlap(
218 dir1: str,
219 dir2: str,
220 *,
221 min_depth: int = MIN_DIRECTORY_DEPTH,
222) -> bool:
223 """Check if two directory paths overlap (one contains the other).
225 Requires the shorter (parent) directory to have at least ``min_depth``
226 path segments to avoid treating broad directories like ``scripts/`` as
227 a conflict signal.
228 """
229 d1 = dir1.rstrip("/") + "/"
230 d2 = dir2.rstrip("/") + "/"
231 if not (d1.startswith(d2) or d2.startswith(d1)):
232 return False
233 # Require minimum depth on the shorter (parent) path
234 shorter = d1 if len(d1) <= len(d2) else d2
235 depth = len(shorter.rstrip("/").split("/"))
236 return depth >= min_depth
239def _file_in_directory(
240 file_path: str,
241 dir_path: str,
242 *,
243 min_depth: int = MIN_DIRECTORY_DEPTH,
244) -> bool:
245 """Check if a file is within a directory.
247 Requires the directory to have at least ``min_depth`` path segments
248 to avoid treating broad directories as a conflict signal.
249 """
250 dir_normalized = dir_path.rstrip("/") + "/"
251 if not file_path.startswith(dir_normalized):
252 return False
253 depth = len(dir_normalized.rstrip("/").split("/"))
254 return depth >= min_depth
257def extract_file_hints(content: str, issue_id: str = "") -> FileHints:
258 """Extract file hints from issue content.
260 Args:
261 content: Issue markdown content
262 issue_id: Optional issue ID for tracking
264 Returns:
265 FileHints with extracted paths and scopes
266 """
267 hints = FileHints(issue_id=issue_id)
269 # Extract file paths
270 for match in FILE_PATH_PATTERN.findall(content):
271 # Filter out obvious non-paths
272 if not _is_valid_path(match):
273 continue
274 hints.files.add(match)
276 # Extract directory paths
277 for match in DIR_PATH_PATTERN.findall(content):
278 if not _is_valid_path(match):
279 continue
280 hints.directories.add(match)
282 # Extract scopes
283 for match in SCOPE_PATTERN.findall(content):
284 hints.scopes.add(match.lower())
286 return hints
289def _is_valid_path(path: str) -> bool:
290 """Filter out false positive paths."""
291 # Skip URLs
292 if path.startswith("http") or path.startswith("//"):
293 return False
294 # Skip very short paths (likely not real file paths)
295 if len(path) < 3:
296 return False
297 # Skip paths that are just file extensions
298 if path.startswith(".") and "/" not in path:
299 return False
300 # Skip common false positives
301 false_positives = {"e.g.", "i.e.", "etc.", "vs.", "v1.", "v2."}
302 if path.lower() in false_positives:
303 return False
304 return True