Coverage for src/romfarmer/driver/spec_io.py: 34%
41 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""YAML I/O for ``romfarmer.ir.spec.Spec`` — loud on every error.
3Specs are persisted under ``artifacts/specs/<spec_hash>.yaml`` so an operator
4can diff what an agent changed between iterations.
5"""
7from __future__ import annotations
9from pathlib import Path
10from typing import Any
12import yaml
14from romfarmer.ir.spec import Spec, SpecError
17def load_spec(path: Path) -> Spec:
18 """Parse and validate a spec YAML. Raises ``SpecError`` on any problem."""
19 if not path.exists():
20 raise SpecError(f"spec not found: {path}")
21 try:
22 raw = yaml.safe_load(path.read_text())
23 except yaml.YAMLError as exc:
24 raise SpecError(f"{path} is not valid YAML: {exc}") from exc
25 if not isinstance(raw, dict):
26 raise SpecError(f"{path}: top level must be a mapping")
27 return Spec.from_dict(raw)
30def dump_spec(spec: Spec) -> str:
31 """YAML text of the full spec (intent first, then the hashed fields)."""
32 d: dict[str, Any] = spec.to_dict()
33 ordered = {
34 "spec_version": d["spec_version"],
35 "intent": d["intent"],
36 "target": d["target"],
37 "platforms": d["platforms"],
38 }
39 header = f"# spec_hash: {spec.spec_hash()}\n# (hash covers target + platforms; intent is provenance only)\n"
40 return header + yaml.safe_dump(
41 ordered, sort_keys=False, allow_unicode=True, default_flow_style=False
42 )
45def save_spec(spec: Spec, specs_dir: Path) -> Path:
46 """Write ``<specs_dir>/<spec_hash>.yaml`` (idempotent) and index the intent.
48 ``<specs_dir>/index.jsonl`` records ``(intent_text, inventory_digest,
49 capability_digest, authored_by, authored_at) → spec_hash`` — P3's
50 durable intent: an intent can be re-run months later against a grown
51 collection and the resulting spec diffed against what the agent decided
52 last time. One line per distinct (spec_hash, inventory_digest).
53 """
54 import json
56 specs_dir.mkdir(parents=True, exist_ok=True)
57 out = specs_dir / f"{spec.spec_hash()}.yaml"
58 if not out.exists():
59 out.write_text(dump_spec(spec))
60 index = specs_dir / "index.jsonl"
61 row = {
62 "spec_hash": spec.spec_hash(),
63 "intent_text": spec.intent.text,
64 "inventory_digest": spec.intent.inventory_digest,
65 "capability_digest": spec.intent.capability_digest,
66 "authored_by": spec.intent.authored_by,
67 "authored_at": spec.intent.authored_at,
68 }
69 existing = index.read_text().splitlines() if index.exists() else []
70 key = (row["spec_hash"], row["inventory_digest"])
71 if not any(
72 (json.loads(ln).get("spec_hash"), json.loads(ln).get("inventory_digest")) == key
73 for ln in existing
74 if ln.strip()
75 ):
76 with index.open("a") as fh:
77 fh.write(json.dumps(row, ensure_ascii=False) + "\n")
78 return out
81def intent_history(specs_dir: Path, intent_text: str | None = None) -> list[dict[str, Any]]:
82 """Rows from ``index.jsonl`` (optionally filtered to one intent text), oldest first."""
83 import json
85 index = specs_dir / "index.jsonl"
86 if not index.exists():
87 return []
88 rows = [json.loads(ln) for ln in index.read_text().splitlines() if ln.strip()]
89 return [r for r in rows if intent_text is None or r.get("intent_text") == intent_text]