Coverage for little_loops / cli / loop / run.py: 38%
262 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-06-16 13:12 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-06-16 13:12 -0500
1"""ll-loop run subcommand."""
3from __future__ import annotations
5import argparse
6import atexit
7import hashlib
8import json
9import os
10import re
11import time
12import uuid
13from datetime import UTC, datetime
14from pathlib import Path
16from little_loops.cli.loop._helpers import (
17 _is_earliest_waiter,
18 _make_instance_id,
19 get_builtin_loops_dir,
20 print_execution_plan,
21 register_loop_signal_handlers,
22 resolve_loop_path,
23 run_background,
24 run_foreground,
25)
26from little_loops.logger import Logger
29def _parse_program_md(path: Path) -> dict[str, str]:
30 """Parse .ll/program.md heading sections into context key-value pairs.
32 Sections mapped:
33 ## Directive → directive (prose)
34 ## Targets → targets (space-joined list items)
35 ## Benchmark → each key: value pair injected directly
36 ## Budget → budget (prose)
37 ## Constraints → constraints (prose)
38 """
39 if not path.exists():
40 return {}
41 try:
42 content = path.read_text()
43 except OSError:
44 return {}
46 def _extract(heading: str) -> str:
47 m = re.search(rf"^##\s+{re.escape(heading)}\s*$", content, re.MULTILINE | re.IGNORECASE)
48 if not m:
49 return ""
50 start = m.end()
51 nxt = re.search(r"^##\s", content[start:], re.MULTILINE)
52 return content[start : start + nxt.start()].strip() if nxt else content[start:].strip()
54 result: dict[str, str] = {}
56 directive = _extract("Directive")
57 if directive:
58 result["directive"] = directive
60 targets_text = _extract("Targets")
61 if targets_text:
62 items = [
63 line.lstrip("-* \t").strip()
64 for line in targets_text.splitlines()
65 if line.strip().startswith(("-", "*"))
66 ]
67 result["targets"] = " ".join(items) if items else targets_text
69 benchmark_text = _extract("Benchmark")
70 if benchmark_text:
71 for line in benchmark_text.splitlines():
72 if ":" in line:
73 k, _, v = line.partition(":")
74 k, v = k.strip(), v.strip()
75 if k and v:
76 result[k] = v
78 budget = _extract("Budget")
79 if budget:
80 result["budget"] = budget
82 constraints = _extract("Constraints")
83 if constraints:
84 result["constraints"] = constraints
86 return result
89def cmd_run(
90 loop_name: str,
91 args: argparse.Namespace,
92 loops_dir: Path,
93 logger: Logger,
94) -> int:
95 """Run a loop."""
96 from little_loops.fsm.concurrency import LockManager, resolve_scope
97 from little_loops.fsm.persistence import PersistentExecutor, _reconcile_stale_runs
98 from little_loops.fsm.rate_limit_circuit import RateLimitCircuit
99 from little_loops.fsm.validation import load_and_validate
101 try:
102 if getattr(args, "builtin", False):
103 path = get_builtin_loops_dir() / f"{loop_name}.yaml"
104 if not path.exists():
105 logger.error(f"Built-in loop not found: {loop_name!r}")
106 return 1
107 else:
108 path = resolve_loop_path(loop_name, loops_dir)
109 fsm, _ = load_and_validate(path)
110 except FileNotFoundError as e:
111 logger.error(str(e))
112 return 1
113 except ValueError as e:
114 logger.error(f"Validation error: {e}")
115 return 1
117 # Apply overrides
118 if args.max_iterations:
119 fsm.max_iterations = args.max_iterations
120 if args.delay is not None:
121 fsm.backoff = args.delay
122 if args.no_llm:
123 fsm.llm.enabled = False
124 if args.llm_model:
125 fsm.llm.model = args.llm_model
126 # Inject positional input arg before --context so --context can override
127 if getattr(args, "input", None) is not None:
128 raw = args.input
129 try:
130 parsed = json.loads(raw)
131 if isinstance(parsed, dict):
132 matched = {k: v for k, v in parsed.items() if k in fsm.context}
133 if matched:
134 fsm.context.update(matched)
135 else:
136 fsm.context[fsm.input_key] = raw
137 else:
138 fsm.context[fsm.input_key] = raw
139 except (json.JSONDecodeError, ValueError):
140 fsm.context[fsm.input_key] = raw
141 # Inject program.md fields before --context so --context can override
142 program_md_arg = getattr(args, "program_md", None)
143 program_md_path = (
144 program_md_arg if program_md_arg is not None else Path.cwd() / ".ll" / "program.md"
145 )
146 for key, value in _parse_program_md(program_md_path).items():
147 fsm.context[key] = value
148 for kv in getattr(args, "context", None) or []:
149 if "=" not in kv:
150 raise SystemExit(f"Invalid --context format: {kv!r} (expected KEY=VALUE)")
151 key, _, value = kv.partition("=")
152 fsm.context[key.strip()] = value.strip()
154 # Generate instance_id early so run_dir can be derived before the validation scan
155 if getattr(args, "foreground_internal", False):
156 _pre_instance_id: str | None = getattr(args, "instance_id", None)
157 else:
158 _pre_instance_id = _make_instance_id(loop_name)
160 # Inject run_dir into context before validation so ${context.run_dir} resolves.
161 # --context run_dir=VALUE (already applied above) takes precedence.
162 if "run_dir" not in fsm.context:
163 fsm.context["run_dir"] = str(loops_dir / "runs" / (_pre_instance_id or loop_name)) + "/"
165 # Inject input hash for checkpoint fingerprinting.
166 # --context input_hash=VALUE (already applied above) takes precedence.
167 if "input_hash" not in fsm.context and isinstance(fsm.context.get("input"), str):
168 fsm.context["input_hash"] = hashlib.sha256(fsm.context["input"].encode()).hexdigest()[:12]
170 # Inject loop metadata into context so templates can reference
171 # ${context.max_iterations} in state actions and evaluator prompts.
172 # --context max_iterations=VALUE (already applied above) takes precedence.
173 # Must run after the --max-iterations CLI override (line 118-119) so the
174 # context value reflects any CLI-supplied override.
175 if "max_iterations" not in fsm.context:
176 fsm.context["max_iterations"] = fsm.max_iterations
178 # Apply YAML loop config env-var overrides (CLI flags below overwrite these)
179 if fsm.config is not None and isinstance(fsm.config.handoff_threshold, int):
180 os.environ["LL_HANDOFF_THRESHOLD"] = str(fsm.config.handoff_threshold)
182 if getattr(args, "handoff_threshold", None) is not None:
183 if not (1 <= args.handoff_threshold <= 100):
184 raise SystemExit("--handoff-threshold must be between 1 and 100")
185 os.environ["LL_HANDOFF_THRESHOLD"] = str(args.handoff_threshold)
187 if getattr(args, "context_limit", None) is not None:
188 os.environ["LL_CONTEXT_LIMIT"] = str(args.context_limit)
190 from little_loops.config import BRConfig
191 from little_loops.design_tokens import load_design_tokens, render_as_prompt_context
193 _config = BRConfig(Path.cwd())
195 if not fsm.context.get("design_tokens_context"):
196 _tokens = load_design_tokens(_config)
197 fsm.context["design_tokens_context"] = render_as_prompt_context(_tokens) if _tokens else ""
199 _edge_label_colors = _config.cli.colors.fsm_edge_labels.to_dict()
200 _highlight_color = _config.cli.colors.fsm_active_state
201 _badges = _config.loops.glyphs.to_dict()
203 # Dry run
204 if args.dry_run:
205 from little_loops.cli.loop.diagram_modes import resolve_facets
206 from little_loops.cli.loop.layout import _render_fsm_diagram
207 from little_loops.cli.output import terminal_width
209 facets = resolve_facets(args)
210 if facets is not None:
211 tw = terminal_width()
212 header_text = f"== loop: {fsm.name} "
213 print(header_text + "=" * max(0, tw - len(header_text)))
214 diagram = _render_fsm_diagram(
215 fsm,
216 highlight_color=_highlight_color,
217 edge_label_colors=_edge_label_colors,
218 badges=_badges,
219 mode=facets.scope,
220 suppress_labels=not facets.edge_labels,
221 title_only=facets.state_detail == "title",
222 )
223 print(diagram)
224 print()
225 print_execution_plan(fsm, edge_label_colors=_edge_label_colors)
226 return 0
228 # Pre-run validation: check required context variables are present
229 _ctx_var_re = re.compile(r"\$\{context\.([^}.]+)")
230 missing_keys: set[str] = set()
231 for state in fsm.states.values():
232 templates = [state.action] if state.action else []
233 if state.evaluate and state.evaluate.prompt:
234 templates.append(state.evaluate.prompt)
235 for template in templates:
236 for m in _ctx_var_re.finditer(template):
237 key = m.group(1)
238 if key not in fsm.context:
239 missing_keys.add(key)
240 if missing_keys:
241 for key in sorted(missing_keys):
242 logger.error(
243 f"Missing required context variable: '{key}'. "
244 f"Run with: ll-loop run {loop_name} --context {key}=VALUE"
245 )
246 return 1
248 # Pre-run validation: check required_inputs are present and non-empty
249 for key in fsm.required_inputs:
250 if not fsm.context.get(key, ""):
251 logger.error(
252 f"loop '{loop_name}' requires input '{key}' but none was provided. "
253 f"Pass it via: ll-loop run {loop_name} <value>"
254 )
255 return 1
257 # Baseline mode: apply to context before background gate so flags forward correctly
258 baseline_enabled = getattr(args, "baseline", False)
259 if baseline_enabled:
260 if getattr(args, "worktree", False):
261 raise SystemExit("--baseline and --worktree cannot be combined")
262 fsm.context["_baseline"] = {
263 "enabled": True,
264 "skill": getattr(args, "baseline_skill", None),
265 "items": getattr(args, "items", None),
266 "cross_host": getattr(args, "cross_host", False),
267 }
269 # Background mode: spawn detached process and return
270 if getattr(args, "background", False):
271 if getattr(args, "worktree", False):
272 raise SystemExit("--worktree and --background cannot be combined")
273 if getattr(args, "follow", False):
274 raise SystemExit(
275 "--follow and --background cannot be combined; use 'll-logs tail' to watch a background loop"
276 )
277 return run_background(loop_name, args, loops_dir)
279 # Register PID file for all foreground runs so cmd_stop can send SIGTERM (BUG-639).
280 # Background-spawned processes (foreground_internal=True) have their PID written by the
281 # parent in run_background(); plain foreground runs must write their own PID here.
282 running_dir = loops_dir / ".running"
283 running_dir.mkdir(parents=True, exist_ok=True)
284 _reconcile_stale_runs(loops_dir)
285 instance_id = _pre_instance_id
286 pid_file = running_dir / f"{instance_id or loop_name}.pid"
287 foreground_pid_file: Path | None = pid_file
289 if not getattr(args, "foreground_internal", False):
290 pid_file.parent.mkdir(parents=True, exist_ok=True)
291 pid_file.write_text(str(os.getpid()))
293 def _cleanup_pid() -> None:
294 pid_file.unlink(missing_ok=True)
296 atexit.register(_cleanup_pid)
298 # Scope-based locking
299 lock_manager = LockManager(loops_dir)
300 scope = resolve_scope(fsm.scope or ["."], fsm.context)
301 _queue_entry_file: Path | None = None
303 def _cleanup_queue_entry() -> None:
304 if _queue_entry_file is not None:
305 _queue_entry_file.unlink(missing_ok=True)
307 if not getattr(args, "no_lock", False):
308 if not lock_manager.acquire(fsm.name, scope, instance_id=instance_id):
309 conflict = lock_manager.find_conflict(scope)
310 if conflict and getattr(args, "queue", False):
311 # Write queue entry so dashboard shows the waiting loop
312 queue_dir = loops_dir / ".queue"
313 queue_dir.mkdir(parents=True, exist_ok=True)
314 entry_id = str(uuid.uuid4())
315 entry = {
316 "id": entry_id,
317 "loopName": loop_name,
318 "enqueuedAt": datetime.now(UTC).isoformat(),
319 "context": {
320 "waitingFor": conflict.loop_name,
321 "scope": conflict.scope,
322 "pid": os.getpid(),
323 },
324 }
325 _queue_entry_file = queue_dir / f"{entry_id}.json"
326 _queue_entry_file.write_text(json.dumps(entry, indent=2))
327 atexit.register(_cleanup_queue_entry)
329 logger.info(f"Waiting for conflicting loop '{conflict.loop_name}' to finish...")
330 # Retry loop: when N waiters are released simultaneously, only one wins
331 # acquire(); losers loop back and wait again rather than exiting (BUG-1281).
332 acquired = False
333 _wait_start = time.time()
334 _budget = _config.loops.queue_wait_timeout_seconds
335 while time.time() - _wait_start < _budget:
336 _remaining = _budget - (time.time() - _wait_start)
337 if not lock_manager.wait_for_scope(scope, timeout=int(_remaining)):
338 _cleanup_queue_entry()
339 logger.error("Timeout waiting for scope to become available")
340 return 1
341 if not _is_earliest_waiter(entry_id, queue_dir):
342 time.sleep(1)
343 continue
344 if lock_manager.acquire(fsm.name, scope, instance_id=instance_id):
345 acquired = True
346 break
347 if not acquired:
348 _cleanup_queue_entry()
349 logger.error("Failed to acquire lock after waiting")
350 return 1
351 # Lock acquired - no longer queued
352 _cleanup_queue_entry()
353 elif conflict:
354 logger.error(f"Scope conflict with running loop: {conflict.loop_name}")
355 logger.info(f" Conflicting scope: {conflict.scope}")
356 logger.info(" Use --queue to wait for it to finish")
357 return 1
358 else:
359 # Unexpected: find_conflict returned None but acquire failed
360 logger.error("Failed to acquire scope lock (unknown reason)")
361 return 1
363 executor: PersistentExecutor | None = None
364 try:
365 # Worktree isolation: create branch + directory before anything reads Path.cwd()
366 if getattr(args, "worktree", False):
367 from little_loops.config import BRConfig as _MainBRConfig
368 from little_loops.parallel.git_lock import GitLock
369 from little_loops.worktree_utils import cleanup_worktree, setup_worktree
371 _main_config = _MainBRConfig(Path.cwd())
372 _worktree_base = _main_config.get_worktree_base()
373 _copy_files = _main_config.parallel.worktree_copy_files
374 _repo_path = Path.cwd()
376 _timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
377 _safe_name = re.sub(r"[^a-zA-Z0-9-]", "-", loop_name)
378 _branch_name = f"{_timestamp}-{_safe_name}"
379 _worktree_path = _worktree_base / _branch_name
381 _worktree_base.mkdir(parents=True, exist_ok=True)
382 _git_lock = GitLock(logger)
384 setup_worktree(
385 repo_path=_repo_path,
386 worktree_path=_worktree_path,
387 branch_name=_branch_name,
388 copy_files=_copy_files,
389 logger=logger,
390 git_lock=_git_lock,
391 )
393 logger.info(f"Worktree: {_worktree_path}")
394 logger.info(f"Branch: {_branch_name}")
396 def _cleanup_worktree_on_exit() -> None:
397 cleanup_worktree(
398 worktree_path=_worktree_path,
399 repo_path=_repo_path,
400 logger=logger,
401 git_lock=_git_lock,
402 delete_branch=True,
403 )
405 atexit.register(_cleanup_worktree_on_exit)
407 os.environ["CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR"] = "1"
408 os.chdir(_worktree_path)
410 circuit = (
411 RateLimitCircuit(Path(_config.commands.rate_limits.circuit_breaker_path))
412 if _config.commands.rate_limits.circuit_breaker_enabled
413 else None
414 )
415 Path(fsm.context["run_dir"]).mkdir(parents=True, exist_ok=True)
416 executor = PersistentExecutor(
417 fsm, loops_dir=loops_dir, circuit=circuit, instance_id=instance_id, pid=os.getpid()
418 )
420 # Register signal handlers for graceful shutdown
421 register_loop_signal_handlers(executor, pid_file=foreground_pid_file)
423 from little_loops.extension import wire_extensions
424 from little_loops.transport import wire_transports
426 wire_extensions(executor.event_bus, _config.extensions, executor=executor)
427 wire_transports(executor.event_bus, _config.events)
428 return run_foreground(
429 executor,
430 fsm,
431 args,
432 highlight_color=_highlight_color,
433 edge_label_colors=_edge_label_colors,
434 badges=_badges,
435 instance_id=instance_id,
436 loop_path=path,
437 running_dir=running_dir,
438 model=fsm.llm.model,
439 )
440 finally:
441 if executor is not None:
442 executor.close_transports()
443 if not getattr(args, "no_lock", False):
444 lock_manager.release(fsm.name, instance_id=instance_id)