Coverage for little_loops / cli / loop / _helpers.py: 64%

301 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-04-02 13:03 -0500

1"""Shared helpers for ll-loop CLI subcommands.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6import signal 

7import subprocess 

8import sys 

9import time 

10from pathlib import Path 

11from types import FrameType 

12from typing import TYPE_CHECKING, Any 

13 

14from little_loops.cli.output import colorize, terminal_width 

15from little_loops.logger import Logger 

16 

17if TYPE_CHECKING: 

18 from little_loops.fsm.schema import FSMLoop 

19 

20# Exit code mapping for terminated_by values 

21EXIT_CODES: dict[str, int] = { 

22 "terminal": 0, 

23 "signal": 0, 

24 "handoff": 0, 

25 "max_iterations": 1, 

26 "timeout": 1, 

27} 

28 

29# Module-level shutdown state for signal handling 

30_loop_shutdown_requested: bool = False 

31_loop_executor: Any = None 

32_loop_pid_file: Path | None = None 

33 

34 

35def _loop_signal_handler(signum: int, frame: FrameType | None) -> None: 

36 """Handle shutdown signals gracefully for ll-loop. 

37 

38 First signal: Set shutdown flag for graceful exit after current state. 

39 Second signal: Force immediate exit. 

40 """ 

41 global _loop_shutdown_requested 

42 if _loop_shutdown_requested: 

43 # Second signal - force exit 

44 if _loop_pid_file is not None: 

45 _loop_pid_file.unlink(missing_ok=True) 

46 print("\nForce shutdown requested", file=sys.stderr) 

47 sys.exit(1) 

48 _loop_shutdown_requested = True 

49 print("\nShutdown requested, will exit after current state...", file=sys.stderr) 

50 if _loop_executor is not None: 

51 _loop_executor.request_shutdown() 

52 # Kill any child subprocess currently blocking in the action runner 

53 inner = getattr(_loop_executor, "_executor", None) 

54 if inner is not None: 

55 runner = getattr(inner, "action_runner", None) 

56 if runner is not None: 

57 proc = getattr(runner, "_current_process", None) 

58 if proc is not None: 

59 proc.kill() 

60 # Also kill MCP subprocesses tracked directly on FSMExecutor (_run_subprocess path) 

61 fsm_proc = getattr(inner, "_current_process", None) 

62 if fsm_proc is not None: 

63 fsm_proc.kill() 

64 

65 

66def register_loop_signal_handlers(executor: Any, pid_file: Path | None = None) -> None: 

67 """Register SIGINT/SIGTERM handlers for graceful loop shutdown. 

68 

69 Sets up signal handling so that Ctrl-C triggers a graceful shutdown 

70 (calls executor.request_shutdown()) rather than raising KeyboardInterrupt. 

71 A second Ctrl-C forces immediate exit with PID file cleanup. 

72 

73 Args: 

74 executor: The PersistentExecutor instance to request shutdown on. 

75 pid_file: Optional path to PID file to clean up on forced exit. 

76 """ 

77 global _loop_shutdown_requested, _loop_executor, _loop_pid_file 

78 _loop_shutdown_requested = False 

79 _loop_executor = executor 

80 _loop_pid_file = pid_file 

81 signal.signal(signal.SIGINT, _loop_signal_handler) 

82 signal.signal(signal.SIGTERM, _loop_signal_handler) 

83 

84 

85def get_builtin_loops_dir() -> Path: 

86 """Get the path to built-in loops bundled with the plugin.""" 

87 return Path(__file__).parent.parent.parent / "loops" 

88 

89 

90def resolve_loop_path(name_or_path: str, loops_dir: Path) -> Path: 

91 """Resolve loop name to file path.""" 

92 path = Path(name_or_path) 

93 if path.exists(): 

94 return path 

95 

96 # Try <loops_dir>/<name>.fsm.yaml first (compiled FSM) 

97 fsm_path = loops_dir / f"{name_or_path}.fsm.yaml" 

98 if fsm_path.exists(): 

99 return fsm_path 

100 

101 # Fall back to <loops_dir>/<name>.yaml 

102 loops_path = loops_dir / f"{name_or_path}.yaml" 

103 if loops_path.exists(): 

104 return loops_path 

105 

106 # Fall back to built-in loops from plugin directory 

107 builtin_path = get_builtin_loops_dir() / f"{name_or_path}.yaml" 

108 if builtin_path.exists(): 

109 return builtin_path 

110 

111 raise FileNotFoundError(f"Loop not found: {name_or_path}") 

112 

113 

114def load_loop(name_or_path: str, loops_dir: Path, logger: Logger) -> FSMLoop: 

115 """Load and validate a loop. 

116 

117 Raises: 

118 FileNotFoundError: If loop not found. 

119 ValueError: If loop is invalid. 

120 """ 

121 from little_loops.fsm.validation import load_and_validate 

122 

123 path = resolve_loop_path(name_or_path, loops_dir) 

124 fsm, _ = load_and_validate(path) 

125 return fsm 

126 

127 

128def load_loop_with_spec( 

129 name_or_path: str, loops_dir: Path, logger: Logger 

130) -> tuple[FSMLoop, dict[str, Any]]: 

131 """Load a loop and return both the FSMLoop and raw spec dict. 

132 

133 Used by commands that need access to raw YAML fields (e.g., description). 

134 

135 Raises: 

136 FileNotFoundError: If loop not found. 

137 ValueError: If loop is invalid. 

138 """ 

139 import yaml 

140 

141 from little_loops.fsm.validation import load_and_validate 

142 

143 path = resolve_loop_path(name_or_path, loops_dir) 

144 

145 with open(path) as f: 

146 spec = yaml.safe_load(f) 

147 

148 fsm, _ = load_and_validate(path) 

149 return fsm, spec 

150 

151 

152def print_execution_plan(fsm: FSMLoop) -> None: 

153 """Print dry-run execution plan.""" 

154 tw = terminal_width() 

155 print(colorize(f"Execution plan for: {fsm.name}", "1")) 

156 print() 

157 print("States:") 

158 for name, state in fsm.states.items(): 

159 terminal_marker = colorize(" [TERMINAL]", "32") if state.terminal else "" 

160 print(f" {colorize(f'[{name}]', '1')}{terminal_marker}") 

161 if state.action: 

162 if state.action_type == "prompt": 

163 lines = state.action.strip().splitlines() 

164 preview = "\n ".join(lines[:3]) 

165 if len(lines) > 3 or len(state.action) > 200: 

166 preview += " ..." 

167 print(f" action: |\n {preview}") 

168 else: 

169 max_action = tw - 16 

170 action_display = ( 

171 state.action[:max_action] + "..." 

172 if len(state.action) > max_action 

173 else state.action 

174 ) 

175 print(f" action: {action_display}") 

176 if state.evaluate: 

177 print(f" evaluate: {state.evaluate.type}") 

178 if state.on_yes: 

179 print(f" on_yes {colorize('->', '2')} {colorize(state.on_yes, '2')}") 

180 if state.on_no: 

181 print(f" on_no {colorize('->', '2')} {colorize(state.on_no, '2')}") 

182 if state.on_error: 

183 print(f" on_error {colorize('->', '2')} {colorize(state.on_error, '2')}") 

184 if state.next: 

185 print(f" next {colorize('->', '2')} {colorize(state.next, '2')}") 

186 if state.route: 

187 print(" route:") 

188 for verdict, target in state.route.routes.items(): 

189 print(f" {verdict} {colorize('->', '2')} {colorize(target, '2')}") 

190 if state.route.default: 

191 print(f" _ {colorize('->', '2')} {colorize(state.route.default, '2')}") 

192 print() 

193 print(f"Initial state: {fsm.initial}") 

194 print(f"Max iterations: {fsm.max_iterations}") 

195 if fsm.timeout: 

196 print(f"Timeout: {fsm.timeout}s") 

197 if fsm.context: 

198 print("Context:") 

199 for key, value in fsm.context.items(): 

200 print(f" {key}: {value!r}") 

201 

202 

203def run_background( 

204 loop_name: str, args: argparse.Namespace, loops_dir: Path, subcommand: str = "run" 

205) -> int: 

206 """Launch loop as a detached background process. 

207 

208 Spawns a new process with start_new_session=True that re-executes 

209 the loop with --foreground-internal. The parent writes the PID file 

210 and returns immediately. 

211 

212 Args: 

213 subcommand: The ll-loop subcommand to spawn ("run" or "resume"). 

214 

215 Returns: 

216 Exit code (0 = launched successfully). 

217 """ 

218 running_dir = loops_dir / ".running" 

219 running_dir.mkdir(parents=True, exist_ok=True) 

220 

221 pid_file = running_dir / f"{loop_name}.pid" 

222 log_file = running_dir / f"{loop_name}.log" 

223 

224 # Build re-exec command with --foreground-internal instead of --background 

225 cmd = [ 

226 sys.executable, 

227 "-m", 

228 "little_loops.cli.loop", 

229 subcommand, 

230 loop_name, 

231 "--foreground-internal", 

232 ] 

233 

234 # Forward relevant args 

235 max_iter = getattr(args, "max_iterations", None) 

236 if max_iter: 

237 cmd.extend(["--max-iterations", str(max_iter)]) 

238 if getattr(args, "no_llm", False): 

239 cmd.append("--no-llm") 

240 llm_model = getattr(args, "llm_model", None) 

241 if llm_model: 

242 cmd.extend(["--llm-model", llm_model]) 

243 if getattr(args, "verbose", False): 

244 cmd.append("--verbose") 

245 if getattr(args, "show_diagrams", False): 

246 cmd.append("--show-diagrams") 

247 if getattr(args, "quiet", False): 

248 cmd.append("--quiet") 

249 if getattr(args, "queue", False): 

250 cmd.append("--queue") 

251 for kv in getattr(args, "context", None) or []: 

252 cmd.extend(["--context", kv]) 

253 delay = getattr(args, "delay", None) 

254 if delay is not None: 

255 cmd.extend(["--delay", str(delay)]) 

256 handoff_threshold = getattr(args, "handoff_threshold", None) 

257 if handoff_threshold is not None: 

258 cmd.extend(["--handoff-threshold", str(handoff_threshold)]) 

259 context_limit = getattr(args, "context_limit", None) 

260 if context_limit is not None: 

261 cmd.extend(["--context-limit", str(context_limit)]) 

262 

263 with open(log_file, "w") as log_fh: 

264 process = subprocess.Popen( 

265 cmd, 

266 start_new_session=True, 

267 stdout=log_fh, 

268 stderr=log_fh, 

269 stdin=subprocess.DEVNULL, 

270 ) 

271 

272 pid_file.write_text(str(process.pid)) 

273 print( 

274 f"Loop {colorize(loop_name, '1')} started in background (PID: {colorize(str(process.pid), '2')})" 

275 ) 

276 print(f" Log: {colorize(str(log_file), '2')}") 

277 print(f" Status: {colorize(f'll-loop status {loop_name}', '2')}") 

278 print(f" Stop: {colorize(f'll-loop stop {loop_name}', '2')}") 

279 return 0 

280 

281 

282def run_foreground( 

283 executor: Any, 

284 fsm: FSMLoop, 

285 args: argparse.Namespace, 

286 highlight_color: str = "32", 

287 edge_label_colors: dict[str, str] | None = None, 

288 badges: dict[str, str] | None = None, 

289) -> int: 

290 """Run loop with progress display. 

291 

292 Args: 

293 highlight_color: ANSI SGR code for the active FSM state highlight in verbose mode. 

294 edge_label_colors: Optional label→SGR-code mapping for transition edge labels. 

295 badges: Optional glyph-key→string mapping for state type badges in FSM diagrams. 

296 

297 Returns: 

298 Exit code (0 = success). 

299 """ 

300 quiet = getattr(args, "quiet", False) 

301 verbose = getattr(args, "verbose", False) 

302 show_diagrams = getattr(args, "show_diagrams", False) 

303 clear_screen = getattr(args, "clear", False) 

304 if not quiet: 

305 print(f"Running loop: {colorize(fsm.name, '1')}") 

306 print(f"Max iterations: {colorize(str(fsm.max_iterations), '2')}") 

307 print() 

308 

309 current_iteration = [0] # Use list to allow mutation in closure 

310 last_parent_state: list[str | None] = [ 

311 None 

312 ] # Track last depth=0 state for sub-loop highlighting 

313 current_child_fsm: list[FSMLoop | None] = [ 

314 None 

315 ] # Track active child FSM during sub-loop execution 

316 loop_start_time = time.monotonic() 

317 

318 def display_progress(event: dict) -> None: 

319 """Display progress for events.""" 

320 event_type = event.get("event") 

321 depth = event.get("depth", 0) 

322 indent = " " * depth 

323 tw = terminal_width() 

324 max_line = tw - 8 - len(indent) 

325 

326 if event_type == "state_enter": 

327 current_iteration[0] = event.get("iteration", 0) 

328 state = event.get("state", "") 

329 if not quiet: 

330 elapsed_int = int(time.monotonic() - loop_start_time) 

331 if elapsed_int < 60: 

332 elapsed_str = f"{elapsed_int}s" 

333 else: 

334 elapsed_str = f"{elapsed_int // 60}m {elapsed_int % 60}s" 

335 if clear_screen and sys.stdout.isatty() and depth == 0: 

336 print("\033[2J\033[H", end="", flush=True) 

337 if depth == 0: 

338 last_parent_state[0] = state 

339 fsm_state = fsm.states.get(state) 

340 if fsm_state is not None and fsm_state.loop is not None: 

341 try: 

342 current_child_fsm[0] = load_loop( 

343 fsm_state.loop, executor.loops_dir, Logger() 

344 ) 

345 except (FileNotFoundError, ValueError): 

346 pass # leave current_child_fsm[0] unchanged on failure 

347 else: 

348 current_child_fsm[0] = None 

349 if show_diagrams: 

350 from little_loops.cli.loop.layout import _render_fsm_diagram 

351 

352 highlight = state if depth == 0 else last_parent_state[0] 

353 diagram = _render_fsm_diagram( 

354 fsm, 

355 highlight_state=highlight, 

356 highlight_color=highlight_color, 

357 edge_label_colors=edge_label_colors, 

358 badges=badges, 

359 ) 

360 header_text = f"== loop: {fsm.name} " 

361 header = header_text + "=" * max(0, tw - len(header_text)) 

362 print(header, flush=True) 

363 print(diagram, flush=True) 

364 if depth > 0 and current_child_fsm[0] is not None: 

365 child_name = current_child_fsm[0].name 

366 separator_text = f"\u2500\u2500 sub-loop: {child_name} " 

367 separator = separator_text + "\u2500" * max(0, tw - len(separator_text)) 

368 print(separator, flush=True) 

369 child_diagram = _render_fsm_diagram( 

370 current_child_fsm[0], 

371 highlight_state=state, 

372 highlight_color=highlight_color, 

373 edge_label_colors=edge_label_colors, 

374 badges=badges, 

375 ) 

376 print(child_diagram, flush=True) 

377 if not quiet: 

378 print( 

379 f"{indent}[{current_iteration[0]}/{fsm.max_iterations}] {colorize(state, '1')} ({colorize(elapsed_str, '2')})", 

380 end="", 

381 flush=True, 

382 ) 

383 

384 elif event_type == "action_start": 

385 if not quiet: 

386 action = event.get("action", "") 

387 is_prompt = event.get("is_prompt", False) 

388 if is_prompt: 

389 lines = action.strip().splitlines() 

390 line_count = len(lines) 

391 prompt_badge = "\u2726" # ✦ 

392 print( 

393 f"{indent} -> {colorize(prompt_badge, '2')} {colorize(f'({line_count} lines)', '2')}", 

394 flush=True, 

395 ) 

396 show_count = line_count if verbose else min(5, line_count) 

397 for line in lines[:show_count]: 

398 display = line[:max_line] + "..." if len(line) > max_line else line 

399 print(f"{indent} {display}", flush=True) 

400 if line_count > show_count: 

401 print( 

402 f"{indent} ... ({line_count - show_count} more lines)", flush=True 

403 ) 

404 else: 

405 action_display = action[:max_line] + "..." if len(action) > max_line else action 

406 print(f"{indent} -> {colorize(action_display, '2')}", flush=True) 

407 

408 elif event_type == "action_output": 

409 if not quiet and verbose: 

410 line = event.get("line", "") 

411 if line.strip(): 

412 display = line[:max_line] + "..." if len(line) > max_line else line 

413 print(f"{indent} {display}", flush=True) 

414 

415 elif event_type == "action_complete": 

416 if not quiet: 

417 duration_ms = event.get("duration_ms", 0) 

418 exit_code = event.get("exit_code", 0) 

419 output_preview = event.get("output_preview") 

420 is_prompt = event.get("is_prompt", False) 

421 duration_sec = duration_ms / 1000 

422 if duration_sec < 60: 

423 duration_str = f"{duration_sec:.1f}s" 

424 else: 

425 minutes = int(duration_sec // 60) 

426 seconds = duration_sec % 60 

427 duration_str = f"{minutes}m {seconds:.0f}s" 

428 parts = [f"{indent} ({colorize(duration_str, '2')})"] 

429 if exit_code == 124: 

430 parts.append(colorize("timed out", "38;5;208")) 

431 elif exit_code != 0: 

432 parts.append(colorize(f"exit: {exit_code}", "38;5;208")) 

433 print(" ".join(parts), flush=True) 

434 # Skip output preview for prompt states (already streamed) and in verbose mode 

435 # (lines already shown via action_output events). In non-verbose mode, show 

436 # a tail summary for shell states. 

437 if output_preview and not is_prompt and not verbose: 

438 lines = [ln for ln in output_preview.splitlines() if ln.strip()] 

439 show_lines = lines[-8:] if lines else [] 

440 for line in show_lines: 

441 display = line[:max_line] + "..." if len(line) > max_line else line 

442 print(f"{indent} {display}", flush=True) 

443 

444 elif event_type == "evaluate": 

445 if not quiet: 

446 verdict = event.get("verdict", "") 

447 confidence = event.get("confidence") 

448 reason = event.get("reason", "") 

449 error = event.get("error", "") 

450 if verdict in ("yes", "target", "progress"): 

451 symbol = colorize("\u2713", "32") # green checkmark 

452 verdict_colored = colorize(verdict, "32") 

453 else: 

454 symbol = colorize("\u2717", "38;5;208") # orange x mark 

455 verdict_colored = ( 

456 colorize(verdict, "38;5;208") 

457 if verdict in ("no", "error") 

458 else colorize(verdict, "2") 

459 ) 

460 # Build verdict line 

461 if error and verdict == "error": 

462 verdict_line = f"{symbol} {verdict_colored}: {error}" 

463 elif confidence is not None: 

464 verdict_line = ( 

465 f"{symbol} {verdict_colored} {colorize(f'({confidence:.2f})', '2')}" 

466 ) 

467 else: 

468 verdict_line = f"{symbol} {verdict_colored}" 

469 print(f"{indent} {verdict_line}", flush=True) 

470 # Show raw_preview for error verdicts to aid diagnosis 

471 raw_preview = event.get("raw_preview", "") 

472 if raw_preview and verdict == "error": 

473 print(f"{indent} raw: {raw_preview[:200]}", flush=True) 

474 # Show reason on a second line if present (and not already shown as error) 

475 if reason and not (error and verdict == "error"): 

476 reason_display = reason[:300] + "..." if len(reason) > 300 else reason 

477 print(f"{indent} {reason_display}", flush=True) 

478 

479 elif event_type == "route": 

480 if not quiet: 

481 to_state = event.get("to", "") 

482 print(f"{indent} {colorize('->', '2')} {colorize(to_state, '1')}", flush=True) 

483 

484 # Wire progress display via the EventBus on PersistentExecutor 

485 if not quiet or show_diagrams: 

486 if hasattr(executor, "event_bus"): 

487 executor.event_bus.register(display_progress) 

488 else: 

489 executor._on_event = display_progress 

490 

491 result = executor.run() 

492 

493 if not quiet: 

494 print() 

495 duration_sec = result.duration_ms / 1000 

496 if duration_sec < 60: 

497 duration_str = f"{duration_sec:.1f}s" 

498 else: 

499 minutes = int(duration_sec // 60) 

500 seconds = duration_sec % 60 

501 duration_str = f"{minutes}m {seconds:.0f}s" 

502 if result.terminated_by == "terminal": 

503 state_colored = colorize(result.final_state, "32") 

504 else: 

505 state_colored = colorize(result.final_state, "38;5;208") 

506 print(f"Loop completed: {state_colored} ({result.iterations} iterations, {duration_str})") 

507 

508 return EXIT_CODES.get(result.terminated_by, 1)