Coverage for little_loops / cli / loop / run.py: 26%
108 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
1"""ll-loop run subcommand."""
3from __future__ import annotations
5import argparse
6import atexit
7import os
8import re
9from pathlib import Path
11from little_loops.cli.loop._helpers import (
12 get_builtin_loops_dir,
13 print_execution_plan,
14 register_loop_signal_handlers,
15 resolve_loop_path,
16 run_background,
17 run_foreground,
18)
19from little_loops.logger import Logger
22def cmd_run(
23 loop_name: str,
24 args: argparse.Namespace,
25 loops_dir: Path,
26 logger: Logger,
27) -> int:
28 """Run a loop."""
29 from little_loops.fsm.concurrency import LockManager
30 from little_loops.fsm.persistence import PersistentExecutor
31 from little_loops.fsm.validation import load_and_validate
33 try:
34 if getattr(args, "builtin", False):
35 path = get_builtin_loops_dir() / f"{loop_name}.yaml"
36 if not path.exists():
37 logger.error(f"Built-in loop not found: {loop_name!r}")
38 return 1
39 else:
40 path = resolve_loop_path(loop_name, loops_dir)
41 fsm, _ = load_and_validate(path)
42 except FileNotFoundError as e:
43 logger.error(str(e))
44 return 1
45 except ValueError as e:
46 logger.error(f"Validation error: {e}")
47 return 1
49 # Apply overrides
50 if args.max_iterations:
51 fsm.max_iterations = args.max_iterations
52 if args.delay is not None:
53 fsm.backoff = args.delay
54 if args.no_llm:
55 fsm.llm.enabled = False
56 if args.llm_model:
57 fsm.llm.model = args.llm_model
58 # Inject positional input arg before --context so --context can override
59 if getattr(args, "input", None) is not None:
60 fsm.context[fsm.input_key] = args.input
61 for kv in getattr(args, "context", None) or []:
62 if "=" not in kv:
63 raise SystemExit(f"Invalid --context format: {kv!r} (expected KEY=VALUE)")
64 key, _, value = kv.partition("=")
65 fsm.context[key.strip()] = value.strip()
67 # Apply YAML loop config env-var overrides (CLI flags below overwrite these)
68 if fsm.config is not None and isinstance(fsm.config.handoff_threshold, int):
69 os.environ["LL_HANDOFF_THRESHOLD"] = str(fsm.config.handoff_threshold)
71 if getattr(args, "handoff_threshold", None) is not None:
72 if not (1 <= args.handoff_threshold <= 100):
73 raise SystemExit("--handoff-threshold must be between 1 and 100")
74 os.environ["LL_HANDOFF_THRESHOLD"] = str(args.handoff_threshold)
76 if getattr(args, "context_limit", None) is not None:
77 os.environ["LL_CONTEXT_LIMIT"] = str(args.context_limit)
79 # Dry run
80 if args.dry_run:
81 print_execution_plan(fsm)
82 return 0
84 # Pre-run validation: check required context variables are present
85 _ctx_var_re = re.compile(r"\$\{context\.([^}.]+)")
86 missing_keys: set[str] = set()
87 for state in fsm.states.values():
88 templates = [state.action] if state.action else []
89 if state.evaluate and state.evaluate.prompt:
90 templates.append(state.evaluate.prompt)
91 for template in templates:
92 for m in _ctx_var_re.finditer(template):
93 key = m.group(1)
94 if key not in fsm.context:
95 missing_keys.add(key)
96 if missing_keys:
97 for key in sorted(missing_keys):
98 logger.error(
99 f"Missing required context variable: '{key}'. "
100 f"Run with: ll-loop run {loop_name} --context {key}=VALUE"
101 )
102 return 1
104 # Background mode: spawn detached process and return
105 if getattr(args, "background", False):
106 return run_background(loop_name, args, loops_dir)
108 # Register PID file for all foreground runs so cmd_stop can send SIGTERM (BUG-639).
109 # Background-spawned processes (foreground_internal=True) have their PID written by the
110 # parent in run_background(); plain foreground runs must write their own PID here.
111 running_dir = loops_dir / ".running"
112 running_dir.mkdir(parents=True, exist_ok=True)
113 pid_file = running_dir / f"{loop_name}.pid"
114 foreground_pid_file: Path | None = pid_file
116 if not getattr(args, "foreground_internal", False):
117 pid_file.write_text(str(os.getpid()))
119 def _cleanup_pid() -> None:
120 pid_file.unlink(missing_ok=True)
122 atexit.register(_cleanup_pid)
124 # Scope-based locking
125 lock_manager = LockManager(loops_dir)
126 scope = fsm.scope or ["."]
128 if not lock_manager.acquire(fsm.name, scope):
129 conflict = lock_manager.find_conflict(scope)
130 if conflict and getattr(args, "queue", False):
131 logger.info(f"Waiting for conflicting loop '{conflict.loop_name}' to finish...")
132 if not lock_manager.wait_for_scope(scope, timeout=3600):
133 logger.error("Timeout waiting for scope to become available")
134 return 1
135 # Re-acquire after waiting
136 if not lock_manager.acquire(fsm.name, scope):
137 logger.error("Failed to acquire lock after waiting")
138 return 1
139 elif conflict:
140 logger.error(f"Scope conflict with running loop: {conflict.loop_name}")
141 logger.info(f" Conflicting scope: {conflict.scope}")
142 logger.info(" Use --queue to wait for it to finish")
143 return 1
144 else:
145 # Unexpected: find_conflict returned None but acquire failed
146 logger.error("Failed to acquire scope lock (unknown reason)")
147 return 1
149 try:
150 executor = PersistentExecutor(fsm, loops_dir=loops_dir)
152 # Register signal handlers for graceful shutdown
153 register_loop_signal_handlers(executor, pid_file=foreground_pid_file)
155 from little_loops.config import BRConfig
157 config = BRConfig(Path.cwd())
158 cli_colors = config.cli.colors
159 highlight_color = cli_colors.fsm_active_state
160 edge_label_colors = cli_colors.fsm_edge_labels.to_dict()
161 badges = config.loops.glyphs.to_dict()
162 return run_foreground(
163 executor,
164 fsm,
165 args,
166 highlight_color=highlight_color,
167 edge_label_colors=edge_label_colors,
168 badges=badges,
169 )
170 finally:
171 lock_manager.release(fsm.name)