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

105 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

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

2 

3from __future__ import annotations 

4 

5import argparse 

6import errno 

7import os 

8import signal 

9from pathlib import Path 

10 

11from little_loops.cli.loop._helpers import load_loop 

12from little_loops.logger import Logger 

13 

14 

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

16 """Read and validate a PID file. 

17 

18 Returns: 

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

20 """ 

21 if not pid_file.exists(): 

22 return None 

23 try: 

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

25 except (ValueError, OSError): 

26 return None 

27 

28 

29def _process_alive(pid: int) -> bool: 

30 """Check if a process is still running.""" 

31 try: 

32 os.kill(pid, 0) 

33 return True 

34 except OSError as e: 

35 if e.errno == errno.ESRCH: 

36 return False # No such process 

37 return True # EPERM or other: process exists, no permission 

38 

39 

40def cmd_status( 

41 loop_name: str, 

42 loops_dir: Path, 

43 logger: Logger, 

44) -> int: 

45 """Show loop status.""" 

46 from little_loops.fsm.persistence import StatePersistence 

47 

48 persistence = StatePersistence(loop_name, loops_dir) 

49 state = persistence.load_state() 

50 

51 if state is None: 

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

53 return 1 

54 

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

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

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

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

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

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

61 

62 # Show PID info if available (background mode) 

63 running_dir = loops_dir / ".running" 

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

65 pid = _read_pid_file(pid_file) 

66 if pid is not None: 

67 if _process_alive(pid): 

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

69 else: 

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

71 

72 if state.continuation_prompt: 

73 # Show truncated continuation context 

74 prompt_preview = state.continuation_prompt[:200] 

75 if len(state.continuation_prompt) > 200: 

76 prompt_preview += "..." 

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

78 return 0 

79 

80 

81def cmd_stop( 

82 loop_name: str, 

83 loops_dir: Path, 

84 logger: Logger, 

85) -> int: 

86 """Stop a running loop.""" 

87 from little_loops.fsm.persistence import StatePersistence 

88 

89 persistence = StatePersistence(loop_name, loops_dir) 

90 state = persistence.load_state() 

91 

92 if state is None: 

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

94 return 1 

95 

96 if state.status != "running": 

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

98 return 1 

99 

100 state.status = "interrupted" 

101 persistence.save_state(state) 

102 

103 # Send SIGTERM to background process if PID file exists 

104 running_dir = loops_dir / ".running" 

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

106 pid = _read_pid_file(pid_file) 

107 if pid is not None: 

108 if _process_alive(pid): 

109 os.kill(pid, signal.SIGTERM) 

110 logger.success(f"Sent SIGTERM to {loop_name} (PID: {pid})") 

111 else: 

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

113 pid_file.unlink(missing_ok=True) 

114 else: 

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

116 

117 return 0 

118 

119 

120def cmd_resume( 

121 loop_name: str, 

122 args: argparse.Namespace, 

123 loops_dir: Path, 

124 logger: Logger, 

125) -> int: 

126 """Resume an interrupted loop.""" 

127 from little_loops.fsm.persistence import PersistentExecutor, StatePersistence 

128 

129 try: 

130 fsm = load_loop(loop_name, loops_dir, logger) 

131 except FileNotFoundError as e: 

132 logger.error(str(e)) 

133 return 1 

134 except ValueError as e: 

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

136 return 1 

137 

138 # Check state before resuming to show context 

139 persistence = StatePersistence(loop_name, loops_dir) 

140 state = persistence.load_state() 

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

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

143 if state.continuation_prompt: 

144 # Show truncated continuation context 

145 prompt_preview = state.continuation_prompt[:500] 

146 if len(state.continuation_prompt) > 500: 

147 prompt_preview += "..." 

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

149 print() 

150 

151 executor = PersistentExecutor(fsm, loops_dir=loops_dir) 

152 result = executor.resume() 

153 

154 if result is None: 

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

156 return 1 

157 

158 duration_sec = result.duration_ms / 1000 

159 if duration_sec < 60: 

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

161 else: 

162 minutes = int(duration_sec // 60) 

163 seconds = duration_sec % 60 

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

165 

166 logger.success( 

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

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

169 ) 

170 return 0 if result.terminated_by == "terminal" else 1