Coverage for little_loops / config / core.py: 51%
140 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
1"""Core configuration dataclasses and the root BRConfig aggregator.
3ProjectConfig holds project-level settings. BRConfig is the single entry
4point that loads ll-config.json and exposes all domain configs via properties.
5"""
7from __future__ import annotations
9import json
10from dataclasses import dataclass
11from pathlib import Path
12from typing import TYPE_CHECKING, Any, cast
14from little_loops.config.automation import (
15 AutomationConfig,
16 CommandsConfig,
17 DependencyMappingConfig,
18 ParallelAutomationConfig,
19)
20from little_loops.config.cli import CliConfig, RefineStatusConfig
21from little_loops.config.features import (
22 IssuesConfig,
23 LoopsConfig,
24 ScanConfig,
25 SprintsConfig,
26 SyncConfig,
27)
29if TYPE_CHECKING:
30 from little_loops.parallel.types import ParallelConfig
33@dataclass
34class ProjectConfig:
35 """Project-level configuration."""
37 name: str = ""
38 src_dir: str = "src/"
39 test_dir: str = "tests"
40 test_cmd: str = "pytest"
41 lint_cmd: str = "ruff check ."
42 type_cmd: str | None = "mypy"
43 format_cmd: str | None = "ruff format ."
44 build_cmd: str | None = None
45 run_cmd: str | None = None
47 @classmethod
48 def from_dict(cls, data: dict[str, Any]) -> ProjectConfig:
49 """Create ProjectConfig from dictionary."""
50 return cls(
51 name=data.get("name", ""),
52 src_dir=data.get("src_dir", "src/"),
53 test_dir=data.get("test_dir", "tests"),
54 test_cmd=data.get("test_cmd", "pytest"),
55 lint_cmd=data.get("lint_cmd", "ruff check ."),
56 type_cmd=data.get("type_cmd", "mypy"),
57 format_cmd=data.get("format_cmd", "ruff format ."),
58 build_cmd=data.get("build_cmd"),
59 run_cmd=data.get("run_cmd"),
60 )
63class BRConfig:
64 """Main configuration class for little-loops.
66 Loads configuration from .claude/ll-config.json and merges with defaults.
67 Provides convenient property access to all configuration values.
69 Example:
70 config = BRConfig(Path.cwd())
71 print(config.project.src_dir) # "src/"
72 print(config.issues.base_dir) # ".issues"
73 print(config.get_issue_dir("bugs")) # Path(".issues/bugs")
74 """
76 CONFIG_FILENAME = "ll-config.json"
77 CONFIG_DIR = ".claude"
79 def __init__(self, project_root: Path) -> None:
80 """Initialize configuration from project root.
82 Args:
83 project_root: Path to the project root directory
84 """
85 self.project_root = project_root.resolve()
86 self._raw_config = self._load_config()
87 self._parse_config()
89 def _load_config(self) -> dict[str, Any]:
90 """Load configuration from file."""
91 config_path = self.project_root / self.CONFIG_DIR / self.CONFIG_FILENAME
92 if config_path.exists():
93 with open(config_path, encoding="utf-8") as f:
94 return cast(dict[str, Any], json.load(f))
95 return {}
97 def _parse_config(self) -> None:
98 """Parse raw config into typed dataclasses."""
99 self._project = ProjectConfig.from_dict(self._raw_config.get("project", {}))
100 if not self._project.name:
101 self._project.name = self.project_root.name
103 self._issues = IssuesConfig.from_dict(self._raw_config.get("issues", {}))
104 self._automation = AutomationConfig.from_dict(self._raw_config.get("automation", {}))
105 self._parallel = ParallelAutomationConfig.from_dict(self._raw_config.get("parallel", {}))
106 self._commands = CommandsConfig.from_dict(self._raw_config.get("commands", {}))
107 self._scan = ScanConfig.from_dict(self._raw_config.get("scan", {}))
108 self._sprints = SprintsConfig.from_dict(self._raw_config.get("sprints", {}))
109 self._loops = LoopsConfig.from_dict(self._raw_config.get("loops", {}))
110 self._sync = SyncConfig.from_dict(self._raw_config.get("sync", {}))
111 self._dependency_mapping = DependencyMappingConfig.from_dict(
112 self._raw_config.get("dependency_mapping", {})
113 )
114 self._cli = CliConfig.from_dict(self._raw_config.get("cli", {}))
115 self._refine_status = RefineStatusConfig.from_dict(
116 self._raw_config.get("refine_status", {})
117 )
119 @property
120 def project(self) -> ProjectConfig:
121 """Get project configuration."""
122 return self._project
124 @property
125 def issues(self) -> IssuesConfig:
126 """Get issues configuration."""
127 return self._issues
129 @property
130 def automation(self) -> AutomationConfig:
131 """Get automation configuration."""
132 return self._automation
134 @property
135 def parallel(self) -> ParallelAutomationConfig:
136 """Get parallel automation configuration."""
137 return self._parallel
139 @property
140 def commands(self) -> CommandsConfig:
141 """Get commands configuration."""
142 return self._commands
144 @property
145 def scan(self) -> ScanConfig:
146 """Get scan configuration."""
147 return self._scan
149 @property
150 def sprints(self) -> SprintsConfig:
151 """Get sprints configuration."""
152 return self._sprints
154 @property
155 def loops(self) -> LoopsConfig:
156 """Get loops configuration."""
157 return self._loops
159 @property
160 def sync(self) -> SyncConfig:
161 """Get sync configuration."""
162 return self._sync
164 @property
165 def dependency_mapping(self) -> DependencyMappingConfig:
166 """Get dependency mapping configuration."""
167 return self._dependency_mapping
169 @property
170 def cli(self) -> CliConfig:
171 """Get CLI output configuration."""
172 return self._cli
174 @property
175 def refine_status(self) -> RefineStatusConfig:
176 """Get refine-status display configuration."""
177 return self._refine_status
179 @property
180 def repo_path(self) -> Path:
181 """Get the repository root path."""
182 return self.project_root
184 # Convenience methods for common operations
186 def get_issue_dir(self, category: str) -> Path:
187 """Get the directory path for an issue category.
189 Args:
190 category: Category key (e.g., "bugs", "features")
192 Returns:
193 Path to the issue category directory
194 """
195 if category in self._issues.categories:
196 dir_name = self._issues.categories[category].dir
197 else:
198 dir_name = category
199 return self.project_root / self._issues.base_dir / dir_name
201 def get_completed_dir(self) -> Path:
202 """Get the path to the completed issues directory."""
203 return self.project_root / self._issues.base_dir / self._issues.completed_dir
205 def get_deferred_dir(self) -> Path:
206 """Get the path to the deferred issues directory."""
207 return self.project_root / self._issues.base_dir / self._issues.deferred_dir
209 def get_issue_prefix(self, category: str) -> str:
210 """Get the issue ID prefix for a category.
212 Args:
213 category: Category key (e.g., "bugs", "features")
215 Returns:
216 Issue prefix (e.g., "BUG", "FEAT")
217 """
218 if category in self._issues.categories:
219 return self._issues.categories[category].prefix
220 return category.upper()[:3]
222 def get_category_action(self, category: str) -> str:
223 """Get the default action for a category.
225 Args:
226 category: Category key (e.g., "bugs", "features")
228 Returns:
229 Action verb (e.g., "fix", "implement")
230 """
231 if category in self._issues.categories:
232 return self._issues.categories[category].action
233 return "fix"
235 def get_loops_dir(self) -> Path:
236 """Get the loops directory path."""
237 return self.project_root / self._loops.loops_dir
239 def get_src_path(self) -> Path:
240 """Get the source directory path."""
241 return self.project_root / self._project.src_dir
243 def get_worktree_base(self) -> Path:
244 """Get the worktree base directory path."""
245 return self.project_root / self._automation.worktree_base
247 def get_state_file(self) -> Path:
248 """Get the state file path."""
249 return self.project_root / self._automation.state_file
251 def get_parallel_state_file(self) -> Path:
252 """Get the parallel state file path."""
253 return self.project_root / self._parallel.base.state_file
255 def create_parallel_config(
256 self,
257 *,
258 max_workers: int | None = None,
259 priority_filter: list[str] | None = None,
260 max_issues: int = 0,
261 dry_run: bool = False,
262 timeout_seconds: int | None = None,
263 idle_timeout_per_issue: int | None = None,
264 stream_output: bool | None = None,
265 show_model: bool | None = None,
266 only_ids: set[str] | None = None,
267 skip_ids: set[str] | None = None,
268 type_prefixes: set[str] | None = None,
269 merge_pending: bool = False,
270 clean_start: bool = False,
271 ignore_pending: bool = False,
272 overlap_detection: bool = False,
273 serialize_overlapping: bool = True,
274 base_branch: str = "main",
275 ) -> ParallelConfig:
276 """Create a ParallelConfig from BRConfig settings with optional overrides.
278 Args:
279 max_workers: Override max_workers (default: from config)
280 priority_filter: Override priority filter (default: from issues config)
281 max_issues: Maximum issues to process (default: 0 = unlimited)
282 dry_run: Preview mode (default: False)
283 timeout_seconds: Per-issue timeout (default: from config)
284 idle_timeout_per_issue: Kill worker if no output for N seconds (0 to disable, default: 0)
285 stream_output: Stream output (default: from config)
286 show_model: Make API call to verify model (default: False)
287 only_ids: If provided, only process these issue IDs
288 skip_ids: Issue IDs to skip (in addition to completed/failed)
289 merge_pending: Attempt to merge pending worktrees (default: False)
290 clean_start: Remove all worktrees without checking (default: False)
291 ignore_pending: Report pending work but continue (default: False)
292 overlap_detection: Enable pre-flight overlap detection (default: False)
293 serialize_overlapping: If True, defer overlapping issues; if False, just warn
295 Returns:
296 ParallelConfig configured from BRConfig
297 """
298 from little_loops.parallel.types import ParallelConfig
300 return ParallelConfig(
301 max_workers=max_workers or self._parallel.base.max_workers,
302 p0_sequential=self._parallel.p0_sequential,
303 worktree_base=Path(self._parallel.base.worktree_base),
304 state_file=Path(self._parallel.base.state_file),
305 max_merge_retries=self._parallel.max_merge_retries,
306 priority_filter=priority_filter or self._issues.priorities,
307 max_issues=max_issues,
308 dry_run=dry_run,
309 timeout_per_issue=timeout_seconds or self._parallel.base.timeout_seconds,
310 idle_timeout_per_issue=idle_timeout_per_issue
311 if idle_timeout_per_issue is not None
312 else 0,
313 stream_subprocess_output=(
314 stream_output if stream_output is not None else self._parallel.base.stream_output
315 ),
316 show_model=show_model if show_model is not None else False,
317 command_prefix=self._parallel.command_prefix,
318 ready_command=self._parallel.ready_command,
319 manage_command=self._parallel.manage_command,
320 only_ids=only_ids,
321 skip_ids=skip_ids,
322 type_prefixes=type_prefixes,
323 worktree_copy_files=self._parallel.worktree_copy_files,
324 require_code_changes=self._parallel.require_code_changes,
325 merge_pending=merge_pending,
326 clean_start=clean_start,
327 ignore_pending=ignore_pending,
328 overlap_detection=overlap_detection,
329 serialize_overlapping=serialize_overlapping,
330 base_branch=base_branch,
331 )
333 @property
334 def issue_categories(self) -> list[str]:
335 """Get list of configured issue category names."""
336 return list(self._issues.categories.keys())
338 @property
339 def issue_priorities(self) -> list[str]:
340 """Get list of valid priority prefixes."""
341 return self._issues.priorities
343 def to_dict(self) -> dict[str, Any]:
344 """Convert configuration to dictionary.
346 Useful for variable substitution in command templates.
347 """
348 return {
349 "project": {
350 "name": self._project.name,
351 "src_dir": self._project.src_dir,
352 "test_dir": self._project.test_dir,
353 "test_cmd": self._project.test_cmd,
354 "lint_cmd": self._project.lint_cmd,
355 "type_cmd": self._project.type_cmd,
356 "format_cmd": self._project.format_cmd,
357 "build_cmd": self._project.build_cmd,
358 "run_cmd": self._project.run_cmd,
359 },
360 "issues": {
361 "base_dir": self._issues.base_dir,
362 "categories": {
363 k: {"prefix": v.prefix, "dir": v.dir, "action": v.action}
364 for k, v in self._issues.categories.items()
365 },
366 "completed_dir": self._issues.completed_dir,
367 "deferred_dir": self._issues.deferred_dir,
368 "priorities": self._issues.priorities,
369 "templates_dir": self._issues.templates_dir,
370 "capture_template": self._issues.capture_template,
371 },
372 "automation": {
373 "timeout_seconds": self._automation.timeout_seconds,
374 "state_file": self._automation.state_file,
375 "worktree_base": self._automation.worktree_base,
376 "max_workers": self._automation.max_workers,
377 "stream_output": self._automation.stream_output,
378 "max_continuations": self._automation.max_continuations,
379 },
380 "parallel": {
381 "max_workers": self._parallel.base.max_workers,
382 "p0_sequential": self._parallel.p0_sequential,
383 "worktree_base": self._parallel.base.worktree_base,
384 "state_file": self._parallel.base.state_file,
385 "timeout_seconds": self._parallel.base.timeout_seconds,
386 "max_merge_retries": self._parallel.max_merge_retries,
387 "stream_output": self._parallel.base.stream_output,
388 "command_prefix": self._parallel.command_prefix,
389 "ready_command": self._parallel.ready_command,
390 "manage_command": self._parallel.manage_command,
391 },
392 "commands": {
393 "pre_implement": self._commands.pre_implement,
394 "post_implement": self._commands.post_implement,
395 "custom_verification": self._commands.custom_verification,
396 "confidence_gate": {
397 "enabled": self._commands.confidence_gate.enabled,
398 "threshold": self._commands.confidence_gate.threshold,
399 },
400 "tdd_mode": self._commands.tdd_mode,
401 },
402 "scan": {
403 "focus_dirs": self._scan.focus_dirs,
404 "exclude_patterns": self._scan.exclude_patterns,
405 "custom_agents": self._scan.custom_agents,
406 },
407 "sprints": {
408 "sprints_dir": self._sprints.sprints_dir,
409 "default_timeout": self._sprints.default_timeout,
410 "default_max_workers": self._sprints.default_max_workers,
411 },
412 "loops": {
413 "loops_dir": self._loops.loops_dir,
414 },
415 "sync": {
416 "enabled": self._sync.enabled,
417 "provider": self._sync.provider,
418 "github": {
419 "repo": self._sync.github.repo,
420 "label_mapping": self._sync.github.label_mapping,
421 "priority_labels": self._sync.github.priority_labels,
422 "sync_completed": self._sync.github.sync_completed,
423 "state_file": self._sync.github.state_file,
424 "pull_template": self._sync.github.pull_template,
425 },
426 },
427 "dependency_mapping": {
428 "overlap_min_files": self._dependency_mapping.overlap_min_files,
429 "overlap_min_ratio": self._dependency_mapping.overlap_min_ratio,
430 "min_directory_depth": self._dependency_mapping.min_directory_depth,
431 "conflict_threshold": self._dependency_mapping.conflict_threshold,
432 "high_conflict_threshold": self._dependency_mapping.high_conflict_threshold,
433 "confidence_modifier": self._dependency_mapping.confidence_modifier,
434 "scoring_weights": {
435 "semantic": self._dependency_mapping.scoring_weights.semantic,
436 "section": self._dependency_mapping.scoring_weights.section,
437 "type": self._dependency_mapping.scoring_weights.type,
438 },
439 "exclude_common_files": self._dependency_mapping.exclude_common_files,
440 },
441 }
443 def resolve_variable(self, var_path: str) -> str | None:
444 """Resolve a variable path like 'project.src_dir' to its value.
446 Args:
447 var_path: Dot-separated path to configuration value
449 Returns:
450 The resolved value as a string, or None if not found
451 """
452 parts = var_path.split(".")
453 value: Any = self.to_dict()
455 for part in parts:
456 if isinstance(value, dict) and part in value:
457 value = value[part]
458 else:
459 return None
461 if value is None:
462 return None
463 if isinstance(value, list):
464 return " ".join(str(v) for v in value)
465 return str(value)
468# Backwards compatibility alias
469CLConfig = BRConfig