Coverage for little_loops / fsm / executor.py: 89%
254 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
1"""FSM Executor - Runtime engine for FSM loop execution.
3This module provides the execution engine that runs FSM loops:
4- Executes actions (shell commands or slash commands)
5- Evaluates results using appropriate evaluators
6- Routes to next states based on verdicts
7- Tracks iteration count and enforces limits
8- Manages captured variables and context
9"""
11from __future__ import annotations
13import subprocess
14import sys
15import time
16from collections.abc import Callable
17from dataclasses import dataclass, field
18from datetime import UTC, datetime
19from typing import Any, Protocol
21from little_loops.fsm.evaluators import (
22 EvaluationResult,
23 evaluate,
24 evaluate_exit_code,
25 evaluate_llm_structured,
26)
27from little_loops.fsm.handoff_handler import HandoffHandler
28from little_loops.fsm.interpolation import InterpolationContext, interpolate
29from little_loops.fsm.schema import FSMLoop, StateConfig
30from little_loops.fsm.signal_detector import DetectedSignal, SignalDetector
33@dataclass
34class ExecutionResult:
35 """Result from FSM execution.
37 Attributes:
38 final_state: Name of the state when execution stopped
39 iterations: Total iterations executed
40 terminated_by: Reason for termination (terminal, max_iterations, timeout, signal, error, handoff)
41 duration_ms: Total execution time in milliseconds
42 captured: All captured variable values
43 error: Error message if terminated_by is "error"
44 handoff: True if execution stopped due to handoff signal
45 continuation_prompt: Continuation context from handoff signal
46 """
48 final_state: str
49 iterations: int
50 terminated_by: str # "terminal", "max_iterations", "timeout", "signal", "error", "handoff"
51 duration_ms: int
52 captured: dict[str, dict[str, Any]]
53 error: str | None = None
54 handoff: bool = False
55 continuation_prompt: str | None = None
57 def to_dict(self) -> dict[str, Any]:
58 """Convert to dictionary for JSON serialization."""
59 result: dict[str, Any] = {
60 "final_state": self.final_state,
61 "iterations": self.iterations,
62 "terminated_by": self.terminated_by,
63 "duration_ms": self.duration_ms,
64 "captured": self.captured,
65 }
66 if self.error is not None:
67 result["error"] = self.error
68 if self.handoff:
69 result["handoff"] = self.handoff
70 if self.continuation_prompt is not None:
71 result["continuation_prompt"] = self.continuation_prompt
72 return result
75@dataclass
76class ActionResult:
77 """Result from action execution.
79 Attributes:
80 output: stdout from the action
81 stderr: stderr from the action
82 exit_code: Exit code from the action
83 duration_ms: Execution time in milliseconds
84 """
86 output: str
87 stderr: str
88 exit_code: int
89 duration_ms: int
92# Type for event callback
93EventCallback = Callable[[dict[str, Any]], None]
96class ActionRunner(Protocol):
97 """Protocol for action execution."""
99 def run(
100 self,
101 action: str,
102 timeout: int,
103 is_slash_command: bool,
104 ) -> ActionResult:
105 """Execute an action and return the result.
107 Args:
108 action: The command to execute
109 timeout: Timeout in seconds
110 is_slash_command: True if this is a slash command (starts with /)
112 Returns:
113 ActionResult with output, stderr, exit_code, duration_ms
114 """
115 ...
118class DefaultActionRunner:
119 """Execute actions via subprocess or Claude CLI."""
121 def run(
122 self,
123 action: str,
124 timeout: int,
125 is_slash_command: bool,
126 ) -> ActionResult:
127 """Execute action and return result.
129 Args:
130 action: The command to execute
131 timeout: Timeout in seconds
132 is_slash_command: True if action starts with /
134 Returns:
135 ActionResult with execution details
136 """
137 start = _now_ms()
139 if is_slash_command:
140 # Execute via Claude CLI
141 cmd = [
142 "claude",
143 "--dangerously-skip-permissions",
144 "-p",
145 action,
146 ]
147 else:
148 # Shell command
149 cmd = ["bash", "-c", action]
151 try:
152 result = subprocess.run(
153 cmd,
154 capture_output=True,
155 text=True,
156 timeout=timeout,
157 )
158 return ActionResult(
159 output=result.stdout,
160 stderr=result.stderr,
161 exit_code=result.returncode,
162 duration_ms=_now_ms() - start,
163 )
164 except subprocess.TimeoutExpired:
165 return ActionResult(
166 output="",
167 stderr="Action timed out",
168 exit_code=124, # Standard timeout exit code
169 duration_ms=timeout * 1000,
170 )
173@dataclass
174class SimulationActionRunner:
175 """Action runner for simulation mode - prompts user instead of executing.
177 This runner allows users to trace through FSM logic without executing
178 real commands. It can either prompt interactively for results or use
179 predefined scenarios.
181 Attributes:
182 scenario: Predefined result pattern ("all-pass", "all-fail", "first-fail", "alternating")
183 call_count: Number of actions simulated so far
184 calls: List of all actions that would have been executed
185 """
187 scenario: str | None = None
188 call_count: int = 0
189 calls: list[str] = field(default_factory=list)
191 def run(
192 self,
193 action: str,
194 timeout: int,
195 is_slash_command: bool,
196 ) -> ActionResult:
197 """Prompt user for simulated result instead of executing.
199 Args:
200 action: The command that would be executed
201 timeout: Timeout (ignored in simulation)
202 is_slash_command: Whether this is a slash command
204 Returns:
205 ActionResult with simulated exit code
206 """
207 del timeout # unused in simulation
208 self.calls.append(action)
209 self.call_count += 1
211 cmd_type = "slash command" if is_slash_command else "shell command"
212 print(f" [SIMULATED] Would execute ({cmd_type}): {action}")
214 if self.scenario:
215 exit_code = self._scenario_result()
216 scenario_label = {
217 "all-pass": "Success (scenario: all-pass)",
218 "all-fail": "Failure (scenario: all-fail)",
219 "first-fail": "Failure" if self.call_count == 1 else "Success",
220 "alternating": "Failure" if self.call_count % 2 == 1 else "Success",
221 }.get(self.scenario, "Success")
222 print(f" [AUTO] Result: {scenario_label}")
223 else:
224 exit_code = self._prompt_result()
226 return ActionResult(
227 output=f"[simulated output for: {action}]",
228 stderr="",
229 exit_code=exit_code,
230 duration_ms=0,
231 )
233 def _scenario_result(self) -> int:
234 """Return exit code based on scenario pattern.
236 Returns:
237 0 for success, 1 for failure based on scenario logic
238 """
239 if self.scenario == "all-pass":
240 return 0
241 elif self.scenario == "all-fail":
242 return 1
243 elif self.scenario == "first-fail":
244 # First call fails, rest pass
245 return 1 if self.call_count == 1 else 0
246 elif self.scenario == "alternating":
247 # Odd calls fail, even calls pass
248 return 1 if self.call_count % 2 == 1 else 0
249 return 0
251 def _prompt_result(self) -> int:
252 """Prompt user for simulated exit code.
254 Returns:
255 Exit code based on user selection
256 """
257 print()
258 print(" ? What should the simulated result be?")
259 print(" 1) Success (exit 0) [default]")
260 print(" 2) Failure (exit 1)")
261 print(" 3) Error (exit 2)")
263 while True:
264 try:
265 sys.stdout.write(" > ")
266 sys.stdout.flush()
267 choice = sys.stdin.readline().strip()
268 if choice in ("1", ""):
269 return 0
270 elif choice == "2":
271 return 1
272 elif choice == "3":
273 return 2
274 print(" Invalid choice. Enter 1, 2, or 3.")
275 except (EOFError, KeyboardInterrupt):
276 print()
277 return 0
280def _now_ms() -> int:
281 """Get current time in milliseconds."""
282 return int(time.time() * 1000)
285def _iso_now() -> str:
286 """Get current time as ISO 8601 string."""
287 return datetime.now(UTC).isoformat()
290class FSMExecutor:
291 """Execute an FSM loop.
293 The executor runs an FSM from its initial state until:
294 - A terminal state is reached
295 - max_iterations is exceeded
296 - A timeout occurs
297 - A shutdown signal is received
298 - An unrecoverable error occurs
300 Events are emitted via the callback for observability.
301 """
303 def __init__(
304 self,
305 fsm: FSMLoop,
306 event_callback: EventCallback | None = None,
307 action_runner: ActionRunner | None = None,
308 signal_detector: SignalDetector | None = None,
309 handoff_handler: HandoffHandler | None = None,
310 ):
311 """Initialize the executor.
313 Args:
314 fsm: The FSM loop to execute
315 event_callback: Optional callback for events
316 action_runner: Optional custom action runner (for testing)
317 signal_detector: Optional signal detector for output parsing
318 handoff_handler: Optional handler for handoff signals
319 """
320 self.fsm = fsm
321 self.event_callback = event_callback or (lambda _: None)
322 self.action_runner: ActionRunner = action_runner or DefaultActionRunner()
323 self.signal_detector = signal_detector
324 self.handoff_handler = handoff_handler
326 # Runtime state
327 self.current_state = fsm.initial
328 self.iteration = 0
329 self.captured: dict[str, dict[str, Any]] = {}
330 self.prev_result: dict[str, Any] | None = None
331 self.started_at = ""
332 self.start_time_ms = 0
333 self.elapsed_offset_ms = 0 # milliseconds from segments before current run (set by PersistentExecutor on resume)
335 # Shutdown flag for graceful signal handling
336 self._shutdown_requested = False
338 # Pending handoff signal (set by _run_action, checked by main loop)
339 self._pending_handoff: DetectedSignal | None = None
341 # Pending error payload from FATAL_ERROR signal (set by _run_action, checked by main loop)
342 self._pending_error: str | None = None
344 def request_shutdown(self) -> None:
345 """Request graceful shutdown of the executor.
347 Sets a flag that will be checked at the start of each iteration,
348 allowing the loop to exit cleanly after the current state completes.
349 """
350 self._shutdown_requested = True
352 def run(self) -> ExecutionResult:
353 """Execute the FSM until terminal state or limits reached.
355 Returns:
356 ExecutionResult with final state and execution metadata
357 """
358 self.started_at = _iso_now()
359 self.start_time_ms = _now_ms()
361 self._emit("loop_start", {"loop": self.fsm.name})
363 try:
364 while True:
365 # Check shutdown request (signal handling)
366 if self._shutdown_requested:
367 return self._finish("signal")
369 # Check iteration limit
370 if self.iteration >= self.fsm.max_iterations:
371 return self._finish("max_iterations")
373 # Check timeout
374 if self.fsm.timeout:
375 elapsed = _now_ms() - self.start_time_ms + self.elapsed_offset_ms
376 if elapsed > self.fsm.timeout * 1000:
377 return self._finish("timeout")
379 # Get current state config
380 state_config = self.fsm.states[self.current_state]
382 # Check terminal
383 if state_config.terminal:
384 # Handle maintain mode - restart loop instead of terminating
385 if self.fsm.maintain:
386 self.iteration += 1
387 maintain_target = state_config.on_maintain or self.fsm.initial
388 self._emit(
389 "route",
390 {
391 "from": self.current_state,
392 "to": maintain_target,
393 "reason": "maintain",
394 },
395 )
396 self.current_state = maintain_target
397 continue
398 return self._finish("terminal")
400 self.iteration += 1
401 self._emit(
402 "state_enter",
403 {
404 "state": self.current_state,
405 "iteration": self.iteration,
406 },
407 )
409 # Execute state
410 next_state = self._execute_state(state_config)
412 # Check for pending error signal (FATAL_ERROR)
413 if self._pending_error is not None:
414 return self._finish("error", error=self._pending_error)
416 # Check for pending handoff signal
417 if self._pending_handoff:
418 return self._handle_handoff(self._pending_handoff)
420 # Handle maintain mode
421 if next_state is None and self.fsm.maintain:
422 next_state = state_config.on_maintain or self.fsm.initial
424 if next_state is None:
425 return self._finish("error", error="No valid transition")
427 # At this point next_state is guaranteed to be str
428 resolved_next: str = next_state
430 self._emit(
431 "route",
432 {
433 "from": self.current_state,
434 "to": resolved_next,
435 },
436 )
438 self.current_state = resolved_next
440 # Interruptible backoff sleep between iterations
441 if self.fsm.backoff and self.fsm.backoff > 0:
442 deadline = time.time() + self.fsm.backoff
443 while time.time() < deadline:
444 if self._shutdown_requested:
445 break
446 time.sleep(min(0.1, deadline - time.time()))
448 except Exception as exc:
449 return self._finish("error", error=str(exc))
451 def _execute_state(self, state: StateConfig) -> str | None:
452 """Execute a single state and return next state name.
454 Args:
455 state: The state configuration to execute
457 Returns:
458 Next state name, or None if no valid transition
459 """
460 # Build interpolation context
461 ctx = self._build_context()
463 # Handle unconditional transition
464 if state.next:
465 if state.action:
466 self._run_action(state.action, state, ctx)
467 return interpolate(state.next, ctx)
469 # Execute action if present
470 action_result = None
471 if state.action:
472 action_result = self._run_action(state.action, state, ctx)
474 # Evaluate
475 eval_result = self._evaluate(state, action_result, ctx)
476 self.prev_result = {
477 "output": action_result.output if action_result else "",
478 "exit_code": action_result.exit_code if action_result else 0,
479 "state": self.current_state,
480 }
482 # Update context with result for routing interpolation
483 if eval_result:
484 ctx.result = {
485 "verdict": eval_result.verdict,
486 "details": eval_result.details,
487 }
489 # Route based on verdict
490 verdict = eval_result.verdict if eval_result else "success"
491 return self._route(state, verdict, ctx)
493 def _run_action(
494 self,
495 action_template: str,
496 state: StateConfig,
497 ctx: InterpolationContext,
498 ) -> ActionResult:
499 """Execute action and optionally capture result.
501 Args:
502 action_template: Action string (may contain variables)
503 state: State configuration
504 ctx: Interpolation context
506 Returns:
507 ActionResult with output and exit code
508 """
509 action = interpolate(action_template, ctx)
511 self._emit("action_start", {"action": action})
513 # Determine if this is a slash command/prompt based on action_type or heuristic
514 if state.action_type is not None:
515 is_slash_command = state.action_type in ("prompt", "slash_command")
516 else:
517 is_slash_command = action.startswith("/")
519 result = self.action_runner.run(
520 action,
521 timeout=state.timeout or 120,
522 is_slash_command=is_slash_command,
523 )
525 self._emit(
526 "action_complete",
527 {
528 "exit_code": result.exit_code,
529 "duration_ms": result.duration_ms,
530 },
531 )
533 # Capture if requested
534 if state.capture:
535 self.captured[state.capture] = {
536 "output": result.output,
537 "stderr": result.stderr,
538 "exit_code": result.exit_code,
539 "duration_ms": result.duration_ms,
540 }
542 # Check for signals in output
543 if self.signal_detector:
544 signal = self.signal_detector.detect_first(result.output)
545 if signal:
546 if signal.signal_type == "handoff":
547 self._pending_handoff = signal
548 elif signal.signal_type == "error":
549 self._pending_error = signal.payload
550 elif signal.signal_type == "stop":
551 self.request_shutdown()
553 return result
555 def _evaluate(
556 self,
557 state: StateConfig,
558 action_result: ActionResult | None,
559 ctx: InterpolationContext,
560 ) -> EvaluationResult | None:
561 """Evaluate action result.
563 Args:
564 state: State configuration
565 action_result: Result from action execution (may be None)
566 ctx: Interpolation context
568 Returns:
569 EvaluationResult, or None if no evaluation needed
570 """
571 if state.evaluate is None:
572 # Default evaluation based on action type
573 if action_result:
574 # Determine if this is a prompt/slash command for default evaluation
575 if state.action_type is not None:
576 is_prompt = state.action_type in ("prompt", "slash_command")
577 else:
578 is_prompt = state.action is not None and state.action.startswith("/")
580 if is_prompt:
581 # Slash command or prompt: use LLM evaluation
582 result = evaluate_llm_structured(
583 action_result.output,
584 model=self.fsm.llm.model,
585 max_tokens=self.fsm.llm.max_tokens,
586 timeout=self.fsm.llm.timeout,
587 )
588 else:
589 # Shell command: use exit code
590 result = evaluate_exit_code(action_result.exit_code)
592 self._emit(
593 "evaluate",
594 {
595 "type": "default",
596 "verdict": result.verdict,
597 },
598 )
599 return result
600 return None
602 # Explicit evaluation config
603 result = evaluate(
604 config=state.evaluate,
605 output=action_result.output if action_result else "",
606 exit_code=action_result.exit_code if action_result else 0,
607 context=ctx,
608 )
610 self._emit(
611 "evaluate",
612 {
613 "type": state.evaluate.type,
614 "verdict": result.verdict,
615 **result.details,
616 },
617 )
619 return result
621 def _route(
622 self,
623 state: StateConfig,
624 verdict: str,
625 ctx: InterpolationContext,
626 ) -> str | None:
627 """Determine next state from verdict.
629 Resolution order (from design doc):
630 1. next (unconditional) - handled before this method
631 2. route (full routing table)
632 3. on_success/on_failure/on_error (shorthand)
633 4. terminal - handled in main loop
634 5. error
636 Args:
637 state: State configuration
638 verdict: Verdict string from evaluation
639 ctx: Interpolation context
641 Returns:
642 Next state name, or None if no valid route
643 """
644 if state.route:
645 routes = state.route.routes
646 if verdict in routes:
647 return self._resolve_route(routes[verdict], ctx)
648 if state.route.default:
649 return self._resolve_route(state.route.default, ctx)
650 if verdict == "error" and state.route.error:
651 return self._resolve_route(state.route.error, ctx)
652 return None
654 # Shorthand routing
655 if verdict == "success" and state.on_success:
656 return self._resolve_route(state.on_success, ctx)
657 if verdict == "failure" and state.on_failure:
658 return self._resolve_route(state.on_failure, ctx)
659 if verdict == "error" and state.on_error:
660 return self._resolve_route(state.on_error, ctx)
662 return None
664 def _resolve_route(self, route: str, ctx: InterpolationContext) -> str:
665 """Resolve route target, handling special tokens.
667 Args:
668 route: Route target string
669 ctx: Interpolation context
671 Returns:
672 Resolved state name
673 """
674 if route == "$current":
675 return self.current_state
676 return interpolate(route, ctx)
678 def _build_context(self) -> InterpolationContext:
679 """Build interpolation context for current state.
681 Returns:
682 InterpolationContext with all runtime values
683 """
684 return InterpolationContext(
685 context=self.fsm.context,
686 captured=self.captured,
687 prev=self.prev_result,
688 result=None,
689 state_name=self.current_state,
690 iteration=self.iteration,
691 loop_name=self.fsm.name,
692 started_at=self.started_at,
693 elapsed_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms,
694 )
696 def _emit(self, event: str, data: dict[str, Any]) -> None:
697 """Emit an event via the callback."""
698 self.event_callback(
699 {
700 "event": event,
701 "ts": _iso_now(),
702 **data,
703 }
704 )
706 def _finish(self, terminated_by: str, error: str | None = None) -> ExecutionResult:
707 """Finalize execution and return result."""
708 self._emit(
709 "loop_complete",
710 {
711 "final_state": self.current_state,
712 "iterations": self.iteration,
713 "terminated_by": terminated_by,
714 },
715 )
717 return ExecutionResult(
718 final_state=self.current_state,
719 iterations=self.iteration,
720 terminated_by=terminated_by,
721 duration_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms,
722 captured=self.captured,
723 error=error,
724 )
726 def _handle_handoff(self, signal: DetectedSignal) -> ExecutionResult:
727 """Handle a detected handoff signal.
729 Emits a handoff_detected event and optionally invokes the handoff handler.
731 Args:
732 signal: The detected handoff signal
734 Returns:
735 ExecutionResult with handoff information
736 """
737 self._emit(
738 "handoff_detected",
739 {
740 "state": self.current_state,
741 "iteration": self.iteration,
742 "continuation": signal.payload,
743 },
744 )
746 # Invoke handler if configured
747 if self.handoff_handler:
748 result = self.handoff_handler.handle(self.fsm.name, signal.payload)
749 if result.spawned_process is not None:
750 self._emit(
751 "handoff_spawned",
752 {
753 "pid": result.spawned_process.pid,
754 "state": self.current_state,
755 },
756 )
758 return ExecutionResult(
759 final_state=self.current_state,
760 iterations=self.iteration,
761 terminated_by="handoff",
762 duration_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms,
763 captured=self.captured,
764 handoff=True,
765 continuation_prompt=signal.payload,
766 )