Coverage for src/romfarmer/driver/curated.py: 91%

77 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""Curated-list artifacts — hash-addressed, frozen, loaded by ref only. 

2 

3``artifacts/curated/<name>/<sha256>.yaml``:: 

4 

5 name: snes-essentials 

6 generated_by: "agent:<model-id>" # provenance 

7 generated_at: "2026-09-03T…" 

8 basis: {platform: snes, dat: "…", inventory_digest: "sha256:…"} 

9 entries: 

10 - {canonical_name: "Chrono Trigger (USA)", action: include, reason: "…"} 

11 - {canonical_name: "Bad Dump (USA)", action: exclude, reason: "…"} 

12 

13The ref is ``curated/<name>@sha256:<hex>`` where ``<hex>`` is the SHA-256 of 

14the file bytes. A ref is resolved by hash: a name-only reference is a hard 

15error, and a file whose bytes no longer hash to the ref is rejected. This is 

16the mechanism that lets stochastic taste ("best") into a deterministic 

17system: the list is authored above the seam, frozen, and its hash rides in 

18``spec_hash`` — never in ``Action.params``. 

19 

20``freeze_lists`` converts the legacy ``lists/{platform}-delete`` / 

21``lists/{platform}+*`` files into one artifact so existing builds lower to a 

22``Spec`` without losing their curation. 

23""" 

24 

25from __future__ import annotations 

26 

27import hashlib 

28import re 

29from dataclasses import dataclass 

30from pathlib import Path 

31from typing import Any 

32 

33import yaml 

34 

35from romfarmer.ir.spec import SpecError 

36 

37_REF = re.compile(r"^curated/(?P<name>[A-Za-z0-9._-]+)@sha256:(?P<hex>[0-9a-f]{64})$") 

38 

39 

40@dataclass(frozen=True) 

41class CuratedArtifact: 

42 name: str 

43 sha256: str 

44 include: frozenset[str] 

45 exclude: frozenset[str] 

46 basis: dict[str, Any] 

47 generated_by: str = "" 

48 

49 @property 

50 def ref(self) -> str: 

51 return f"curated/{self.name}@sha256:{self.sha256}" 

52 

53 

54def parse_ref(ref: str) -> tuple[str, str]: 

55 m = _REF.match(ref) 

56 if not m: 

57 raise SpecError(f"curated ref must be 'curated/<name>@sha256:<64 hex>', got {ref!r}") 

58 return m.group("name"), m.group("hex") 

59 

60 

61def artifact_path(ref: str, artifacts_dir: Path) -> Path: 

62 name, hex_ = parse_ref(ref) 

63 return artifacts_dir / "curated" / name / f"{hex_}.yaml" 

64 

65 

66def load_curated(ref: str, artifacts_dir: Path) -> CuratedArtifact: 

67 """Load an artifact by ref; verify its bytes hash to the ref.""" 

68 name, hex_ = parse_ref(ref) 

69 path = artifact_path(ref, artifacts_dir) 

70 if not path.exists(): 

71 raise SpecError(f"curated artifact not found: {path} (ref {ref})") 

72 data = path.read_bytes() 

73 actual = hashlib.sha256(data).hexdigest() 

74 if actual != hex_: 

75 raise SpecError( 

76 f"curated artifact {path} hashes to {actual[:12]}…, ref says {hex_[:12]}… — refusing" 

77 ) 

78 return _parse(name, hex_, data) 

79 

80 

81def _parse(name: str, hex_: str, data: bytes) -> CuratedArtifact: 

82 try: 

83 raw = yaml.safe_load(data) 

84 except yaml.YAMLError as exc: 

85 raise SpecError(f"curated artifact {name}@{hex_[:12]} is not valid YAML: {exc}") from exc 

86 if not isinstance(raw, dict) or not isinstance(raw.get("entries"), list): 

87 raise SpecError(f"curated artifact {name}@{hex_[:12]}: expected a mapping with 'entries'") 

88 inc: set[str] = set() 

89 excl: set[str] = set() 

90 for i, e in enumerate(raw["entries"]): 

91 if not isinstance(e, dict) or not e.get("canonical_name"): 

92 raise SpecError(f"curated artifact {name}: entries[{i}] needs canonical_name") 

93 action = str(e.get("action", "include")) 

94 if action == "include": 

95 inc.add(str(e["canonical_name"])) 

96 elif action == "exclude": 

97 excl.add(str(e["canonical_name"])) 

98 else: 

99 raise SpecError(f"curated artifact {name}: entries[{i}].action must be include|exclude") 

100 return CuratedArtifact( 

101 name=name, 

102 sha256=hex_, 

103 include=frozenset(inc), 

104 exclude=frozenset(excl), 

105 basis=dict(raw.get("basis") or {}), 

106 generated_by=str(raw.get("generated_by", "")), 

107 ) 

108 

109 

110def write_curated( 

111 name: str, 

112 entries: list[dict[str, str]], 

113 artifacts_dir: Path, 

114 *, 

115 generated_by: str, 

116 basis: dict[str, Any] | None = None, 

117 generated_at: str = "", 

118) -> CuratedArtifact: 

119 """Freeze ``entries`` into a new artifact; returns it (with its ref). 

120 

121 This is the ONE way a model's output enters the system: it becomes bytes, 

122 the bytes get a hash, the hash goes into the spec. Canonical YAML 

123 (sorted entries) so the same list always produces the same ref. 

124 """ 

125 if not re.match(r"^[A-Za-z0-9._-]+$", name): 

126 raise SpecError(f"curated artifact name must be [A-Za-z0-9._-]+, got {name!r}") 

127 norm = sorted( 

128 ( 

129 { 

130 "canonical_name": str(e["canonical_name"]), 

131 "action": str(e.get("action", "include")), 

132 "reason": str(e.get("reason", "")), 

133 } 

134 for e in entries 

135 ), 

136 key=lambda e: (e["action"], e["canonical_name"]), 

137 ) 

138 doc = { 

139 "name": name, 

140 "generated_by": generated_by, 

141 "generated_at": generated_at, 

142 "basis": dict(basis or {}), 

143 "entries": norm, 

144 } 

145 data = yaml.safe_dump(doc, sort_keys=False, allow_unicode=True).encode("utf-8") 

146 hex_ = hashlib.sha256(data).hexdigest() 

147 path = artifacts_dir / "curated" / name / f"{hex_}.yaml" 

148 path.parent.mkdir(parents=True, exist_ok=True) 

149 if not path.exists(): 

150 path.write_bytes(data) 

151 return _parse(name, hex_, data) 

152 

153 

154def freeze_lists(platform: str, lists_dir: Path, artifacts_dir: Path) -> CuratedArtifact | None: 

155 """Convert legacy ``lists/{platform}-delete`` + ``lists/{platform}+*`` into one artifact. 

156 

157 Returns ``None`` when the platform has no list files (nothing to freeze). 

158 """ 

159 from romfarmer.driver.resolve import load_curated_lists 

160 

161 include, exclude = load_curated_lists(platform, lists_dir) 

162 if not include and not exclude: 

163 return None 

164 entries = [ 

165 {"canonical_name": n, "action": "include", "reason": f"lists/{platform}+*"} for n in include 

166 ] 

167 entries += [ 

168 {"canonical_name": n, "action": "exclude", "reason": f"lists/{platform}-delete"} 

169 for n in exclude 

170 ] 

171 return write_curated( 

172 f"{platform}-lists", 

173 entries, 

174 artifacts_dir, 

175 generated_by="freeze_lists", 

176 basis={"platform": platform, "source": f"lists/{platform}-delete, lists/{platform}+*"}, 

177 )