Coverage for little_loops / cli / loop / _helpers.py: 92%
152 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"""Shared helpers for ll-loop CLI subcommands."""
3from __future__ import annotations
5import argparse
6import subprocess
7import sys
8import time
9from pathlib import Path
10from typing import TYPE_CHECKING, Any
12if TYPE_CHECKING:
13 from little_loops.fsm.schema import FSMLoop
14 from little_loops.logger import Logger
17def get_builtin_loops_dir() -> Path:
18 """Get the path to built-in loops bundled with the plugin."""
19 return Path(__file__).parent.parent.parent.parent.parent / "loops"
22def resolve_loop_path(name_or_path: str, loops_dir: Path) -> Path:
23 """Resolve loop name to path, preferring compiled FSM over paradigm."""
24 path = Path(name_or_path)
25 if path.exists():
26 return path
28 # Try <loops_dir>/<name>.fsm.yaml first (compiled FSM)
29 fsm_path = loops_dir / f"{name_or_path}.fsm.yaml"
30 if fsm_path.exists():
31 return fsm_path
33 # Fall back to <loops_dir>/<name>.yaml (paradigm)
34 loops_path = loops_dir / f"{name_or_path}.yaml"
35 if loops_path.exists():
36 return loops_path
38 # Fall back to built-in loops from plugin directory
39 builtin_path = get_builtin_loops_dir() / f"{name_or_path}.yaml"
40 if builtin_path.exists():
41 return builtin_path
43 raise FileNotFoundError(f"Loop not found: {name_or_path}")
46def load_loop(name_or_path: str, loops_dir: Path, logger: Logger) -> FSMLoop:
47 """Load and validate a loop, auto-compiling paradigm files.
49 Raises:
50 FileNotFoundError: If loop not found.
51 ValueError: If loop is invalid.
52 """
53 import yaml
55 from little_loops.fsm.compilers import compile_paradigm
56 from little_loops.fsm.validation import load_and_validate
58 path = resolve_loop_path(name_or_path, loops_dir)
60 with open(path) as f:
61 spec = yaml.safe_load(f)
63 # Auto-compile if it's a paradigm file (has 'paradigm' but no 'initial')
64 if "paradigm" in spec and "initial" not in spec:
65 logger.info(f"Auto-compiling paradigm file: {path}")
66 return compile_paradigm(spec)
67 else:
68 return load_and_validate(path)
71def load_loop_with_spec(
72 name_or_path: str, loops_dir: Path, logger: Logger
73) -> tuple[FSMLoop, dict[str, Any]]:
74 """Load a loop and return both the FSMLoop and raw spec dict.
76 Used by commands that need access to raw YAML fields (e.g., description).
78 Raises:
79 FileNotFoundError: If loop not found.
80 ValueError: If loop is invalid.
81 """
82 import yaml
84 from little_loops.fsm.compilers import compile_paradigm
85 from little_loops.fsm.validation import load_and_validate
87 path = resolve_loop_path(name_or_path, loops_dir)
89 with open(path) as f:
90 spec = yaml.safe_load(f)
92 if "paradigm" in spec and "initial" not in spec:
93 logger.info(f"Auto-compiling paradigm file: {path}")
94 fsm = compile_paradigm(spec)
95 else:
96 fsm = load_and_validate(path)
98 return fsm, spec
101def print_execution_plan(fsm: FSMLoop) -> None:
102 """Print dry-run execution plan."""
103 print(f"Execution plan for: {fsm.name}")
104 print()
105 print("States:")
106 for name, state in fsm.states.items():
107 terminal_marker = " [TERMINAL]" if state.terminal else ""
108 print(f" [{name}]{terminal_marker}")
109 if state.action:
110 if len(state.action) > 70:
111 action_display = state.action[:70] + "..."
112 else:
113 action_display = state.action
114 print(f" action: {action_display}")
115 if state.evaluate:
116 print(f" evaluate: {state.evaluate.type}")
117 if state.on_success:
118 print(f" on_success -> {state.on_success}")
119 if state.on_failure:
120 print(f" on_failure -> {state.on_failure}")
121 if state.on_error:
122 print(f" on_error -> {state.on_error}")
123 if state.next:
124 print(f" next -> {state.next}")
125 if state.route:
126 print(" route:")
127 for verdict, target in state.route.routes.items():
128 print(f" {verdict} -> {target}")
129 if state.route.default:
130 print(f" _ -> {state.route.default}")
131 print()
132 print(f"Initial state: {fsm.initial}")
133 print(f"Max iterations: {fsm.max_iterations}")
134 if fsm.timeout:
135 print(f"Timeout: {fsm.timeout}s")
138def run_background(loop_name: str, args: argparse.Namespace, loops_dir: Path) -> int:
139 """Launch loop as a detached background process.
141 Spawns a new process with start_new_session=True that re-executes
142 the loop with --foreground-internal. The parent writes the PID file
143 and returns immediately.
145 Returns:
146 Exit code (0 = launched successfully).
147 """
148 running_dir = loops_dir / ".running"
149 running_dir.mkdir(parents=True, exist_ok=True)
151 pid_file = running_dir / f"{loop_name}.pid"
152 log_file = running_dir / f"{loop_name}.log"
154 # Build re-exec command with --foreground-internal instead of --background
155 cmd = [sys.executable, "-m", "little_loops.cli.loop", "run", loop_name, "--foreground-internal"]
157 # Forward relevant args
158 max_iter = getattr(args, "max_iterations", None)
159 if max_iter:
160 cmd.extend(["--max-iterations", str(max_iter)])
161 if getattr(args, "no_llm", False):
162 cmd.append("--no-llm")
163 llm_model = getattr(args, "llm_model", None)
164 if llm_model:
165 cmd.extend(["--llm-model", llm_model])
166 if getattr(args, "quiet", False):
167 cmd.append("--quiet")
168 if getattr(args, "queue", False):
169 cmd.append("--queue")
171 log_fh = open(log_file, "w") # noqa: SIM115
172 process = subprocess.Popen(
173 cmd,
174 start_new_session=True,
175 stdout=log_fh,
176 stderr=log_fh,
177 stdin=subprocess.DEVNULL,
178 )
180 pid_file.write_text(str(process.pid))
181 print(f"Loop '{loop_name}' started in background (PID: {process.pid})")
182 print(f" Log: {log_file}")
183 print(f" Status: ll-loop status {loop_name}")
184 print(f" Stop: ll-loop stop {loop_name}")
185 return 0
188def run_foreground(executor: Any, fsm: FSMLoop, args: argparse.Namespace) -> int:
189 """Run loop with progress display.
191 Returns:
192 Exit code (0 = success).
193 """
194 quiet = getattr(args, "quiet", False)
195 if not quiet:
196 print(f"Running loop: {fsm.name}")
197 print(f"Max iterations: {fsm.max_iterations}")
198 print()
200 current_iteration = [0] # Use list to allow mutation in closure
201 loop_start_time = time.monotonic()
203 def display_progress(event: dict) -> None:
204 """Display progress for events."""
205 event_type = event.get("event")
207 if event_type == "state_enter":
208 current_iteration[0] = event.get("iteration", 0)
209 state = event.get("state", "")
210 elapsed_int = int(time.monotonic() - loop_start_time)
211 if elapsed_int < 60:
212 elapsed_str = f"{elapsed_int}s"
213 else:
214 elapsed_str = f"{elapsed_int // 60}m {elapsed_int % 60}s"
215 print(
216 f"[{current_iteration[0]}/{fsm.max_iterations}] {state} ({elapsed_str})",
217 end="",
218 flush=True,
219 )
221 elif event_type == "action_start":
222 action = event.get("action", "")
223 action_display = action[:60] + "..." if len(action) > 60 else action
224 print(f" -> {action_display}", flush=True)
226 elif event_type == "evaluate":
227 verdict = event.get("verdict", "")
228 confidence = event.get("confidence")
229 if verdict in ("success", "target", "progress"):
230 symbol = "\u2713" # checkmark
231 else:
232 symbol = "\u2717" # x mark
233 if confidence is not None:
234 print(f" {symbol} {verdict} (confidence: {confidence:.2f})", flush=True)
235 else:
236 print(f" {symbol} {verdict}", flush=True)
238 elif event_type == "route":
239 to_state = event.get("to", "")
240 print(f" -> {to_state}", flush=True)
242 # Wire progress display via the proper observer slot on PersistentExecutor
243 if not quiet:
244 executor._on_event = display_progress
246 result = executor.run()
248 if not quiet:
249 print()
250 duration_sec = result.duration_ms / 1000
251 if duration_sec < 60:
252 duration_str = f"{duration_sec:.1f}s"
253 else:
254 minutes = int(duration_sec // 60)
255 seconds = duration_sec % 60
256 duration_str = f"{minutes}m {seconds:.0f}s"
257 print(
258 f"Loop completed: {result.final_state} ({result.iterations} iterations, {duration_str})"
259 )
261 return 0 if result.terminated_by == "terminal" else 1