Coverage for little_loops / cli / loop / lifecycle.py: 8%

180 statements  

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

1"""ll-loop lifecycle subcommands: status, stop, resume.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6import atexit 

7import os 

8import signal 

9import time 

10from pathlib import Path 

11 

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 

20 

21 

22def _format_relative_time(seconds: float) -> str: 

23 """Format seconds as a human-readable relative time string (e.g., '3m ago').""" 

24 total = int(seconds) 

25 if total < 60: 

26 return f"{total}s ago" 

27 if total < 3600: 

28 m, s = divmod(total, 60) 

29 return f"{m}m ago" if s == 0 else f"{m}m {s}s ago" 

30 if total < 86400: 

31 h, rem = divmod(total, 3600) 

32 m = rem // 60 

33 return f"{h}h ago" if m == 0 else f"{h}h {m}m ago" 

34 d, rem = divmod(total, 86400) 

35 h = rem // 3600 

36 return f"{d}d ago" if h == 0 else f"{d}d {h}h ago" 

37 

38 

39def _read_pid_file(pid_file: Path) -> int | None: 

40 """Read and validate a PID file. 

41 

42 Returns: 

43 The PID as an integer, or None if the file doesn't exist or is invalid. 

44 """ 

45 if not pid_file.exists(): 

46 return None 

47 try: 

48 return int(pid_file.read_text().strip()) 

49 except (ValueError, OSError): 

50 return None 

51 

52 

53def cmd_status( 

54 loop_name: str, 

55 loops_dir: Path, 

56 logger: Logger, 

57 args: argparse.Namespace | None = None, 

58) -> int: 

59 """Show loop status.""" 

60 from little_loops.cli.output import print_json 

61 from little_loops.fsm.persistence import StatePersistence 

62 

63 persistence = StatePersistence(loop_name, loops_dir) 

64 state = persistence.load_state() 

65 

66 if state is None: 

67 logger.error(f"No state found for: {loop_name}") 

68 return 1 

69 

70 running_dir = loops_dir / ".running" 

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

72 pid = _read_pid_file(pid_file) 

73 

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

75 log_file_str: str | None = None 

76 log_updated_ago: str | None = None 

77 last_event: str | None = None 

78 if log_file.exists(): 

79 log_file_str = str(log_file) 

80 age_seconds = time.time() - log_file.stat().st_mtime 

81 log_updated_ago = _format_relative_time(age_seconds) 

82 try: 

83 lines = log_file.read_text().splitlines() 

84 non_empty = [ln for ln in lines if ln.strip()] 

85 last_event = non_empty[-1] if non_empty else None 

86 except OSError: 

87 last_event = None 

88 

89 if getattr(args, "json", False): 

90 d = state.to_dict() 

91 d["pid"] = pid 

92 d["log_file"] = log_file_str 

93 d["log_updated_ago"] = log_updated_ago 

94 d["last_event"] = last_event 

95 print_json(d) 

96 return 0 

97 

98 print(f"Loop: {state.loop_name}") 

99 print(f"Status: {state.status}") 

100 print(f"Current state: {state.current_state}") 

101 print(f"Iteration: {state.iteration}") 

102 print(f"Started: {state.started_at}") 

103 print(f"Updated: {state.updated_at}") 

104 

105 # Show PID info if available (background mode) 

106 if pid is not None: 

107 if _process_alive(pid): 

108 print(f"PID: {pid} (running)") 

109 else: 

110 print(f"PID: {pid} (not running - stale PID file)") 

111 

112 # Show log file info 

113 if log_file_str is not None: 

114 print(f"Log: {log_file_str}") 

115 print(f"Log updated: {log_updated_ago}") 

116 if last_event: 

117 print(f"Last event: {last_event}") 

118 else: 

119 print("Log: (not found)") 

120 

121 if state.continuation_prompt: 

122 # Show truncated continuation context 

123 prompt_preview = state.continuation_prompt[:200] 

124 if len(state.continuation_prompt) > 200: 

125 prompt_preview += "..." 

126 print(f"Continuation context: {prompt_preview}") 

127 return 0 

128 

129 

130def cmd_stop( 

131 loop_name: str, 

132 loops_dir: Path, 

133 logger: Logger, 

134) -> int: 

135 """Stop a running loop.""" 

136 from little_loops.fsm.persistence import StatePersistence 

137 

138 persistence = StatePersistence(loop_name, loops_dir) 

139 state = persistence.load_state() 

140 

141 if state is None: 

142 logger.error(f"No state found for: {loop_name}") 

143 return 1 

144 

145 if state.status != "running": 

146 logger.error(f"Loop not running: {loop_name} (status: {state.status})") 

147 return 1 

148 

149 # Check PID before modifying state to avoid overwriting the process's own final status. 

150 # Race condition: process may finish and write its terminal status between 

151 # cmd_stop's state read and a premature state write. 

152 running_dir = loops_dir / ".running" 

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

154 pid = _read_pid_file(pid_file) 

155 if pid is not None: 

156 if _process_alive(pid): 

157 # Process confirmed alive: send SIGTERM, then wait for exit 

158 os.kill(pid, signal.SIGTERM) 

159 for _ in range(10): 

160 time.sleep(1) 

161 if not _process_alive(pid): 

162 break 

163 else: 

164 # Still alive after grace period: force kill 

165 try: 

166 os.kill(pid, signal.SIGKILL) 

167 logger.warning(f"Sent SIGKILL to {loop_name} (PID: {pid})") 

168 except OSError: 

169 pass # Process exited between poll and kill 

170 state.status = "interrupted" 

171 persistence.save_state(state) 

172 pid_file.unlink(missing_ok=True) 

173 logger.success(f"Stopped {loop_name} (PID: {pid})") 

174 else: 

175 # Process already exited: preserve its final status, only clean up PID file 

176 logger.info(f"Process {pid} not running, cleaning up PID file") 

177 pid_file.unlink(missing_ok=True) 

178 else: 

179 # No PID file: no background process tracked, update state only 

180 state.status = "interrupted" 

181 persistence.save_state(state) 

182 logger.success(f"Marked {loop_name} as interrupted") 

183 

184 return 0 

185 

186 

187def cmd_resume( 

188 loop_name: str, 

189 args: argparse.Namespace, 

190 loops_dir: Path, 

191 logger: Logger, 

192) -> int: 

193 """Resume an interrupted loop.""" 

194 from little_loops.fsm.persistence import PersistentExecutor, StatePersistence 

195 

196 # Background mode: spawn detached process and return 

197 if getattr(args, "background", False): 

198 return run_background(loop_name, args, loops_dir, subcommand="resume") 

199 

200 # Register PID file for all foreground runs so cmd_stop can send SIGTERM (BUG-639). 

201 # Background-spawned processes (foreground_internal=True) have their PID written by the 

202 # parent in run_background(); plain foreground runs must write their own PID here. 

203 import os 

204 

205 running_dir = loops_dir / ".running" 

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

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

208 foreground_pid_file: Path | None = pid_file 

209 

210 if not getattr(args, "foreground_internal", False): 

211 pid_file.write_text(str(os.getpid())) 

212 

213 def _cleanup_pid() -> None: 

214 pid_file.unlink(missing_ok=True) 

215 

216 atexit.register(_cleanup_pid) 

217 

218 try: 

219 fsm = load_loop(loop_name, loops_dir, logger) 

220 except FileNotFoundError as e: 

221 logger.error(str(e)) 

222 return 1 

223 except ValueError as e: 

224 logger.error(f"Validation error: {e}") 

225 return 1 

226 

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

228 if "=" not in kv: 

229 raise SystemExit(f"Invalid --context format: {kv!r} (expected KEY=VALUE)") 

230 key, _, value = kv.partition("=") 

231 fsm.context[key.strip()] = value.strip() 

232 

233 if getattr(args, "delay", None) is not None: 

234 fsm.backoff = args.delay 

235 

236 # Apply YAML loop config env-var overrides (CLI flags below overwrite these) 

237 if fsm.config is not None and isinstance(fsm.config.handoff_threshold, int): 

238 os.environ["LL_HANDOFF_THRESHOLD"] = str(fsm.config.handoff_threshold) 

239 

240 if getattr(args, "handoff_threshold", None) is not None: 

241 if not (1 <= args.handoff_threshold <= 100): 

242 raise SystemExit("--handoff-threshold must be between 1 and 100") 

243 os.environ["LL_HANDOFF_THRESHOLD"] = str(args.handoff_threshold) 

244 

245 # Check state before resuming to show context 

246 persistence = StatePersistence(loop_name, loops_dir) 

247 state = persistence.load_state() 

248 if state and state.status == "awaiting_continuation": 

249 print(f"Resuming from context handoff (iteration {state.iteration})...") 

250 if state.continuation_prompt: 

251 # Show truncated continuation context 

252 prompt_preview = state.continuation_prompt[:500] 

253 if len(state.continuation_prompt) > 500: 

254 prompt_preview += "..." 

255 print(f"Context: {prompt_preview}") 

256 print() 

257 

258 executor = PersistentExecutor(fsm, loops_dir=loops_dir) 

259 

260 # Register signal handlers for graceful shutdown (same as cmd_run) 

261 register_loop_signal_handlers(executor, pid_file=foreground_pid_file) 

262 

263 result = executor.resume() 

264 

265 if result is None: 

266 logger.warning(f"Nothing to resume for: {loop_name}") 

267 return 1 

268 

269 duration_sec = result.duration_ms / 1000 

270 if duration_sec < 60: 

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

272 else: 

273 minutes = int(duration_sec // 60) 

274 seconds = duration_sec % 60 

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

276 

277 logger.success( 

278 f"Resumed and completed: {result.final_state} " 

279 f"({result.iterations} iterations, {duration_str})" 

280 ) 

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