Coverage for little_loops / cli / loop / config_cmds.py: 96%

80 statements  

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

1"""ll-loop config subcommands: compile, validate, install.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6from pathlib import Path 

7from typing import Any 

8 

9from little_loops.cli.loop._helpers import get_builtin_loops_dir, resolve_loop_path 

10from little_loops.logger import Logger 

11 

12 

13def cmd_compile( 

14 args: argparse.Namespace, 

15 logger: Logger, 

16) -> int: 

17 """Compile paradigm YAML to FSM.""" 

18 import yaml 

19 

20 from little_loops.fsm.compilers import compile_paradigm 

21 

22 input_path = Path(args.input) 

23 if not input_path.exists(): 

24 logger.error(f"Input file not found: {input_path}") 

25 return 1 

26 

27 try: 

28 with open(input_path) as f: 

29 spec = yaml.safe_load(f) 

30 fsm = compile_paradigm(spec) 

31 except ValueError as e: 

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

33 return 1 

34 except yaml.YAMLError as e: 

35 logger.error(f"YAML parse error: {e}") 

36 return 1 

37 

38 output_path = ( 

39 Path(args.output) if args.output else Path(str(input_path).replace(".yaml", ".fsm.yaml")) 

40 ) 

41 

42 # Convert FSMLoop to dict for YAML output 

43 fsm_dict: dict[str, Any] = { 

44 "name": fsm.name, 

45 "paradigm": fsm.paradigm, 

46 "initial": fsm.initial, 

47 "states": {name: state.to_dict() for name, state in fsm.states.items()}, 

48 "max_iterations": fsm.max_iterations, 

49 } 

50 if fsm.context: 

51 fsm_dict["context"] = fsm.context 

52 if fsm.maintain: 

53 fsm_dict["maintain"] = fsm.maintain 

54 if fsm.backoff: 

55 fsm_dict["backoff"] = fsm.backoff 

56 if fsm.timeout: 

57 fsm_dict["timeout"] = fsm.timeout 

58 

59 with open(output_path, "w") as f: 

60 yaml.dump(fsm_dict, f, default_flow_style=False, sort_keys=False) 

61 

62 logger.success(f"Compiled to: {output_path}") 

63 return 0 

64 

65 

66def cmd_validate( 

67 loop_name: str, 

68 loops_dir: Path, 

69 logger: Logger, 

70) -> int: 

71 """Validate a loop definition.""" 

72 import yaml 

73 

74 from little_loops.fsm.compilers import compile_paradigm 

75 from little_loops.fsm.validation import load_and_validate 

76 

77 try: 

78 path = resolve_loop_path(loop_name, loops_dir) 

79 

80 # Load the file to check format 

81 with open(path) as f: 

82 spec = yaml.safe_load(f) 

83 

84 # Auto-compile if it's a paradigm file (has 'paradigm' but no 'initial') 

85 if "paradigm" in spec and "initial" not in spec: 

86 logger.info(f"Compiling paradigm file for validation: {path}") 

87 fsm = compile_paradigm(spec) 

88 else: 

89 fsm = load_and_validate(path) 

90 

91 logger.success(f"{loop_name} is valid") 

92 print(f" States: {', '.join(fsm.states.keys())}") 

93 print(f" Initial: {fsm.initial}") 

94 print(f" Max iterations: {fsm.max_iterations}") 

95 return 0 

96 except FileNotFoundError as e: 

97 logger.error(str(e)) 

98 return 1 

99 except ValueError as e: 

100 logger.error(f"{loop_name} is invalid: {e}") 

101 return 1 

102 

103 

104def cmd_install( 

105 loop_name: str, 

106 loops_dir: Path, 

107 logger: Logger, 

108) -> int: 

109 """Copy a built-in loop to .loops/ for customization.""" 

110 import shutil 

111 

112 builtin_dir = get_builtin_loops_dir() 

113 source = builtin_dir / f"{loop_name}.yaml" 

114 

115 if not source.exists(): 

116 available = [f.stem for f in builtin_dir.glob("*.yaml")] if builtin_dir.exists() else [] 

117 logger.error(f"No built-in loop named '{loop_name}'") 

118 if available: 

119 print(f"Available built-in loops: {', '.join(sorted(available))}") 

120 return 1 

121 

122 loops_dir.mkdir(exist_ok=True) 

123 dest = loops_dir / f"{loop_name}.yaml" 

124 

125 if dest.exists(): 

126 logger.error(f"Loop already exists: {dest}") 

127 print("Remove it first or edit it directly.") 

128 return 1 

129 

130 shutil.copy2(source, dest) 

131 print(f"Installed {loop_name} to {dest}") 

132 print("You can now customize it by editing the file.") 

133 return 0