Coverage for little_loops / cli / loop / lifecycle.py: 0%
131 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"""ll-loop lifecycle subcommands: status, stop, resume."""
3from __future__ import annotations
5import argparse
6import atexit
7import os
8import signal
9import time
10from pathlib import Path
12from little_loops.cli.loop._helpers import (
13 EXIT_CODES,
14 load_loop,
15 register_loop_signal_handlers,
16 run_background,
17)
18from little_loops.fsm.concurrency import _process_alive
19from little_loops.logger import Logger
22def _read_pid_file(pid_file: Path) -> int | None:
23 """Read and validate a PID file.
25 Returns:
26 The PID as an integer, or None if the file doesn't exist or is invalid.
27 """
28 if not pid_file.exists():
29 return None
30 try:
31 return int(pid_file.read_text().strip())
32 except (ValueError, OSError):
33 return None
36def cmd_status(
37 loop_name: str,
38 loops_dir: Path,
39 logger: Logger,
40) -> int:
41 """Show loop status."""
42 from little_loops.fsm.persistence import StatePersistence
44 persistence = StatePersistence(loop_name, loops_dir)
45 state = persistence.load_state()
47 if state is None:
48 logger.error(f"No state found for: {loop_name}")
49 return 1
51 print(f"Loop: {state.loop_name}")
52 print(f"Status: {state.status}")
53 print(f"Current state: {state.current_state}")
54 print(f"Iteration: {state.iteration}")
55 print(f"Started: {state.started_at}")
56 print(f"Updated: {state.updated_at}")
58 # Show PID info if available (background mode)
59 running_dir = loops_dir / ".running"
60 pid_file = running_dir / f"{loop_name}.pid"
61 pid = _read_pid_file(pid_file)
62 if pid is not None:
63 if _process_alive(pid):
64 print(f"PID: {pid} (running)")
65 else:
66 print(f"PID: {pid} (not running - stale PID file)")
68 if state.continuation_prompt:
69 # Show truncated continuation context
70 prompt_preview = state.continuation_prompt[:200]
71 if len(state.continuation_prompt) > 200:
72 prompt_preview += "..."
73 print(f"Continuation context: {prompt_preview}")
74 return 0
77def cmd_stop(
78 loop_name: str,
79 loops_dir: Path,
80 logger: Logger,
81) -> int:
82 """Stop a running loop."""
83 from little_loops.fsm.persistence import StatePersistence
85 persistence = StatePersistence(loop_name, loops_dir)
86 state = persistence.load_state()
88 if state is None:
89 logger.error(f"No state found for: {loop_name}")
90 return 1
92 if state.status != "running":
93 logger.error(f"Loop not running: {loop_name} (status: {state.status})")
94 return 1
96 # Check PID before modifying state to avoid overwriting the process's own final status.
97 # Race condition: process may finish and write its terminal status between
98 # cmd_stop's state read and a premature state write.
99 running_dir = loops_dir / ".running"
100 pid_file = running_dir / f"{loop_name}.pid"
101 pid = _read_pid_file(pid_file)
102 if pid is not None:
103 if _process_alive(pid):
104 # Process confirmed alive: send SIGTERM, then wait for exit
105 os.kill(pid, signal.SIGTERM)
106 for _ in range(10):
107 time.sleep(1)
108 if not _process_alive(pid):
109 break
110 else:
111 # Still alive after grace period: force kill
112 try:
113 os.kill(pid, signal.SIGKILL)
114 logger.warning(f"Sent SIGKILL to {loop_name} (PID: {pid})")
115 except OSError:
116 pass # Process exited between poll and kill
117 state.status = "interrupted"
118 persistence.save_state(state)
119 pid_file.unlink(missing_ok=True)
120 logger.success(f"Stopped {loop_name} (PID: {pid})")
121 else:
122 # Process already exited: preserve its final status, only clean up PID file
123 logger.info(f"Process {pid} not running, cleaning up PID file")
124 pid_file.unlink(missing_ok=True)
125 else:
126 # No PID file: no background process tracked, update state only
127 state.status = "interrupted"
128 persistence.save_state(state)
129 logger.success(f"Marked {loop_name} as interrupted")
131 return 0
134def cmd_resume(
135 loop_name: str,
136 args: argparse.Namespace,
137 loops_dir: Path,
138 logger: Logger,
139) -> int:
140 """Resume an interrupted loop."""
141 from little_loops.fsm.persistence import PersistentExecutor, StatePersistence
143 # Background mode: spawn detached process and return
144 if getattr(args, "background", False):
145 return run_background(loop_name, args, loops_dir, subcommand="resume")
147 # Register PID file for all foreground runs so cmd_stop can send SIGTERM (BUG-639).
148 # Background-spawned processes (foreground_internal=True) have their PID written by the
149 # parent in run_background(); plain foreground runs must write their own PID here.
150 import os
152 running_dir = loops_dir / ".running"
153 running_dir.mkdir(parents=True, exist_ok=True)
154 pid_file = running_dir / f"{loop_name}.pid"
155 foreground_pid_file: Path | None = pid_file
157 if not getattr(args, "foreground_internal", False):
158 pid_file.write_text(str(os.getpid()))
160 def _cleanup_pid() -> None:
161 pid_file.unlink(missing_ok=True)
163 atexit.register(_cleanup_pid)
165 try:
166 fsm = load_loop(loop_name, loops_dir, logger)
167 except FileNotFoundError as e:
168 logger.error(str(e))
169 return 1
170 except ValueError as e:
171 logger.error(f"Validation error: {e}")
172 return 1
174 for kv in getattr(args, "context", None) or []:
175 if "=" not in kv:
176 raise SystemExit(f"Invalid --context format: {kv!r} (expected KEY=VALUE)")
177 key, _, value = kv.partition("=")
178 fsm.context[key.strip()] = value.strip()
180 if getattr(args, "delay", None) is not None:
181 fsm.backoff = args.delay
183 # Check state before resuming to show context
184 persistence = StatePersistence(loop_name, loops_dir)
185 state = persistence.load_state()
186 if state and state.status == "awaiting_continuation":
187 print(f"Resuming from context handoff (iteration {state.iteration})...")
188 if state.continuation_prompt:
189 # Show truncated continuation context
190 prompt_preview = state.continuation_prompt[:500]
191 if len(state.continuation_prompt) > 500:
192 prompt_preview += "..."
193 print(f"Context: {prompt_preview}")
194 print()
196 executor = PersistentExecutor(fsm, loops_dir=loops_dir)
198 # Register signal handlers for graceful shutdown (same as cmd_run)
199 register_loop_signal_handlers(executor, pid_file=foreground_pid_file)
201 result = executor.resume()
203 if result is None:
204 logger.warning(f"Nothing to resume for: {loop_name}")
205 return 1
207 duration_sec = result.duration_ms / 1000
208 if duration_sec < 60:
209 duration_str = f"{duration_sec:.1f}s"
210 else:
211 minutes = int(duration_sec // 60)
212 seconds = duration_sec % 60
213 duration_str = f"{minutes}m {seconds:.0f}s"
215 logger.success(
216 f"Resumed and completed: {result.final_state} "
217 f"({result.iterations} iterations, {duration_str})"
218 )
219 return EXIT_CODES.get(result.terminated_by, 1)