Coverage for little_loops / fsm / executor.py: 91%

403 statements  

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

1"""FSM Executor - Runtime engine for FSM loop execution. 

2 

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""" 

10 

11from __future__ import annotations 

12 

13import json 

14import subprocess 

15import sys 

16import threading 

17import time 

18from collections.abc import Callable 

19from dataclasses import dataclass, field 

20from datetime import UTC, datetime 

21from pathlib import Path 

22from typing import Any, Protocol 

23 

24from little_loops.fsm.evaluators import ( 

25 EvaluationResult, 

26 evaluate, 

27 evaluate_exit_code, 

28 evaluate_llm_structured, 

29 evaluate_mcp_result, 

30) 

31from little_loops.fsm.handoff_handler import HandoffHandler 

32from little_loops.fsm.interpolation import ( 

33 InterpolationContext, 

34 InterpolationError, 

35 interpolate, 

36 interpolate_dict, 

37) 

38from little_loops.fsm.schema import FSMLoop, StateConfig 

39from little_loops.fsm.signal_detector import DetectedSignal, SignalDetector 

40from little_loops.session_log import get_current_session_jsonl 

41 

42 

43@dataclass 

44class ExecutionResult: 

45 """Result from FSM execution. 

46 

47 Attributes: 

48 final_state: Name of the state when execution stopped 

49 iterations: Total iterations executed 

50 terminated_by: Reason for termination (terminal, max_iterations, timeout, signal, error, handoff) 

51 duration_ms: Total execution time in milliseconds 

52 captured: All captured variable values 

53 error: Error message if terminated_by is "error" 

54 handoff: True if execution stopped due to handoff signal 

55 continuation_prompt: Continuation context from handoff signal 

56 """ 

57 

58 final_state: str 

59 iterations: int 

60 terminated_by: str # "terminal", "max_iterations", "timeout", "signal", "error", "handoff" 

61 duration_ms: int 

62 captured: dict[str, dict[str, Any]] 

63 error: str | None = None 

64 handoff: bool = False 

65 continuation_prompt: str | None = None 

66 

67 def to_dict(self) -> dict[str, Any]: 

68 """Convert to dictionary for JSON serialization.""" 

69 result: dict[str, Any] = { 

70 "final_state": self.final_state, 

71 "iterations": self.iterations, 

72 "terminated_by": self.terminated_by, 

73 "duration_ms": self.duration_ms, 

74 "captured": self.captured, 

75 } 

76 if self.error is not None: 

77 result["error"] = self.error 

78 if self.handoff: 

79 result["handoff"] = self.handoff 

80 if self.continuation_prompt is not None: 

81 result["continuation_prompt"] = self.continuation_prompt 

82 return result 

83 

84 

85@dataclass 

86class ActionResult: 

87 """Result from action execution. 

88 

89 Attributes: 

90 output: stdout from the action 

91 stderr: stderr from the action 

92 exit_code: Exit code from the action 

93 duration_ms: Execution time in milliseconds 

94 """ 

95 

96 output: str 

97 stderr: str 

98 exit_code: int 

99 duration_ms: int 

100 

101 

102# Type for event callback 

103EventCallback = Callable[[dict[str, Any]], None] 

104 

105 

106class ActionRunner(Protocol): 

107 """Protocol for action execution.""" 

108 

109 def run( 

110 self, 

111 action: str, 

112 timeout: int, 

113 is_slash_command: bool, 

114 on_output_line: Callable[[str], None] | None = None, 

115 ) -> ActionResult: 

116 """Execute an action and return the result. 

117 

118 Args: 

119 action: The command to execute 

120 timeout: Timeout in seconds 

121 is_slash_command: True if this is a slash command (starts with /) 

122 on_output_line: Optional callback invoked for each output line 

123 

124 Returns: 

125 ActionResult with output, stderr, exit_code, duration_ms 

126 """ 

127 ... 

128 

129 

130class DefaultActionRunner: 

131 """Execute actions via subprocess or Claude CLI.""" 

132 

133 def __init__(self) -> None: 

134 self._current_process: subprocess.Popen[str] | None = None 

135 

136 def run( 

137 self, 

138 action: str, 

139 timeout: int, 

140 is_slash_command: bool, 

141 on_output_line: Callable[[str], None] | None = None, 

142 ) -> ActionResult: 

143 """Execute action and return result, streaming output line by line. 

144 

145 Args: 

146 action: The command to execute 

147 timeout: Timeout in seconds 

148 is_slash_command: True if action starts with / 

149 on_output_line: Optional callback invoked for each stdout line 

150 

151 Returns: 

152 ActionResult with execution details 

153 """ 

154 start = _now_ms() 

155 

156 if is_slash_command: 

157 # Execute via Claude CLI 

158 cmd = [ 

159 "claude", 

160 "--dangerously-skip-permissions", 

161 "--no-session-persistence", 

162 "-p", 

163 action, 

164 ] 

165 else: 

166 # Shell command 

167 cmd = ["bash", "-c", action] 

168 

169 process = subprocess.Popen( 

170 cmd, 

171 stdout=subprocess.PIPE, 

172 stderr=subprocess.PIPE, 

173 text=True, 

174 ) 

175 self._current_process = process 

176 output_chunks: list[str] = [] 

177 stderr_chunks: list[str] = [] 

178 

179 def _drain_stderr() -> None: 

180 assert process.stderr is not None 

181 for line in process.stderr: 

182 stderr_chunks.append(line) 

183 

184 stderr_thread = threading.Thread(target=_drain_stderr, daemon=True) 

185 stderr_thread.start() 

186 

187 try: 

188 for line in process.stdout: # type: ignore[union-attr] 

189 output_chunks.append(line) 

190 if on_output_line: 

191 on_output_line(line.rstrip()) 

192 process.wait(timeout=timeout) 

193 except subprocess.TimeoutExpired: 

194 process.kill() 

195 process.wait() 

196 stderr_thread.join(timeout=5) 

197 return ActionResult( 

198 output="".join(output_chunks), 

199 stderr="".join(stderr_chunks) or "Action timed out", 

200 exit_code=124, 

201 duration_ms=timeout * 1000, 

202 ) 

203 finally: 

204 self._current_process = None 

205 stderr_thread.join(timeout=5) 

206 stderr = "".join(stderr_chunks) 

207 return ActionResult( 

208 output="".join(output_chunks), 

209 stderr=stderr, 

210 exit_code=process.returncode, 

211 duration_ms=_now_ms() - start, 

212 ) 

213 

214 

215@dataclass 

216class SimulationActionRunner: 

217 """Action runner for simulation mode - prompts user instead of executing. 

218 

219 This runner allows users to trace through FSM logic without executing 

220 real commands. It can either prompt interactively for results or use 

221 predefined scenarios. 

222 

223 Attributes: 

224 scenario: Predefined result pattern ("all-pass", "all-fail", "first-fail", "alternating") 

225 call_count: Number of actions simulated so far 

226 calls: List of all actions that would have been executed 

227 """ 

228 

229 scenario: str | None = None 

230 call_count: int = 0 

231 calls: list[str] = field(default_factory=list) 

232 

233 def run( 

234 self, 

235 action: str, 

236 timeout: int, 

237 is_slash_command: bool, 

238 on_output_line: Callable[[str], None] | None = None, 

239 ) -> ActionResult: 

240 """Prompt user for simulated result instead of executing. 

241 

242 Args: 

243 action: The command that would be executed 

244 timeout: Timeout (ignored in simulation) 

245 is_slash_command: Whether this is a slash command 

246 on_output_line: Ignored in simulation 

247 

248 Returns: 

249 ActionResult with simulated exit code 

250 """ 

251 del timeout, on_output_line # unused in simulation 

252 self.calls.append(action) 

253 self.call_count += 1 

254 

255 cmd_type = "slash command" if is_slash_command else "shell command" 

256 print(f" [SIMULATED] Would execute ({cmd_type}): {action}") 

257 

258 if self.scenario: 

259 exit_code = self._scenario_result() 

260 scenario_label = { 

261 "all-pass": "Success (scenario: all-pass)", 

262 "all-fail": "Failure (scenario: all-fail)", 

263 "all-error": "Error (scenario: all-error)", 

264 "first-fail": "Failure" if self.call_count == 1 else "Success", 

265 "alternating": "Failure" if self.call_count % 2 == 1 else "Success", 

266 }.get(self.scenario, "Success") 

267 print(f" [AUTO] Result: {scenario_label}") 

268 else: 

269 exit_code = self._prompt_result() 

270 

271 return ActionResult( 

272 output=f"[simulated output for: {action}]", 

273 stderr="", 

274 exit_code=exit_code, 

275 duration_ms=0, 

276 ) 

277 

278 def _scenario_result(self) -> int: 

279 """Return exit code based on scenario pattern. 

280 

281 Returns: 

282 0 for success, 1 for failure, 2 for error based on scenario logic 

283 """ 

284 if self.scenario == "all-pass": 

285 return 0 

286 elif self.scenario == "all-fail": 

287 return 1 

288 elif self.scenario == "all-error": 

289 return 2 

290 elif self.scenario == "first-fail": 

291 # First call fails, rest pass 

292 return 1 if self.call_count == 1 else 0 

293 elif self.scenario == "alternating": 

294 # Odd calls fail, even calls pass 

295 return 1 if self.call_count % 2 == 1 else 0 

296 return 0 

297 

298 def _prompt_result(self) -> int: 

299 """Prompt user for simulated exit code. 

300 

301 Returns: 

302 Exit code based on user selection 

303 """ 

304 print() 

305 print(" ? What should the simulated result be?") 

306 print(" 1) Success (exit 0) [default]") 

307 print(" 2) Failure (exit 1)") 

308 print(" 3) Error (exit 2)") 

309 

310 while True: 

311 try: 

312 sys.stdout.write(" > ") 

313 sys.stdout.flush() 

314 choice = sys.stdin.readline().strip() 

315 if choice in ("1", ""): 

316 return 0 

317 elif choice == "2": 

318 return 1 

319 elif choice == "3": 

320 return 2 

321 print(" Invalid choice. Enter 1, 2, or 3.") 

322 except (EOFError, KeyboardInterrupt): 

323 print() 

324 return 0 

325 

326 

327def _now_ms() -> int: 

328 """Get current time in milliseconds.""" 

329 return int(time.time() * 1000) 

330 

331 

332def _iso_now() -> str: 

333 """Get current time as ISO 8601 string.""" 

334 return datetime.now(UTC).isoformat() 

335 

336 

337class FSMExecutor: 

338 """Execute an FSM loop. 

339 

340 The executor runs an FSM from its initial state until: 

341 - A terminal state is reached 

342 - max_iterations is exceeded 

343 - A timeout occurs 

344 - A shutdown signal is received 

345 - An unrecoverable error occurs 

346 

347 Events are emitted via the callback for observability. 

348 """ 

349 

350 def __init__( 

351 self, 

352 fsm: FSMLoop, 

353 event_callback: EventCallback | None = None, 

354 action_runner: ActionRunner | None = None, 

355 signal_detector: SignalDetector | None = None, 

356 handoff_handler: HandoffHandler | None = None, 

357 loops_dir: Path | None = None, 

358 ): 

359 """Initialize the executor. 

360 

361 Args: 

362 fsm: The FSM loop to execute 

363 event_callback: Optional callback for events 

364 action_runner: Optional custom action runner (for testing) 

365 signal_detector: Optional signal detector for output parsing 

366 handoff_handler: Optional handler for handoff signals 

367 loops_dir: Base directory for resolving sub-loop references 

368 """ 

369 self.fsm = fsm 

370 self.event_callback = event_callback or (lambda _: None) 

371 self.action_runner: ActionRunner = action_runner or DefaultActionRunner() 

372 self.signal_detector = signal_detector 

373 self.handoff_handler = handoff_handler 

374 self.loops_dir = loops_dir 

375 

376 # Runtime state 

377 self.current_state = fsm.initial 

378 self.iteration = 0 

379 self.captured: dict[str, dict[str, Any]] = {} 

380 self.prev_result: dict[str, Any] | None = None 

381 self.started_at = "" 

382 self.start_time_ms = 0 

383 self.elapsed_offset_ms = ( 

384 0 # milliseconds from segments before current run (set by PersistentExecutor on resume) 

385 ) 

386 

387 # Shutdown flag for graceful signal handling 

388 self._shutdown_requested = False 

389 

390 # Currently running MCP subprocess (set by _run_subprocess, cleared in finally). 

391 # Enables external shutdown code to kill the process on SIGTERM. 

392 self._current_process: subprocess.Popen[str] | None = None 

393 

394 # Pending handoff signal (set by _run_action, checked by main loop) 

395 self._pending_handoff: DetectedSignal | None = None 

396 

397 # Pending error payload from FATAL_ERROR signal (set by _run_action, checked by main loop) 

398 self._pending_error: str | None = None 

399 

400 # Per-state retry tracking for max_retries support. 

401 # _retry_counts[state_name] = number of consecutive re-entries into that state. 

402 # Incremented each time we enter the same state as the previous iteration. 

403 # Reset when a different state is entered, or after retry exhaustion. 

404 self._retry_counts: dict[str, int] = {} 

405 # State entered in the previous iteration (None on first iteration or after resume). 

406 self._prev_state: str | None = None 

407 

408 # Nesting depth for sub-loop event forwarding (0 = top-level, 1+ = sub-loop). 

409 # Set by the parent executor when constructing child executors. 

410 self._depth: int = 0 

411 

412 def request_shutdown(self) -> None: 

413 """Request graceful shutdown of the executor. 

414 

415 Sets a flag that will be checked at the start of each iteration, 

416 allowing the loop to exit cleanly after the current state completes. 

417 """ 

418 self._shutdown_requested = True 

419 

420 def run(self) -> ExecutionResult: 

421 """Execute the FSM until terminal state or limits reached. 

422 

423 Returns: 

424 ExecutionResult with final state and execution metadata 

425 """ 

426 self.started_at = _iso_now() 

427 self.start_time_ms = _now_ms() 

428 

429 self._emit("loop_start", {"loop": self.fsm.name}) 

430 

431 try: 

432 while True: 

433 # Check shutdown request (signal handling) 

434 if self._shutdown_requested: 

435 return self._finish("signal") 

436 

437 # Check iteration limit 

438 if self.iteration >= self.fsm.max_iterations: 

439 return self._finish("max_iterations") 

440 

441 # Check timeout 

442 if self.fsm.timeout: 

443 elapsed = _now_ms() - self.start_time_ms + self.elapsed_offset_ms 

444 if elapsed > self.fsm.timeout * 1000: 

445 return self._finish("timeout") 

446 

447 # Get current state config 

448 state_config = self.fsm.states[self.current_state] 

449 

450 # Update per-state retry tracking based on transition from previous iteration. 

451 # If re-entering the same state consecutively, increment retry count. 

452 # If entering a different state, clear the previous state's retry count. 

453 if self._prev_state is not None: 

454 if self.current_state == self._prev_state: 

455 self._retry_counts[self.current_state] = ( 

456 self._retry_counts.get(self.current_state, 0) + 1 

457 ) 

458 else: 

459 self._retry_counts.pop(self._prev_state, None) 

460 

461 # Check terminal 

462 if state_config.terminal: 

463 # Handle maintain mode - restart loop instead of terminating 

464 if self.fsm.maintain: 

465 self.iteration += 1 

466 maintain_target = state_config.on_maintain or self.fsm.initial 

467 self._emit( 

468 "route", 

469 { 

470 "from": self.current_state, 

471 "to": maintain_target, 

472 "reason": "maintain", 

473 }, 

474 ) 

475 self._prev_state = self.current_state 

476 self.current_state = maintain_target 

477 continue 

478 return self._finish("terminal") 

479 

480 # Check per-state retry limit. If the consecutive re-entry count exceeds 

481 # max_retries, skip execution and route to on_retry_exhausted instead. 

482 if state_config.max_retries is not None: 

483 retry_count = self._retry_counts.get(self.current_state, 0) 

484 if retry_count > state_config.max_retries: 

485 # on_retry_exhausted is guaranteed non-None by validation when 

486 # max_retries is set, but we fall back to an error if misconfigured. 

487 exhausted_state: str = state_config.on_retry_exhausted or "" 

488 if not exhausted_state: 

489 return self._finish( 

490 "error", 

491 error=f"State '{self.current_state}' exceeded max_retries " 

492 "but on_retry_exhausted is not set", 

493 ) 

494 self._emit( 

495 "retry_exhausted", 

496 { 

497 "state": self.current_state, 

498 "retries": retry_count, 

499 "next": exhausted_state, 

500 }, 

501 ) 

502 self._retry_counts.pop(self.current_state, None) 

503 self._prev_state = self.current_state 

504 self.current_state = exhausted_state 

505 continue 

506 

507 self.iteration += 1 

508 self._emit( 

509 "state_enter", 

510 { 

511 "state": self.current_state, 

512 "iteration": self.iteration, 

513 }, 

514 ) 

515 

516 # Execute state 

517 next_state = self._execute_state(state_config) 

518 

519 # Check for pending error signal (FATAL_ERROR) 

520 if self._pending_error is not None: 

521 return self._finish("error", error=self._pending_error) 

522 

523 # Check for pending handoff signal 

524 if self._pending_handoff: 

525 return self._handle_handoff(self._pending_handoff) 

526 

527 # Handle maintain mode 

528 if next_state is None and self.fsm.maintain: 

529 next_state = state_config.on_maintain or self.fsm.initial 

530 

531 # SIGKILL in _execute_state sets shutdown flag and returns None 

532 if next_state is None and self._shutdown_requested: 

533 return self._finish("signal") 

534 

535 if next_state is None: 

536 return self._finish("error", error="No valid transition") 

537 

538 # At this point next_state is guaranteed to be str 

539 resolved_next: str = next_state 

540 

541 self._emit( 

542 "route", 

543 { 

544 "from": self.current_state, 

545 "to": resolved_next, 

546 }, 

547 ) 

548 

549 self._prev_state = self.current_state 

550 self.current_state = resolved_next 

551 

552 # Interruptible backoff sleep between iterations 

553 if self.fsm.backoff and self.fsm.backoff > 0: 

554 deadline = time.time() + self.fsm.backoff 

555 while time.time() < deadline: 

556 if self._shutdown_requested: 

557 break 

558 time.sleep(min(0.1, deadline - time.time())) 

559 

560 except InterpolationError as exc: 

561 return self._finish( 

562 "error", 

563 error=( 

564 f"Missing context variable in state '{self.current_state}': {exc}. " 

565 f"Run with: ll-loop run {self.fsm.name} --context KEY=VALUE" 

566 ), 

567 ) 

568 except Exception as exc: 

569 return self._finish("error", error=str(exc)) 

570 

571 def _execute_sub_loop(self, state: StateConfig, ctx: InterpolationContext) -> str | None: 

572 """Execute a sub-loop state by loading and running a child FSM. 

573 

574 Args: 

575 state: The state configuration with loop field set 

576 ctx: Interpolation context for routing 

577 

578 Returns: 

579 Next state name based on child loop verdict, or None 

580 """ 

581 from little_loops.cli.loop._helpers import resolve_loop_path 

582 from little_loops.fsm.validation import load_and_validate 

583 

584 assert state.loop is not None # guarded by caller 

585 loop_path = resolve_loop_path(state.loop, self.loops_dir or Path(".loops")) 

586 child_fsm, _ = load_and_validate(loop_path) 

587 

588 # Pass parent context to child if requested 

589 if state.context_passthrough: 

590 # Extract .output strings from capture result dicts so ${context.key} resolves 

591 # to the plain output string (e.g. "ENH-123") rather than the full capture object. 

592 captured_as_context = { 

593 k: v["output"] if isinstance(v, dict) and "exit_code" in v else v 

594 for k, v in self.captured.items() 

595 } 

596 child_fsm.context = {**self.fsm.context, **captured_as_context, **child_fsm.context} 

597 

598 depth = self._depth + 1 

599 

600 def _sub_event_callback(event: dict) -> None: 

601 # Only inject depth if not already set by a deeper nested sub-loop 

602 if "depth" not in event: 

603 self.event_callback({**event, "depth": depth}) 

604 else: 

605 self.event_callback(event) 

606 

607 child_executor = FSMExecutor( 

608 child_fsm, 

609 action_runner=self.action_runner, 

610 loops_dir=self.loops_dir, 

611 event_callback=_sub_event_callback, 

612 ) 

613 child_executor._depth = depth # propagate depth for further nesting 

614 child_result = child_executor.run() 

615 

616 # Merge child captures back into parent under the state name 

617 if state.context_passthrough and child_executor.captured: 

618 self.captured[self.current_state] = child_executor.captured 

619 

620 # Route based on child termination reason 

621 if child_result.terminated_by == "terminal": 

622 return interpolate(state.on_yes, ctx) if state.on_yes else None 

623 else: 

624 # error, max_iterations, timeout, signal — all are failure 

625 return interpolate(state.on_no, ctx) if state.on_no else None 

626 

627 def _execute_state(self, state: StateConfig) -> str | None: 

628 """Execute a single state and return next state name. 

629 

630 Args: 

631 state: The state configuration to execute 

632 

633 Returns: 

634 Next state name, or None if no valid transition 

635 """ 

636 # Build interpolation context 

637 ctx = self._build_context() 

638 

639 # Dispatch to sub-loop handler if this is a sub-loop state 

640 if state.loop is not None: 

641 try: 

642 return self._execute_sub_loop(state, ctx) 

643 except (FileNotFoundError, ValueError): 

644 if state.on_error: 

645 return interpolate(state.on_error, ctx) 

646 raise 

647 

648 # Handle unconditional transition 

649 if state.next: 

650 if state.action: 

651 result = self._run_action(state.action, state, ctx) 

652 self.prev_result = { 

653 "output": result.output, 

654 "exit_code": result.exit_code, 

655 "state": self.current_state, 

656 } 

657 if result.exit_code is not None and result.exit_code < 0: 

658 # Process killed by signal — do not silently advance via next 

659 if state.on_error: 

660 return interpolate(state.on_error, ctx) 

661 self.request_shutdown() 

662 return None 

663 return interpolate(state.next, ctx) 

664 

665 # Execute action if present 

666 action_result = None 

667 if state.action: 

668 action_result = self._run_action(state.action, state, ctx) 

669 

670 # Evaluate 

671 eval_result = self._evaluate(state, action_result, ctx) 

672 self.prev_result = { 

673 "output": action_result.output if action_result else "", 

674 "exit_code": action_result.exit_code if action_result else 0, 

675 "state": self.current_state, 

676 } 

677 

678 # Update context with result for routing interpolation 

679 if eval_result: 

680 ctx.result = { 

681 "verdict": eval_result.verdict, 

682 "details": eval_result.details, 

683 } 

684 

685 # Route based on verdict 

686 verdict = eval_result.verdict if eval_result else "yes" 

687 return self._route(state, verdict, ctx) 

688 

689 def _run_action( 

690 self, 

691 action_template: str, 

692 state: StateConfig, 

693 ctx: InterpolationContext, 

694 ) -> ActionResult: 

695 """Execute action and optionally capture result. 

696 

697 Args: 

698 action_template: Action string (may contain variables) 

699 state: State configuration 

700 ctx: Interpolation context 

701 

702 Returns: 

703 ActionResult with output and exit code 

704 """ 

705 action = interpolate(action_template, ctx) 

706 action_mode = self._action_mode(state) 

707 

708 self._emit("action_start", {"action": action, "is_prompt": action_mode == "prompt"}) 

709 

710 def _on_line(line: str) -> None: 

711 self._emit("action_output", {"line": line}) 

712 

713 if action_mode == "mcp_tool": 

714 # Direct MCP tool call — bypass action_runner entirely 

715 interpolated_params = interpolate_dict(state.params, ctx) if state.params else {} 

716 cmd = ["mcp-call", action, json.dumps(interpolated_params)] 

717 result = self._run_subprocess( 

718 cmd, 

719 timeout=state.timeout or self.fsm.default_timeout or 30, 

720 on_output_line=_on_line, 

721 ) 

722 else: 

723 result = self.action_runner.run( 

724 action, 

725 timeout=state.timeout or self.fsm.default_timeout or 3600, 

726 is_slash_command=action_mode == "prompt", 

727 on_output_line=_on_line, 

728 ) 

729 

730 preview = result.output[-2000:].strip() if result.output else None 

731 payload: dict[str, Any] = { 

732 "exit_code": result.exit_code, 

733 "duration_ms": result.duration_ms, 

734 "output_preview": preview, 

735 "is_prompt": action_mode == "prompt", 

736 } 

737 if action_mode == "prompt": 

738 session_jsonl = get_current_session_jsonl() 

739 payload["session_jsonl"] = str(session_jsonl) if session_jsonl else None 

740 self._emit("action_complete", payload) 

741 

742 # Capture if requested 

743 if state.capture: 

744 self.captured[state.capture] = { 

745 "output": result.output, 

746 "stderr": result.stderr, 

747 "exit_code": result.exit_code, 

748 "duration_ms": result.duration_ms, 

749 } 

750 

751 # Check for signals in output 

752 if self.signal_detector: 

753 signal = self.signal_detector.detect_first(result.output) 

754 if signal: 

755 if signal.signal_type == "handoff": 

756 self._pending_handoff = signal 

757 elif signal.signal_type == "error": 

758 self._pending_error = signal.payload 

759 elif signal.signal_type == "stop": 

760 self.request_shutdown() 

761 

762 return result 

763 

764 def _run_subprocess( 

765 self, 

766 cmd: list[str], 

767 timeout: int, 

768 on_output_line: Any | None = None, 

769 ) -> ActionResult: 

770 """Run a subprocess directly and return ActionResult. 

771 

772 Follows the same Popen + stderr-drain-thread pattern as DefaultActionRunner. 

773 

774 Args: 

775 cmd: Command and arguments to execute 

776 timeout: Timeout in seconds 

777 on_output_line: Optional callback for each stdout line 

778 

779 Returns: 

780 ActionResult with output, stderr, exit_code, duration_ms 

781 """ 

782 start = _now_ms() 

783 process = subprocess.Popen( 

784 cmd, 

785 stdout=subprocess.PIPE, 

786 stderr=subprocess.PIPE, 

787 text=True, 

788 ) 

789 self._current_process = process 

790 output_chunks: list[str] = [] 

791 stderr_chunks: list[str] = [] 

792 

793 def _drain_stderr() -> None: 

794 assert process.stderr is not None 

795 for line in process.stderr: 

796 stderr_chunks.append(line) 

797 

798 stderr_thread = threading.Thread(target=_drain_stderr, daemon=True) 

799 stderr_thread.start() 

800 

801 try: 

802 for line in process.stdout: # type: ignore[union-attr] 

803 output_chunks.append(line) 

804 if on_output_line: 

805 on_output_line(line.rstrip()) 

806 process.wait(timeout=timeout) 

807 except subprocess.TimeoutExpired: 

808 process.kill() 

809 process.wait() 

810 stderr_thread.join(timeout=5) 

811 return ActionResult( 

812 output="".join(output_chunks), 

813 stderr="".join(stderr_chunks) or "MCP call timed out", 

814 exit_code=124, 

815 duration_ms=timeout * 1000, 

816 ) 

817 finally: 

818 self._current_process = None 

819 stderr_thread.join(timeout=5) 

820 return ActionResult( 

821 output="".join(output_chunks), 

822 stderr="".join(stderr_chunks), 

823 exit_code=process.returncode, 

824 duration_ms=_now_ms() - start, 

825 ) 

826 

827 def _evaluate( 

828 self, 

829 state: StateConfig, 

830 action_result: ActionResult | None, 

831 ctx: InterpolationContext, 

832 ) -> EvaluationResult | None: 

833 """Evaluate action result. 

834 

835 Args: 

836 state: State configuration 

837 action_result: Result from action execution (may be None) 

838 ctx: Interpolation context 

839 

840 Returns: 

841 EvaluationResult, or None if no evaluation needed 

842 """ 

843 if state.evaluate is None: 

844 # Default evaluation based on action type 

845 if action_result: 

846 action_mode = self._action_mode(state) 

847 

848 if action_mode == "mcp_tool": 

849 # MCP tool call: use mcp_result evaluator 

850 result = evaluate_mcp_result(action_result.output, action_result.exit_code) 

851 elif action_mode == "prompt": 

852 # Slash command or prompt: use LLM evaluation 

853 if not self.fsm.llm.enabled: 

854 result = EvaluationResult( 

855 verdict="error", 

856 details={"error": "LLM evaluation disabled via --no-llm"}, 

857 ) 

858 else: 

859 result = evaluate_llm_structured( 

860 action_result.output, 

861 model=self.fsm.llm.model, 

862 max_tokens=self.fsm.llm.max_tokens, 

863 timeout=self.fsm.llm.timeout, 

864 ) 

865 else: 

866 # Shell command: use exit code 

867 result = evaluate_exit_code(action_result.exit_code) 

868 

869 self._emit( 

870 "evaluate", 

871 { 

872 "type": "default", 

873 "verdict": result.verdict, 

874 **result.details, 

875 }, 

876 ) 

877 return result 

878 return None 

879 

880 # Explicit evaluation config 

881 raw_output = action_result.output if action_result else "" 

882 if state.evaluate.source: 

883 try: 

884 eval_input = interpolate(state.evaluate.source, ctx) 

885 except InterpolationError: 

886 eval_input = raw_output 

887 else: 

888 eval_input = raw_output 

889 

890 if state.evaluate.type == "llm_structured" and not self.fsm.llm.enabled: 

891 result = EvaluationResult( 

892 verdict="error", 

893 details={"error": "LLM evaluation disabled via --no-llm"}, 

894 ) 

895 else: 

896 result = evaluate( 

897 config=state.evaluate, 

898 output=eval_input, 

899 exit_code=action_result.exit_code if action_result else 0, 

900 context=ctx, 

901 ) 

902 

903 self._emit( 

904 "evaluate", 

905 { 

906 "type": state.evaluate.type, 

907 "verdict": result.verdict, 

908 **result.details, 

909 }, 

910 ) 

911 

912 return result 

913 

914 def _route( 

915 self, 

916 state: StateConfig, 

917 verdict: str, 

918 ctx: InterpolationContext, 

919 ) -> str | None: 

920 """Determine next state from verdict. 

921 

922 Resolution order (from design doc): 

923 1. next (unconditional) - handled before this method 

924 2. route (full routing table) 

925 3. on_success/on_failure/on_error (shorthand) 

926 4. terminal - handled in main loop 

927 5. error 

928 

929 Args: 

930 state: State configuration 

931 verdict: Verdict string from evaluation 

932 ctx: Interpolation context 

933 

934 Returns: 

935 Next state name, or None if no valid route 

936 """ 

937 if state.route: 

938 routes = state.route.routes 

939 if verdict in routes: 

940 return self._resolve_route(routes[verdict], ctx) 

941 if state.route.default: 

942 return self._resolve_route(state.route.default, ctx) 

943 if verdict == "error" and state.route.error: 

944 return self._resolve_route(state.route.error, ctx) 

945 return None 

946 

947 # Shorthand routing 

948 if verdict == "yes" and state.on_yes: 

949 return self._resolve_route(state.on_yes, ctx) 

950 if verdict == "no" and state.on_no: 

951 return self._resolve_route(state.on_no, ctx) 

952 if verdict == "error" and state.on_error: 

953 return self._resolve_route(state.on_error, ctx) 

954 if verdict == "partial" and state.on_partial: 

955 return self._resolve_route(state.on_partial, ctx) 

956 if verdict == "blocked" and state.on_blocked: 

957 return self._resolve_route(state.on_blocked, ctx) 

958 

959 return None 

960 

961 def _resolve_route(self, route: str, ctx: InterpolationContext) -> str: 

962 """Resolve route target, handling special tokens. 

963 

964 Args: 

965 route: Route target string 

966 ctx: Interpolation context 

967 

968 Returns: 

969 Resolved state name 

970 """ 

971 if route == "$current": 

972 return self.current_state 

973 return interpolate(route, ctx) 

974 

975 def _action_mode(self, state: StateConfig) -> str: 

976 """Return execution mode for the state: 'prompt', 'shell', or 'mcp_tool'.""" 

977 if state.action_type == "mcp_tool": 

978 return "mcp_tool" 

979 if state.action_type in ("prompt", "slash_command"): 

980 return "prompt" 

981 if state.action_type == "shell": 

982 return "shell" 

983 # Heuristic: / prefix = slash_command (prompt mode) 

984 if state.action is not None and state.action.startswith("/"): 

985 return "prompt" 

986 return "shell" 

987 

988 def _build_context(self) -> InterpolationContext: 

989 """Build interpolation context for current state. 

990 

991 Returns: 

992 InterpolationContext with all runtime values 

993 """ 

994 return InterpolationContext( 

995 context=self.fsm.context, 

996 captured=self.captured, 

997 prev=self.prev_result, 

998 result=None, 

999 state_name=self.current_state, 

1000 iteration=self.iteration, 

1001 loop_name=self.fsm.name, 

1002 started_at=self.started_at, 

1003 elapsed_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms, 

1004 ) 

1005 

1006 def _emit(self, event: str, data: dict[str, Any]) -> None: 

1007 """Emit an event via the callback.""" 

1008 self.event_callback( 

1009 { 

1010 "event": event, 

1011 "ts": _iso_now(), 

1012 **data, 

1013 } 

1014 ) 

1015 

1016 def _finish(self, terminated_by: str, error: str | None = None) -> ExecutionResult: 

1017 """Finalize execution and return result.""" 

1018 self._emit( 

1019 "loop_complete", 

1020 { 

1021 "final_state": self.current_state, 

1022 "iterations": self.iteration, 

1023 "terminated_by": terminated_by, 

1024 }, 

1025 ) 

1026 

1027 return ExecutionResult( 

1028 final_state=self.current_state, 

1029 iterations=self.iteration, 

1030 terminated_by=terminated_by, 

1031 duration_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms, 

1032 captured=self.captured, 

1033 error=error, 

1034 ) 

1035 

1036 def _handle_handoff(self, signal: DetectedSignal) -> ExecutionResult: 

1037 """Handle a detected handoff signal. 

1038 

1039 Emits a handoff_detected event and optionally invokes the handoff handler. 

1040 

1041 Args: 

1042 signal: The detected handoff signal 

1043 

1044 Returns: 

1045 ExecutionResult with handoff information 

1046 """ 

1047 self._emit( 

1048 "handoff_detected", 

1049 { 

1050 "state": self.current_state, 

1051 "iteration": self.iteration, 

1052 "continuation": signal.payload, 

1053 }, 

1054 ) 

1055 

1056 # Invoke handler if configured 

1057 if self.handoff_handler: 

1058 result = self.handoff_handler.handle(self.fsm.name, signal.payload) 

1059 if result.spawned_process is not None: 

1060 self._emit( 

1061 "handoff_spawned", 

1062 { 

1063 "pid": result.spawned_process.pid, 

1064 "state": self.current_state, 

1065 }, 

1066 ) 

1067 

1068 return ExecutionResult( 

1069 final_state=self.current_state, 

1070 iterations=self.iteration, 

1071 terminated_by="handoff", 

1072 duration_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms, 

1073 captured=self.captured, 

1074 handoff=True, 

1075 continuation_prompt=signal.payload, 

1076 )