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

209 statements  

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

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

53 

54 type: Literal[ 

55 "exit_code", 

56 "output_numeric", 

57 "output_json", 

58 "output_contains", 

59 "convergence", 

60 "llm_structured", 

61 ] 

62 operator: str | None = None 

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

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

65 pattern: str | None = None 

66 negate: bool = False 

67 path: str | None = None 

68 prompt: str | None = None 

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

70 min_confidence: float = 0.5 

71 uncertain_suffix: bool = False 

72 source: str | None = None 

73 previous: str | None = None 

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

75 

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

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

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

79 

80 # Only include non-None optional fields 

81 if self.operator is not None: 

82 result["operator"] = self.operator 

83 if self.target is not None: 

84 result["target"] = self.target 

85 if self.tolerance is not None: 

86 result["tolerance"] = self.tolerance 

87 if self.pattern is not None: 

88 result["pattern"] = self.pattern 

89 if self.negate: 

90 result["negate"] = self.negate 

91 if self.path is not None: 

92 result["path"] = self.path 

93 if self.prompt is not None: 

94 result["prompt"] = self.prompt 

95 if self.schema is not None: 

96 result["schema"] = self.schema 

97 if self.min_confidence != 0.5: 

98 result["min_confidence"] = self.min_confidence 

99 if self.uncertain_suffix: 

100 result["uncertain_suffix"] = self.uncertain_suffix 

101 if self.source is not None: 

102 result["source"] = self.source 

103 if self.previous is not None: 

104 result["previous"] = self.previous 

105 if self.direction != "minimize": 

106 result["direction"] = self.direction 

107 

108 return result 

109 

110 @classmethod 

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

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

113 return cls( 

114 type=data["type"], 

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

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

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

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

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

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

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

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

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

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

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

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

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

128 ) 

129 

130 

131@dataclass 

132class RouteConfig: 

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

134 

135 Maps verdict strings from evaluators to next state names. 

136 

137 Attributes: 

138 routes: Mapping from verdict string to next state name 

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

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

141 """ 

142 

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

144 default: str | None = None 

145 error: str | None = None 

146 

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

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

149 result = dict(self.routes) 

150 if self.default is not None: 

151 result["_"] = self.default 

152 if self.error is not None: 

153 result["_error"] = self.error 

154 return result 

155 

156 @classmethod 

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

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

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

160 return cls( 

161 routes=routes, 

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

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

164 ) 

165 

166 

167@dataclass 

168class StateConfig: 

169 """Configuration for a single FSM state. 

170 

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

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

173 

174 Attributes: 

175 action: Command to execute (shell or slash command) 

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

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

178 evaluate: Evaluator configuration for result interpretation 

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

180 on_success: Shorthand for success verdict routing 

181 on_failure: Shorthand for failure verdict routing 

182 on_error: Shorthand for error verdict routing 

183 next: Unconditional transition (no evaluation) 

184 terminal: If True, this is an end state 

185 capture: Variable name to store action output 

186 timeout: Action-level timeout in seconds 

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

188 """ 

189 

190 action: str | None = None 

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

192 evaluate: EvaluateConfig | None = None 

193 route: RouteConfig | None = None 

194 on_success: str | None = None 

195 on_failure: str | None = None 

196 on_error: str | None = None 

197 next: str | None = None 

198 terminal: bool = False 

199 capture: str | None = None 

200 timeout: int | None = None 

201 on_maintain: str | None = None 

202 

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

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

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

206 

207 if self.action is not None: 

208 result["action"] = self.action 

209 if self.action_type is not None: 

210 result["action_type"] = self.action_type 

211 if self.evaluate is not None: 

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

213 if self.route is not None: 

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

215 if self.on_success is not None: 

216 result["on_success"] = self.on_success 

217 if self.on_failure is not None: 

218 result["on_failure"] = self.on_failure 

219 if self.on_error is not None: 

220 result["on_error"] = self.on_error 

221 if self.next is not None: 

222 result["next"] = self.next 

223 if self.terminal: 

224 result["terminal"] = self.terminal 

225 if self.capture is not None: 

226 result["capture"] = self.capture 

227 if self.timeout is not None: 

228 result["timeout"] = self.timeout 

229 if self.on_maintain is not None: 

230 result["on_maintain"] = self.on_maintain 

231 

232 return result 

233 

234 @classmethod 

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

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

237 evaluate = None 

238 if "evaluate" in data: 

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

240 

241 route = None 

242 if "route" in data: 

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

244 

245 return cls( 

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

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

248 evaluate=evaluate, 

249 route=route, 

250 on_success=data.get("on_success"), 

251 on_failure=data.get("on_failure"), 

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

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

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

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

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

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

258 ) 

259 

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

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

262 

263 Returns: 

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

265 """ 

266 refs: set[str] = set() 

267 

268 if self.on_success is not None: 

269 refs.add(self.on_success) 

270 if self.on_failure is not None: 

271 refs.add(self.on_failure) 

272 if self.on_error is not None: 

273 refs.add(self.on_error) 

274 if self.next is not None: 

275 refs.add(self.next) 

276 if self.on_maintain is not None: 

277 refs.add(self.on_maintain) 

278 if self.route is not None: 

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

280 if self.route.default is not None: 

281 refs.add(self.route.default) 

282 if self.route.error is not None: 

283 refs.add(self.route.error) 

284 

285 return refs 

286 

287 

288@dataclass 

289class LLMConfig: 

290 """LLM evaluation configuration. 

291 

292 Settings for the llm_structured evaluator. 

293 

294 Attributes: 

295 enabled: If False, disable LLM evaluation entirely 

296 model: Model identifier for LLM calls 

297 max_tokens: Maximum tokens for evaluation response 

298 timeout: Timeout for LLM calls in seconds 

299 """ 

300 

301 enabled: bool = True 

302 model: str = DEFAULT_LLM_MODEL 

303 max_tokens: int = 256 

304 timeout: int = 30 

305 

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

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

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

309 

310 if not self.enabled: 

311 result["enabled"] = self.enabled 

312 if self.model != DEFAULT_LLM_MODEL: 

313 result["model"] = self.model 

314 if self.max_tokens != 256: 

315 result["max_tokens"] = self.max_tokens 

316 if self.timeout != 30: 

317 result["timeout"] = self.timeout 

318 

319 return result if result else {} 

320 

321 @classmethod 

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

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

324 return cls( 

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

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

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

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

329 ) 

330 

331 

332@dataclass 

333class FSMLoop: 

334 """Complete FSM loop definition. 

335 

336 The main dataclass representing a loop configuration. This matches 

337 the universal FSM schema that all paradigms compile to. 

338 

339 Attributes: 

340 name: Unique loop identifier 

341 initial: Starting state name 

342 states: Mapping from state name to StateConfig 

343 paradigm: Source paradigm (for reference, e.g., "goal", "convergence") 

344 context: User-defined shared variables 

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

346 max_iterations: Safety limit for loop iterations 

347 backoff: Seconds between iterations 

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

349 maintain: If True, restart after completion 

350 llm: LLM evaluation configuration 

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

352 """ 

353 

354 name: str 

355 initial: str 

356 states: dict[str, StateConfig] 

357 paradigm: str | None = None 

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

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

360 max_iterations: int = 50 

361 backoff: float | None = None 

362 timeout: int | None = None 

363 maintain: bool = False 

364 llm: LLMConfig = field(default_factory=LLMConfig) 

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

366 

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

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

369 result: dict[str, Any] = { 

370 "name": self.name, 

371 "initial": self.initial, 

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

373 } 

374 

375 if self.paradigm is not None: 

376 result["paradigm"] = self.paradigm 

377 if self.context: 

378 result["context"] = self.context 

379 if self.scope: 

380 result["scope"] = self.scope 

381 if self.max_iterations != 50: 

382 result["max_iterations"] = self.max_iterations 

383 if self.backoff is not None: 

384 result["backoff"] = self.backoff 

385 if self.timeout is not None: 

386 result["timeout"] = self.timeout 

387 if self.maintain: 

388 result["maintain"] = self.maintain 

389 if self.on_handoff != "pause": 

390 result["on_handoff"] = self.on_handoff 

391 

392 llm_dict = self.llm.to_dict() 

393 if llm_dict: 

394 result["llm"] = llm_dict 

395 

396 return result 

397 

398 @classmethod 

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

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

401 states = { 

402 name: StateConfig.from_dict(state_data) 

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

404 } 

405 

406 llm = LLMConfig() 

407 if "llm" in data: 

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

409 

410 return cls( 

411 name=data["name"], 

412 initial=data["initial"], 

413 states=states, 

414 paradigm=data.get("paradigm"), 

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

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

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

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

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

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

421 llm=llm, 

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

423 ) 

424 

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

426 """Get all defined state names. 

427 

428 Returns: 

429 Set of all state names in this FSM. 

430 """ 

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

432 

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

434 """Get all terminal state names. 

435 

436 Returns: 

437 Set of state names where terminal=True. 

438 """ 

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

440 

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

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

443 

444 This includes the initial state and all states referenced 

445 in routing configurations. 

446 

447 Returns: 

448 Set of all referenced state names. 

449 """ 

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

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

452 refs.update(state.get_referenced_states()) 

453 return refs