Coverage for little_loops / cli / loop / testing.py: 86%

145 statements  

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

1"""ll-loop testing subcommands: test, simulate.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6from pathlib import Path 

7 

8from little_loops.cli.loop._helpers import load_loop 

9from little_loops.logger import Logger 

10 

11 

12def cmd_test( 

13 loop_name: str, 

14 loops_dir: Path, 

15 logger: Logger, 

16) -> int: 

17 """Run a single test iteration to verify loop configuration. 

18 

19 Executes the initial state's action and evaluation, then reports 

20 what the loop would do without actually transitioning further. 

21 """ 

22 from little_loops.fsm.evaluators import EvaluationResult, evaluate, evaluate_exit_code 

23 from little_loops.fsm.executor import DefaultActionRunner 

24 from little_loops.fsm.interpolation import InterpolationContext 

25 

26 try: 

27 fsm = load_loop(loop_name, loops_dir, logger) 

28 except FileNotFoundError as e: 

29 logger.error(str(e)) 

30 return 1 

31 except ValueError as e: 

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

33 return 1 

34 

35 # Get initial state 

36 initial = fsm.initial 

37 state_config = fsm.states[initial] 

38 

39 print(f"## Test Iteration: {loop_name}") 

40 print() 

41 print(f"State: {initial}") 

42 

43 # If no action, report and exit 

44 if not state_config.action: 

45 print(f"Initial state '{initial}' has no action to test") 

46 print() 

47 print("\u2713 Loop structure is valid (no check action to execute)") 

48 return 0 

49 

50 action = state_config.action 

51 is_slash = action.startswith("/") or state_config.action_type in ( 

52 "prompt", 

53 "slash_command", 

54 ) 

55 

56 print(f"Action: {action}") 

57 print() 

58 

59 if is_slash: 

60 print("Note: Slash commands require Claude CLI; skipping actual execution.") 

61 print() 

62 print("Verdict: SKIPPED (slash command)") 

63 print() 

64 print("\u2713 Loop structure is valid (slash command not executed)") 

65 return 0 

66 

67 # Run the action 

68 runner = DefaultActionRunner() 

69 timeout = state_config.timeout or 120 

70 result = runner.run(action, timeout=timeout, is_slash_command=False) 

71 

72 print(f"Exit code: {result.exit_code}") 

73 

74 # Truncate output for display 

75 output_lines = result.output.strip().split("\n") 

76 if len(output_lines) > 10: 

77 extra = len(output_lines) - 10 

78 output_preview = "\n".join(output_lines[:10]) + f"\n... ({extra} more lines)" 

79 elif len(result.output) > 500: 

80 output_preview = result.output[:500] + "..." 

81 else: 

82 output_preview = result.output.strip() if result.output.strip() else "(empty)" 

83 

84 print(f"Output:\n{output_preview}") 

85 

86 if result.stderr: 

87 stderr_lines = result.stderr.strip().split("\n") 

88 if len(stderr_lines) > 5: 

89 extra = len(stderr_lines) - 5 

90 stderr_preview = "\n".join(stderr_lines[:5]) + f"\n... ({extra} more lines)" 

91 else: 

92 stderr_preview = result.stderr.strip() 

93 print(f"Stderr:\n{stderr_preview}") 

94 

95 print() 

96 

97 # Evaluate 

98 ctx = InterpolationContext() 

99 eval_result: EvaluationResult 

100 

101 if state_config.evaluate: 

102 eval_result = evaluate( 

103 config=state_config.evaluate, 

104 output=result.output, 

105 exit_code=result.exit_code, 

106 context=ctx, 

107 ) 

108 evaluator_type: str = state_config.evaluate.type 

109 else: 

110 # Default to exit_code evaluation 

111 eval_result = evaluate_exit_code(result.exit_code) 

112 evaluator_type = "exit_code (default)" 

113 

114 print(f"Evaluator: {evaluator_type}") 

115 print(f"Verdict: {eval_result.verdict.upper()}") 

116 

117 if eval_result.details: 

118 for key, value in eval_result.details.items(): 

119 if key != "exit_code" or evaluator_type != "exit_code (default)": 

120 print(f" {key}: {value}") 

121 

122 # Determine next state based on verdict 

123 verdict = eval_result.verdict 

124 next_state = None 

125 

126 if state_config.route: 

127 routes = state_config.route.routes 

128 if verdict in routes: 

129 next_state = routes[verdict] 

130 elif state_config.route.default: 

131 next_state = state_config.route.default 

132 else: 

133 if verdict == "success" and state_config.on_success: 

134 next_state = state_config.on_success 

135 elif verdict == "failure" and state_config.on_failure: 

136 next_state = state_config.on_failure 

137 elif verdict == "error" and state_config.on_error: 

138 next_state = state_config.on_error 

139 

140 print() 

141 if next_state: 

142 print(f"Would transition: {initial} \u2192 {next_state}") 

143 else: 

144 print(f"Would transition: {initial} \u2192 (no route for '{verdict}')") 

145 

146 # Summary 

147 print() 

148 has_error = eval_result.verdict == "error" or "error" in eval_result.details 

149 if has_error: 

150 print("\u26a0 Loop has issues - review the error details above") 

151 return 1 

152 else: 

153 print("\u2713 Loop appears to be configured correctly") 

154 return 0 

155 

156 

157def cmd_simulate( 

158 loop_name: str, 

159 args: argparse.Namespace, 

160 loops_dir: Path, 

161 logger: Logger, 

162) -> int: 

163 """Run interactive simulation of loop execution. 

164 

165 Traces through loop logic without executing commands, allowing users 

166 to verify state transitions and understand loop behavior. 

167 """ 

168 from little_loops.fsm.executor import FSMExecutor, SimulationActionRunner 

169 

170 try: 

171 fsm = load_loop(loop_name, loops_dir, logger) 

172 except FileNotFoundError as e: 

173 logger.error(str(e)) 

174 return 1 

175 except ValueError as e: 

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

177 return 1 

178 

179 # Apply CLI overrides 

180 if args.max_iterations: 

181 fsm.max_iterations = args.max_iterations 

182 else: 

183 # Limit iterations for simulation safety (cap at 20 unless overridden) 

184 if fsm.max_iterations > 20: 

185 logger.info(f"Limiting simulation to 20 iterations (loop config: {fsm.max_iterations})") 

186 fsm.max_iterations = 20 

187 

188 # Create simulation runner 

189 sim_runner = SimulationActionRunner(scenario=args.scenario) 

190 

191 # Track simulation state 

192 states_visited: list[str] = [] 

193 

194 def simulation_callback(event: dict) -> None: 

195 """Display simulation progress.""" 

196 event_type = event.get("event") 

197 

198 if event_type == "state_enter": 

199 iteration = event.get("iteration", 0) 

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

201 states_visited.append(state) 

202 print() 

203 print(f"[{iteration}] State: {state}") 

204 

205 elif event_type == "action_start": 

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

207 action_display = action[:70] + "..." if len(action) > 70 else action 

208 print(f" Action: {action_display}") 

209 

210 elif event_type == "evaluate": 

211 evaluator = event.get("type", "exit_code") 

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

213 print(f" Evaluator: {evaluator}") 

214 print(f" Result: {verdict.upper()}") 

215 

216 elif event_type == "route": 

217 from_state = event.get("from", "") 

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

219 print(f" Transition: {from_state} \u2192 {to_state}") 

220 

221 # Print header 

222 mode_str = f"scenario={args.scenario}" if args.scenario else "interactive" 

223 print(f"=== SIMULATION: {fsm.name} ({mode_str}) ===") 

224 

225 # Run simulation 

226 executor = FSMExecutor( 

227 fsm, 

228 event_callback=simulation_callback, 

229 action_runner=sim_runner, 

230 ) 

231 result = executor.run() 

232 

233 # Print summary 

234 print() 

235 print("=== Summary ===") 

236 arrow = " \u2192 " 

237 print(f"States visited: {arrow.join(states_visited)}") 

238 print(f"Iterations: {result.iterations}") 

239 print(f"Would have executed {len(sim_runner.calls)} commands") 

240 print(f"Terminated by: {result.terminated_by}") 

241 

242 return 0