Coverage for little_loops / fsm / schema.py: 88%

234 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-14 23:20 -0500

1"""FSM loop schema dataclasses. 

2 

3This module defines the type-safe dataclasses that represent FSM loop 

4definitions. These match the universal FSM schema described in the 

5design documentation. 

6 

7The schema supports: 

8- Multiple evaluator types (exit_code, output_numeric, etc.) 

9- Two-layer transition system (evaluate + route) 

10- Both shorthand (on_success/on_failure) and full routing syntax 

11- Context variables and captured values 

12- LLM evaluation configuration 

13""" 

14 

15from __future__ import annotations 

16 

17from dataclasses import dataclass, field 

18from typing import Any, Literal 

19 

20# Default LLM model for structured evaluation 

21DEFAULT_LLM_MODEL: str = "sonnet" 

22 

23 

24@dataclass 

25class EvaluateConfig: 

26 """Evaluator configuration for action result interpretation. 

27 

28 The evaluator determines how to interpret an action's output and 

29 produce a verdict string for routing. 

30 

31 Attributes: 

32 type: Evaluator type. One of: 

33 - exit_code: Map exit codes to verdicts (default for shell) 

34 - output_numeric: Compare numeric output to target 

35 - output_json: Extract and compare JSON path value 

36 - output_contains: Pattern matching on stdout 

37 - convergence: Compare current vs previous value toward target 

38 - llm_structured: Use LLM with structured output (default for slash) 

39 operator: Comparison operator (eq, ne, lt, le, gt, ge) 

40 target: Target value for comparison 

41 tolerance: Acceptable distance from target (for convergence) 

42 pattern: Pattern string for output_contains 

43 negate: If True, invert the match result (output_contains) 

44 path: JSON path for output_json (jq-style) 

45 prompt: Custom prompt for llm_structured 

46 schema: Custom JSON schema for llm_structured response 

47 min_confidence: Minimum confidence threshold for llm_structured 

48 uncertain_suffix: If True, append _uncertain to low-confidence verdicts 

49 source: Override default source (current action output) 

50 previous: Previous value reference for convergence 

51 direction: Optimization direction for convergence (minimize/maximize) 

52 scope: Paths to limit git diff to for diff_stall evaluator 

53 max_stall: Consecutive no-change iterations before failure (diff_stall) 

54 """ 

55 

56 type: Literal[ 

57 "exit_code", 

58 "output_numeric", 

59 "output_json", 

60 "output_contains", 

61 "convergence", 

62 "diff_stall", 

63 "llm_structured", 

64 "mcp_result", 

65 ] 

66 operator: str | None = None 

67 target: int | float | str | None = None 

68 tolerance: float | str | None = None # str for interpolation (e.g., "${context.tolerance}") 

69 pattern: str | None = None 

70 negate: bool = False 

71 path: str | None = None 

72 prompt: str | None = None 

73 schema: dict[str, Any] | None = None 

74 min_confidence: float = 0.5 

75 uncertain_suffix: bool = False 

76 source: str | None = None 

77 previous: str | None = None 

78 direction: Literal["minimize", "maximize"] = "minimize" 

79 scope: list[str] | None = None # for diff_stall: limit git diff to these paths 

80 max_stall: int = 1 # for diff_stall: consecutive no-change iterations before failure 

81 

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

83 """Convert to dictionary for JSON/YAML serialization.""" 

84 result: dict[str, Any] = {"type": self.type} 

85 

86 # Only include non-None optional fields 

87 if self.operator is not None: 

88 result["operator"] = self.operator 

89 if self.target is not None: 

90 result["target"] = self.target 

91 if self.tolerance is not None: 

92 result["tolerance"] = self.tolerance 

93 if self.pattern is not None: 

94 result["pattern"] = self.pattern 

95 if self.negate: 

96 result["negate"] = self.negate 

97 if self.path is not None: 

98 result["path"] = self.path 

99 if self.prompt is not None: 

100 result["prompt"] = self.prompt 

101 if self.schema is not None: 

102 result["schema"] = self.schema 

103 if self.min_confidence != 0.5: 

104 result["min_confidence"] = self.min_confidence 

105 if self.uncertain_suffix: 

106 result["uncertain_suffix"] = self.uncertain_suffix 

107 if self.source is not None: 

108 result["source"] = self.source 

109 if self.previous is not None: 

110 result["previous"] = self.previous 

111 if self.direction != "minimize": 

112 result["direction"] = self.direction 

113 if self.scope is not None: 

114 result["scope"] = self.scope 

115 if self.max_stall != 1: 

116 result["max_stall"] = self.max_stall 

117 

118 return result 

119 

120 @classmethod 

121 def from_dict(cls, data: dict[str, Any]) -> EvaluateConfig: 

122 """Create from dictionary (JSON/YAML deserialization).""" 

123 return cls( 

124 type=data["type"], 

125 operator=data.get("operator"), 

126 target=data.get("target"), 

127 tolerance=data.get("tolerance"), 

128 pattern=data.get("pattern"), 

129 negate=data.get("negate", False), 

130 path=data.get("path"), 

131 prompt=data.get("prompt"), 

132 schema=data.get("schema"), 

133 min_confidence=data.get("min_confidence", 0.5), 

134 uncertain_suffix=data.get("uncertain_suffix", False), 

135 source=data.get("source"), 

136 previous=data.get("previous"), 

137 direction=data.get("direction", "minimize"), 

138 scope=data.get("scope"), 

139 max_stall=data.get("max_stall", 1), 

140 ) 

141 

142 

143@dataclass 

144class RouteConfig: 

145 """Routing table configuration for verdict-to-state mapping. 

146 

147 Maps verdict strings from evaluators to next state names. 

148 

149 Attributes: 

150 routes: Mapping from verdict string to next state name 

151 default: Default state for unmatched verdicts (the "_" key) 

152 error: State for evaluation/execution errors (the "_error" key) 

153 """ 

154 

155 routes: dict[str, str] = field(default_factory=dict) 

156 default: str | None = None 

157 error: str | None = None 

158 

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

160 """Convert to dictionary for JSON/YAML serialization.""" 

161 result = dict(self.routes) 

162 if self.default is not None: 

163 result["_"] = self.default 

164 if self.error is not None: 

165 result["_error"] = self.error 

166 return result 

167 

168 @classmethod 

169 def from_dict(cls, data: dict[str, Any]) -> RouteConfig: 

170 """Create from dictionary (JSON/YAML deserialization).""" 

171 routes = {k: v for k, v in data.items() if not k.startswith("_")} 

172 return cls( 

173 routes=routes, 

174 default=data.get("_"), 

175 error=data.get("_error"), 

176 ) 

177 

178 

179@dataclass 

180class StateConfig: 

181 """Configuration for a single FSM state. 

182 

183 States can have actions, evaluators, and routing. Supports both 

184 shorthand (on_success/on_failure) and full routing table syntax. 

185 

186 Attributes: 

187 action: Command to execute (shell, slash command, or "server/tool-name" for mcp_tool) 

188 action_type: How to execute the action (prompt, slash_command, shell, mcp_tool). 

189 If None, uses heuristic: / prefix = slash_command, else = shell. 

190 params: MCP tool arguments (only used with action_type: mcp_tool). Supports 

191 ${variable} interpolation in string values. 

192 evaluate: Evaluator configuration for result interpretation 

193 route: Full routing table (verdict -> state mapping) 

194 on_yes: Shorthand for yes verdict routing 

195 on_no: Shorthand for no verdict routing 

196 on_error: Shorthand for error verdict routing 

197 on_partial: Shorthand for partial verdict routing 

198 next: Unconditional transition (no evaluation) 

199 terminal: If True, this is an end state 

200 capture: Variable name to store action output 

201 timeout: Action-level timeout in seconds 

202 on_maintain: State to transition to when maintain=True and loop completes 

203 max_retries: Max consecutive re-entries before transitioning to on_retry_exhausted. 

204 A value of N allows N retries after the initial execution (N+1 total entries). 

205 Requires on_retry_exhausted to also be set. 

206 on_retry_exhausted: State to transition to when max_retries consecutive re-entries 

207 are exceeded. Required when max_retries is set. 

208 """ 

209 

210 action: str | None = None 

211 action_type: Literal["prompt", "slash_command", "shell", "mcp_tool"] | None = None 

212 params: dict[str, Any] = field(default_factory=dict) 

213 evaluate: EvaluateConfig | None = None 

214 route: RouteConfig | None = None 

215 on_yes: str | None = None 

216 on_no: str | None = None 

217 on_error: str | None = None 

218 on_partial: str | None = None 

219 next: str | None = None 

220 terminal: bool = False 

221 capture: str | None = None 

222 timeout: int | None = None 

223 on_maintain: str | None = None 

224 max_retries: int | None = None 

225 on_retry_exhausted: str | None = None 

226 

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

228 """Convert to dictionary for JSON/YAML serialization.""" 

229 result: dict[str, Any] = {} 

230 

231 if self.action is not None: 

232 result["action"] = self.action 

233 if self.action_type is not None: 

234 result["action_type"] = self.action_type 

235 if self.params: 

236 result["params"] = self.params 

237 if self.evaluate is not None: 

238 result["evaluate"] = self.evaluate.to_dict() 

239 if self.route is not None: 

240 result["route"] = self.route.to_dict() 

241 if self.on_yes is not None: 

242 result["on_yes"] = self.on_yes 

243 if self.on_no is not None: 

244 result["on_no"] = self.on_no 

245 if self.on_error is not None: 

246 result["on_error"] = self.on_error 

247 if self.on_partial is not None: 

248 result["on_partial"] = self.on_partial 

249 if self.next is not None: 

250 result["next"] = self.next 

251 if self.terminal: 

252 result["terminal"] = self.terminal 

253 if self.capture is not None: 

254 result["capture"] = self.capture 

255 if self.timeout is not None: 

256 result["timeout"] = self.timeout 

257 if self.on_maintain is not None: 

258 result["on_maintain"] = self.on_maintain 

259 if self.max_retries is not None: 

260 result["max_retries"] = self.max_retries 

261 if self.on_retry_exhausted is not None: 

262 result["on_retry_exhausted"] = self.on_retry_exhausted 

263 

264 return result 

265 

266 @classmethod 

267 def from_dict(cls, data: dict[str, Any]) -> StateConfig: 

268 """Create from dictionary (JSON/YAML deserialization).""" 

269 evaluate = None 

270 if "evaluate" in data: 

271 evaluate = EvaluateConfig.from_dict(data["evaluate"]) 

272 

273 route = None 

274 if "route" in data: 

275 route = RouteConfig.from_dict(data["route"]) 

276 

277 return cls( 

278 action=data.get("action"), 

279 action_type=data.get("action_type"), 

280 params=data.get("params", {}), 

281 evaluate=evaluate, 

282 route=route, 

283 on_yes=data.get("on_yes") or data.get("on_success"), 

284 on_no=data.get("on_no") or data.get("on_failure"), 

285 on_error=data.get("on_error"), 

286 on_partial=data.get("on_partial"), 

287 next=data.get("next"), 

288 terminal=data.get("terminal", False), 

289 capture=data.get("capture"), 

290 timeout=data.get("timeout"), 

291 on_maintain=data.get("on_maintain"), 

292 max_retries=data.get("max_retries"), 

293 on_retry_exhausted=data.get("on_retry_exhausted"), 

294 ) 

295 

296 def get_referenced_states(self) -> set[str]: 

297 """Get all state names referenced by this state configuration. 

298 

299 Returns: 

300 Set of state names that this state can transition to. 

301 """ 

302 refs: set[str] = set() 

303 

304 if self.on_yes is not None: 

305 refs.add(self.on_yes) 

306 if self.on_no is not None: 

307 refs.add(self.on_no) 

308 if self.on_error is not None: 

309 refs.add(self.on_error) 

310 if self.on_partial is not None: 

311 refs.add(self.on_partial) 

312 if self.next is not None: 

313 refs.add(self.next) 

314 if self.on_maintain is not None: 

315 refs.add(self.on_maintain) 

316 if self.on_retry_exhausted is not None: 

317 refs.add(self.on_retry_exhausted) 

318 if self.route is not None: 

319 refs.update(self.route.routes.values()) 

320 if self.route.default is not None: 

321 refs.add(self.route.default) 

322 if self.route.error is not None: 

323 refs.add(self.route.error) 

324 

325 return refs 

326 

327 

328@dataclass 

329class LLMConfig: 

330 """LLM evaluation configuration. 

331 

332 Settings for the llm_structured evaluator. 

333 

334 Attributes: 

335 enabled: If False, disable LLM evaluation entirely 

336 model: Model identifier for LLM calls 

337 max_tokens: Maximum tokens for evaluation response 

338 timeout: Timeout for LLM calls in seconds 

339 """ 

340 

341 enabled: bool = True 

342 model: str = DEFAULT_LLM_MODEL 

343 max_tokens: int = 256 

344 timeout: int = 30 

345 

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

347 """Convert to dictionary for JSON/YAML serialization.""" 

348 result: dict[str, Any] = {} 

349 

350 if not self.enabled: 

351 result["enabled"] = self.enabled 

352 if self.model != DEFAULT_LLM_MODEL: 

353 result["model"] = self.model 

354 if self.max_tokens != 256: 

355 result["max_tokens"] = self.max_tokens 

356 if self.timeout != 30: 

357 result["timeout"] = self.timeout 

358 

359 return result if result else {} 

360 

361 @classmethod 

362 def from_dict(cls, data: dict[str, Any]) -> LLMConfig: 

363 """Create from dictionary (JSON/YAML deserialization).""" 

364 return cls( 

365 enabled=data.get("enabled", True), 

366 model=data.get("model", DEFAULT_LLM_MODEL), 

367 max_tokens=data.get("max_tokens", 256), 

368 timeout=data.get("timeout", 30), 

369 ) 

370 

371 

372@dataclass 

373class FSMLoop: 

374 """Complete FSM loop definition. 

375 

376 The main dataclass representing a loop configuration. 

377 

378 Attributes: 

379 name: Unique loop identifier 

380 initial: Starting state name 

381 states: Mapping from state name to StateConfig 

382 context: User-defined shared variables 

383 scope: Paths this loop operates on (for concurrency control) 

384 max_iterations: Safety limit for loop iterations 

385 backoff: Seconds between iterations 

386 timeout: Max total runtime in seconds (loop-level) 

387 maintain: If True, restart after completion 

388 llm: LLM evaluation configuration 

389 on_handoff: Behavior when handoff signal detected (pause/spawn/terminate) 

390 """ 

391 

392 name: str 

393 initial: str 

394 states: dict[str, StateConfig] 

395 description: str | None = None 

396 context: dict[str, Any] = field(default_factory=dict) 

397 scope: list[str] = field(default_factory=list) 

398 max_iterations: int = 50 

399 backoff: float | None = None 

400 timeout: int | None = None 

401 maintain: bool = False 

402 llm: LLMConfig = field(default_factory=LLMConfig) 

403 on_handoff: Literal["pause", "spawn", "terminate"] = "pause" 

404 input_key: str = "input" 

405 

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

407 """Convert to dictionary for JSON/YAML serialization.""" 

408 result: dict[str, Any] = { 

409 "name": self.name, 

410 "initial": self.initial, 

411 "states": {name: state.to_dict() for name, state in self.states.items()}, 

412 } 

413 

414 if self.description is not None: 

415 result["description"] = self.description 

416 if self.context: 

417 result["context"] = self.context 

418 if self.scope: 

419 result["scope"] = self.scope 

420 if self.max_iterations != 50: 

421 result["max_iterations"] = self.max_iterations 

422 if self.backoff is not None: 

423 result["backoff"] = self.backoff 

424 if self.timeout is not None: 

425 result["timeout"] = self.timeout 

426 if self.maintain: 

427 result["maintain"] = self.maintain 

428 if self.on_handoff != "pause": 

429 result["on_handoff"] = self.on_handoff 

430 if self.input_key != "input": 

431 result["input_key"] = self.input_key 

432 

433 llm_dict = self.llm.to_dict() 

434 if llm_dict: 

435 result["llm"] = llm_dict 

436 

437 return result 

438 

439 @classmethod 

440 def from_dict(cls, data: dict[str, Any]) -> FSMLoop: 

441 """Create from dictionary (JSON/YAML deserialization).""" 

442 states = { 

443 name: StateConfig.from_dict(state_data) 

444 for name, state_data in data.get("states", {}).items() 

445 } 

446 

447 llm = LLMConfig() 

448 if "llm" in data: 

449 llm = LLMConfig.from_dict(data["llm"]) 

450 

451 return cls( 

452 name=data["name"], 

453 initial=data["initial"], 

454 states=states, 

455 description=data.get("description"), 

456 context=data.get("context", {}), 

457 scope=data.get("scope", []), 

458 max_iterations=data.get("max_iterations", 50), 

459 backoff=data.get("backoff"), 

460 timeout=data.get("timeout"), 

461 maintain=data.get("maintain", False), 

462 llm=llm, 

463 on_handoff=data.get("on_handoff", "pause"), 

464 input_key=data.get("input_key", "input"), 

465 ) 

466 

467 def get_all_state_names(self) -> set[str]: 

468 """Get all defined state names. 

469 

470 Returns: 

471 Set of all state names in this FSM. 

472 """ 

473 return set(self.states.keys()) 

474 

475 def get_terminal_states(self) -> set[str]: 

476 """Get all terminal state names. 

477 

478 Returns: 

479 Set of state names where terminal=True. 

480 """ 

481 return {name for name, state in self.states.items() if state.terminal} 

482 

483 def get_all_referenced_states(self) -> set[str]: 

484 """Get all state names referenced by transitions. 

485 

486 This includes the initial state and all states referenced 

487 in routing configurations. 

488 

489 Returns: 

490 Set of all referenced state names. 

491 """ 

492 refs: set[str] = {self.initial} 

493 for state in self.states.values(): 

494 refs.update(state.get_referenced_states()) 

495 return refs