Coverage for src/romfarmer/cli/spec.py: 0%

120 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-04 16:33 -0700

1"""``romfarmer spec`` — the SPEC seam from the command line. 

2 

3romfarmer spec lower <build> # legacy build → Spec YAML (+ hash), freezes lists/ into artifacts/ 

4romfarmer spec validate <spec.yaml> # loud validation + resolve every platform 

5romfarmer spec hash <spec.yaml> 

6romfarmer spec run <spec.yaml> # RESOLVE→CATALOG→PLAN→EXECUTE→EMIT — the EXECUTE door 

7""" 

8 

9from __future__ import annotations 

10 

11from pathlib import Path 

12 

13import click 

14from rich.console import Console 

15 

16console = Console() 

17 

18 

19@click.group("spec") 

20def spec_group() -> None: 

21 """Author, validate and hash build Specs (the seam above the compiler).""" 

22 

23 

24@spec_group.command("lower") 

25@click.argument("build") 

26@click.option( 

27 "--out", 

28 type=click.Path(path_type=Path), 

29 help="Write YAML here (default: artifacts/specs/<hash>.yaml)", 

30) 

31@click.option("--no-freeze-lists", is_flag=True, help="Do not freeze lists/ into curated artifacts") 

32def spec_lower(build: str, out: Path | None, no_freeze_lists: bool) -> None: 

33 """Lower a legacy config/builds/<BUILD>.yaml into a frozen Spec.""" 

34 from romfarmer.core.paths import get_paths 

35 from romfarmer.driver.spec_io import dump_spec, save_spec 

36 from romfarmer.driver.spec_resolve import spec_from_build 

37 from romfarmer.ir.spec import SpecError 

38 

39 try: 

40 spec = spec_from_build(build, freeze_lists=not no_freeze_lists) 

41 except SpecError as exc: 

42 console.print(f"[red]{exc}[/red]") 

43 raise SystemExit(1) from exc 

44 if out is not None: 

45 out.write_text(dump_spec(spec)) 

46 path = out 

47 else: 

48 path = save_spec(spec, Path(get_paths().workspace_root) / "artifacts" / "specs") 

49 console.print(f"[green]spec_hash[/green] {spec.spec_hash()} → {path}") 

50 

51 

52@spec_group.command("validate") 

53@click.argument("spec_file", type=click.Path(exists=True, path_type=Path)) 

54def spec_validate(spec_file: Path) -> None: 

55 """Validate SPEC_FILE and RESOLVE every platform (no source scan).""" 

56 from romfarmer.core.paths import get_paths 

57 from romfarmer.driver.spec_io import load_spec 

58 from romfarmer.driver.spec_resolve import resolve_build 

59 from romfarmer.ir.spec import SpecError 

60 

61 ws = Path(get_paths().workspace_root) 

62 try: 

63 spec = load_spec(spec_file) 

64 builds = resolve_build(spec, ws / "config", workspace_root=ws) 

65 except SpecError as exc: 

66 console.print(f"[red]{exc}[/red]") 

67 raise SystemExit(1) from exc 

68 console.print(f"[green]ok[/green] spec_hash={spec.spec_hash()} platforms={len(builds)}") 

69 for rb in builds: 

70 m = rb.manifest 

71 console.print( 

72 f" {rb.platform:14s} chain={'→'.join(rb.chain):12s} dat={'yes' if rb.dat_file else 'no ':3s} " 

73 f"1g1r={'dat' if not m.one_g_one_r else 'pass'} rating_min={m.rating_min} budget={m.budget_bytes}" 

74 ) 

75 

76 

77@spec_group.command("run") 

78@click.argument("spec_file", type=click.Path(exists=True, path_type=Path)) 

79@click.option( 

80 "--validate-only", is_flag=True, help="Validate + RESOLVE only (no source scan, no files)." 

81) 

82@click.option( 

83 "--dry-run", "dry_run", is_flag=True, help="RESOLVE→CATALOG→PLAN and stop. No files written." 

84) 

85@click.option("--output-dir", type=click.Path(path_type=Path), help="Override the staging directory.") 

86@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") 

87def spec_run( 

88 spec_file: Path, 

89 validate_only: bool, 

90 dry_run: bool, 

91 output_dir: Path | None, 

92 yes: bool, 

93) -> None: 

94 """Run SPEC_FILE: RESOLVE -> CATALOG -> PLAN -> EXECUTE -> EMIT, to a staging directory. 

95 

96 This is the deterministic door across the SPEC boundary: everything it 

97 does follows from the frozen Spec alone, with no model call in the path. 

98 It only ever writes under the staging directory (default 

99 ``output/spec-<hash12>``) and stamps a ``spec_manifest.json`` there with 

100 the ``spec_hash`` this output was built from. It never touches a 

101 physical device — that is the separate, explicitly gated ``--deploy`` 

102 step on the legacy build path. 

103 """ 

104 from romfarmer.core.paths import get_paths 

105 from romfarmer.driver.spec_io import load_spec 

106 from romfarmer.driver.spec_resolve import resolve_build 

107 from romfarmer.ir.spec import SpecError 

108 from romfarmer.new_orchestrator import run_spec 

109 

110 ws = Path(get_paths().workspace_root) 

111 try: 

112 spec = load_spec(spec_file) 

113 builds = resolve_build(spec, ws / "config", workspace_root=ws, output_base=output_dir) 

114 except SpecError as exc: 

115 console.print(f"[red]{exc}[/red]") 

116 raise SystemExit(1) from exc 

117 

118 out_base = output_dir or ws / "output" / f"spec-{spec.spec_hash()[:12]}" 

119 console.print(f"[cyan]spec_hash[/cyan] {spec.spec_hash()}") 

120 console.print(f"[cyan]staging[/cyan] {out_base}") 

121 console.print(f"[cyan]platforms[/cyan] {', '.join(rb.platform for rb in builds)}") 

122 

123 if validate_only: 

124 console.print("[green]ok[/green] — RESOLVE passed for every platform") 

125 return 

126 

127 if not dry_run and not yes: 

128 if not click.confirm( 

129 f"\nRun EXECUTE and write to {out_base}?", default=True 

130 ): 

131 console.print("[yellow]cancelled[/yellow]") 

132 return 

133 

134 report = run_spec(spec, ws / "config", workspace_root=ws, output_base=output_dir, dry_run=dry_run) 

135 

136 for p in report.platforms: 

137 if p.planned_only: 

138 console.print(f" [yellow]{p.platform:14s} [dry-run] {p.terminal_count} units planned[/yellow]") 

139 continue 

140 console.print( 

141 f" {p.platform:14s} chain={'→'.join(p.chain):10s} " 

142 f"{p.terminal_count} units {p.actual_bytes / 1e9:.2f} GB" 

143 + (f" [red]{len(p.failed_units)} failed[/red]" if p.failed_units else "") 

144 + (f" [yellow]{p.budget_stopped} budget-stopped[/yellow]" if p.budget_stopped else "") 

145 ) 

146 

147 if dry_run: 

148 console.print("[yellow]--dry-run complete — no files written[/yellow]") 

149 return 

150 

151 manifest_path = report.write_provenance(spec) 

152 console.print( 

153 f"[green]done[/green] {report.total_actual_bytes / 1e9:.2f} GB written to {report.output_base}" 

154 ) 

155 console.print(f"[green]provenance[/green] {manifest_path}") 

156 

157 

158@spec_group.command("hash") 

159@click.argument("spec_file", type=click.Path(exists=True, path_type=Path)) 

160def spec_hash(spec_file: Path) -> None: 

161 """Print the spec_hash of SPEC_FILE.""" 

162 from romfarmer.driver.spec_io import load_spec 

163 

164 click.echo(load_spec(spec_file).spec_hash()) 

165 

166 

167@spec_group.command("summary") 

168@click.argument("spec_file", type=click.Path(exists=True, path_type=Path)) 

169@click.option("--json", "as_json", is_flag=True, help="Emit the compact JSON the agent reads") 

170def spec_summary(spec_file: Path, as_json: bool) -> None: 

171 """INVENTORY (once) + dry-run PLAN → PlanSummary for SPEC_FILE. Moves zero bytes.""" 

172 import json as _json 

173 

174 from romfarmer.core.paths import get_paths 

175 from romfarmer.driver.session import PlanSession 

176 from romfarmer.driver.spec_io import load_spec 

177 from romfarmer.ir.spec import SpecError 

178 

179 ws = Path(get_paths().workspace_root) 

180 try: 

181 spec = load_spec(spec_file) 

182 session = PlanSession(ws, ws / "config") 

183 summary = session.dry_run(spec) 

184 except SpecError as exc: 

185 console.print(f"[red]{exc}[/red]") 

186 raise SystemExit(1) from exc 

187 if as_json: 

188 click.echo(summary.to_json()) 

189 return 

190 d = summary.to_dict() 

191 console.print( 

192 f"[cyan]spec[/cyan] {d['spec_hash'][:12]} total p50={d['bytes_total_p50'] / 1e9:.1f} GB " 

193 f"p90={(d['bytes_total_p90'] or 0) / 1e9:.1f} GB headroom p50=" 

194 f"{(d['headroom_p50'] or 0) / 1e9:.1f} GB trimmed={d['budget_trimmed_units']}" 

195 ) 

196 for w in d["warnings"]: 

197 console.print(f" [yellow]! {w}[/yellow]") 

198 for p in d["platforms"]: 

199 console.print( 

200 f" {p['platform']:12s} {'→'.join(p['chain']):10s} tier={p['tier'] or '?'} " 

201 f"{p['units_out']:5d}/{p['units_in']:<5d} rated={p['rated_fraction']:.0%} " 

202 f"p50={p['bytes_est_p50'] / 1e9:6.2f}GB p90={(p['bytes_est_p90'] or 0) / 1e9:6.2f}GB " 

203 f"q50={p['rating_quantiles'].get('p50', 0):.2f} {p['prediction'][:40]}" 

204 ) 

205 for w in p.get("warnings", []): 

206 console.print(f" [yellow]! {w}[/yellow]") 

207 click.echo(f"\n({len(_json.dumps(d))} bytes of JSON)")