Skip to main content

harness_lock_core/
optimize.rs

1//! Tune optimizers (`specs/tune-optimizers.md`): the harness bundle an optimizer edits, the
2//! evaluation session it calls back into (`hlock tune eval`), and the checks the core makes
3//! before an edit reaches the tune lock.
4//!
5//! An optimizer ([`Optimizer`], `specs/optimizers.md`) is what searches; the backend is
6//! where it and its trials run. It gets a **bundle**: the base lock's
7//! instruction files and skills as files, and `bundle.json`, which says which it may edit.
8//! It evaluates candidates through a **session**, which runs and grades trials of a
9//! candidate on the train or dev split, inside a budget, and never on the test split. When
10//! it returns, the core checks the candidate for text copied from the pack ([`leaks`]) and
11//! measures it against the base lock on the held-out tasks ([`sign_test`]) before any edit
12//! is written ([`apply_to_lock`]).
13
14use std::collections::{BTreeMap, BTreeSet};
15use std::path::{Path, PathBuf};
16
17use serde::{Deserialize, Serialize};
18use serde_json::{json, Value};
19
20use crate::error::{Error, Result};
21use crate::hash::sha256_bytes;
22use crate::lockfile::{Instructions, Lockfile};
23
24/// The component kinds an optimizer may edit.
25pub const KINDS: &[&str] = &["instructions", "skill", "subagent", "script", "middleware"];
26
27/// The bundle directory each kind of file component lives in, and its lock kind.
28const FILE_DIRS: &[(&str, &str)] = &[("subagents", "subagent"), ("scripts", "script"), ("middleware", "middleware")];
29
30/// The lock's name for a file component: a script keeps its file name; a subagent or
31/// middleware file is named by its stem.
32fn file_name_of(kind: &str, file: &str) -> String {
33    if kind == "script" { file.to_string() } else { file.split('.').next().unwrap_or(file).to_string() }
34}
35
36/// Where a new file component of `kind` goes in `profile`'s harness, if it has a place.
37pub fn file_dest(profile: Option<&crate::profiles::HarnessProfile>, kind: &str, file: &str) -> Option<String> {
38    match kind {
39        "script" => Some(format!("{}/{file}", crate::components::SCRIPTS_DIR)),
40        "subagent" => profile?.subagents.as_ref().and_then(|s| s.write.clone().or_else(|| s.dirs.first().cloned())).map(|d| format!("{d}/{file}")),
41        "middleware" => {
42            let m = profile?.middleware.as_ref()?;
43            m.write.clone().or_else(|| m.dirs.first().cloned()).map(|d| format!("{d}/{file}")).or_else(|| m.files.iter().find(|f| f.ends_with(&format!("/{file}")) || f.as_str() == file).cloned())
44        }
45        _ => None,
46    }
47}
48/// The built-in optimizers. Both run in hlock's Python worker.
49pub const BUILTIN_OPTIMIZERS: &[&str] = &["hlock", "harness2"];
50
51/// How an optimizer runs, in whichever process hosts the search.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum OptimizerRunner {
54    /// A Python optimizer: built in or found by its `hlock.optimizers` entry point
55    /// (`object: None`), or a `module:attr` object.
56    Python { object: Option<String> },
57    /// An executable that speaks the backend contract for `harness.optimize`.
58    Command(Vec<String>),
59}
60
61/// The optimizer `tune` searches with (`[tune] optimizer`), resolved from its name. Where
62/// it runs is the backend's business ([`crate::worker::Backend`]).
63#[derive(Debug, Clone, PartialEq)]
64pub struct Optimizer {
65    pub name: String,
66    pub runner: OptimizerRunner,
67    /// `[optimizers.<name>] options`, sent with the request.
68    pub options: Value,
69}
70
71impl Optimizer {
72    /// The optimizer `name` names: a built-in, an `[optimizers.<name>]` table, an
73    /// `hlock-optimizer-<name>` executable on `PATH`, or else a Python optimizer the
74    /// worker looks up by entry point (and reports missing when it runs).
75    pub fn resolve(manifest: &crate::manifest::Manifest, name: &str) -> Result<Optimizer> {
76        let name = name.trim();
77        if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
78            return Err(Error::Manifest(format!("optimizer {name:?} isn't a valid name: use letters, digits, '-' and '_'")));
79        }
80        let def = manifest.optimizers.get(name);
81        if def.is_none() && manifest.backends.contains_key(name) && !BUILTIN_OPTIMIZERS.contains(&name) {
82            return Err(Error::Manifest(format!("[tune] optimizer = {name:?} names a backend: optimizers are declared under [optimizers.{name}], backends only say where the work runs")));
83        }
84        let bad = |why: String| Error::Manifest(format!("[optimizers.{name}] {why}"));
85        let (command, object, options) = crate::worker::parse_def(def, &bad)?;
86        let runner = match (command, object) {
87            (Some(_), _) | (_, Some(_)) if BUILTIN_OPTIMIZERS.contains(&name) => return Err(bad(format!("can only set options: {name} is built in"))),
88            (Some(_), Some(_)) => return Err(bad("sets both command and python: keep one".into())),
89            (Some(c), None) => OptimizerRunner::Command(c),
90            (None, Some(o)) => OptimizerRunner::Python { object: Some(o) },
91            (None, None) if BUILTIN_OPTIMIZERS.contains(&name) => OptimizerRunner::Python { object: None },
92            (None, None) => match crate::profiles::Ctx::from_process().which(&format!("hlock-optimizer-{name}")) {
93                Some(p) => OptimizerRunner::Command(vec![p.to_string_lossy().into_owned()]),
94                None => OptimizerRunner::Python { object: None },
95            },
96        };
97        Ok(Optimizer { name: name.to_string(), runner, options })
98    }
99
100    /// How the optimizer was found, for `hlock optimizer status`.
101    pub fn source(&self) -> String {
102        match &self.runner {
103            OptimizerRunner::Python { object: None } if BUILTIN_OPTIMIZERS.contains(&self.name.as_str()) => "built in".into(),
104            OptimizerRunner::Python { object: None } => format!("looked up as '{}' in the hlock.optimizers entry points", self.name),
105            OptimizerRunner::Python { object: Some(o) } => format!("Python object {o}"),
106            OptimizerRunner::Command(argv) if argv.len() == 1 && Path::new(&argv[0]).file_name().is_some_and(|f| f.to_string_lossy() == format!("hlock-optimizer-{}", self.name)) => {
107                format!("hlock-optimizer-{} on PATH", self.name)
108            }
109            OptimizerRunner::Command(argv) => format!("command {}", argv.join(" ")),
110        }
111    }
112
113    /// The request's `optimizer` field (contract 5).
114    pub fn to_value(&self) -> Value {
115        let (object, command) = match &self.runner {
116            OptimizerRunner::Python { object } => (json!(object), Value::Null),
117            OptimizerRunner::Command(argv) => (Value::Null, json!(argv)),
118        };
119        json!({"name": self.name, "options": self.options, "object": object, "command": command})
120    }
121}
122
123const MAX_COMPONENT_BYTES: usize = 15 * 1024;
124const MAX_CHANGED_LINES: usize = 120;
125
126fn err(m: impl Into<String>) -> Error {
127    Error::Tuning(m.into())
128}
129
130/// One component of a bundle: an instruction file or a skill.
131#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
132pub struct Component {
133    /// Its path in the bundle: `instructions/CLAUDE.md`, `skills/review`.
134    pub id: String,
135    pub kind: String,
136    /// Its name in the lock.
137    pub name: String,
138    pub digest: String,
139    pub editable: bool,
140    /// Why it can't be edited, when it can't.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub why: Option<String>,
143    /// An instruction file's role (`guardrails`, `memory`, `tool-guidance`), and the roles it
144    /// holds as sections.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub role: Option<String>,
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub sections: Vec<String>,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
152pub struct Limits {
153    pub max_component_bytes: usize,
154    pub max_changed_lines: usize,
155}
156
157/// `bundle.json`: what's in a bundle and what an optimizer may do with it.
158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
159pub struct BundleSpec {
160    pub harness: String,
161    pub components: Vec<Component>,
162    /// Kinds of component an optimizer may add.
163    pub may_add: Vec<String>,
164    pub limits: Limits,
165}
166
167impl BundleSpec {
168    pub fn load(dir: &Path) -> Result<BundleSpec> {
169        let text = std::fs::read_to_string(dir.join("bundle.json")).map_err(|e| err(format!("can't read {}/bundle.json: {e}", dir.display())))?;
170        serde_json::from_str(&text).map_err(|e| err(format!("{}/bundle.json: {e}", dir.display())))
171    }
172}
173
174fn plain_path(p: &str) -> bool {
175    crate::fsutil::safe_rel(p) && !p.contains('{') && !p.starts_with('~')
176}
177
178/// Where a lock entry's content is, next to the lock: its vendored copy, else the project's
179/// file or directory at the path it records.
180fn located(lock_dir: &Path, vendored: Option<&str>, project: &[Option<&str>]) -> Option<PathBuf> {
181    vendored
182        .filter(|v| crate::fsutil::safe_rel(v))
183        .map(|v| lock_dir.join(v))
184        .filter(|p| p.exists())
185        .or_else(|| project.iter().flatten().filter(|p| plain_path(p)).map(|p| lock_dir.join(p)).find(|p| p.exists()))
186}
187
188/// Write the base lock's instruction files and skills into `dest` as a bundle, with the
189/// kinds in `edit` editable. `default_instructions` (the harness's own instruction file) is
190/// always there, empty when the lock has none, so an optimizer can write a system prompt.
191pub fn write_seed(base: Option<&Lockfile>, profile: Option<&crate::profiles::HarnessProfile>, lock_dir: &Path, harness: &str, default_instructions: &str, edit: &[String], dest: &Path) -> Result<BundleSpec> {
192    let _ = std::fs::remove_dir_all(dest);
193    std::fs::create_dir_all(dest)?;
194    let can = |kind: &str| edit.iter().any(|e| e == kind);
195    let mut components = Vec::new();
196    let mut instructions: Vec<&Instructions> = base.map(|l| l.instructions.iter().collect()).unwrap_or_default();
197    instructions.retain(|i| plain_path(&i.name));
198    let fallback = Instructions { name: default_instructions.to_string(), ..Default::default() };
199    if !instructions.iter().any(|i| i.name == default_instructions) {
200        instructions.push(&fallback);
201    }
202    for i in instructions {
203        let from = located(lock_dir, i.vendored.as_deref(), &[Some(&i.name)]);
204        let text = from.as_deref().map(|p| crate::fsutil::read_regular(p, 1 << 20)).transpose()?.unwrap_or_default();
205        let id = format!("instructions/{}", i.name);
206        let out = dest.join(&id);
207        std::fs::create_dir_all(out.parent().unwrap_or(dest))?;
208        std::fs::write(&out, &text)?;
209        let why = if !can("instructions") {
210            Some("not in [tune] edit".to_string())
211        } else if i.dep.declared {
212            Some("a declared dependency: change it at its source".to_string())
213        } else {
214            None
215        };
216        components.push(Component { id, kind: "instructions".into(), name: i.name.clone(), digest: sha256_bytes(&text), editable: why.is_none(), why, role: i.role.clone(), sections: i.sections.clone() });
217    }
218    for s in base.map(|l| l.skill.as_slice()).unwrap_or_default().iter().filter(|s| s.enabled) {
219        let source = s.source.as_deref().and_then(|p| p.strip_prefix("./"));
220        let Some(dir) = located(lock_dir, s.vendored.as_deref(), &[s.path.as_deref(), source]).filter(|d| d.join("SKILL.md").is_file()) else { continue };
221        if !crate::fsutil::plain_name(&s.name) {
222            continue;
223        }
224        let id = format!("skills/{}", s.name);
225        crate::fsutil::copy_tree(&dir, &dest.join(&id))?;
226        let why = if !can("skill") {
227            Some("not in [tune] edit".to_string())
228        } else if s.dep.declared {
229            Some("a declared dependency: change it at its source".to_string())
230        } else {
231            None
232        };
233        components.push(Component { id: id.clone(), kind: "skill".into(), name: s.name.clone(), digest: crate::capture::tree_digest(&dest.join(&id)), editable: why.is_none(), why, role: None, sections: Vec::new() });
234    }
235    // subagents, scripts and middleware: one file each, under the kind's directory
236    for (dir, kind) in FILE_DIRS {
237        let items: &[crate::lockfile::FileComponent] = match (*kind, base) {
238            ("subagent", Some(l)) => &l.subagent,
239            ("script", Some(l)) => &l.script,
240            ("middleware", Some(l)) => &l.middleware,
241            _ => &[],
242        };
243        for c in items {
244            let Some(from) = located(lock_dir, c.vendored.as_deref(), &[Some(&c.path)]).filter(|p| p.is_file()) else { continue };
245            let file = from.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
246            if !crate::fsutil::plain_name(&file) {
247                continue;
248            }
249            let id = format!("{dir}/{file}");
250            let bytes = crate::fsutil::read_regular(&from, 1 << 20)?;
251            std::fs::create_dir_all(dest.join(dir))?;
252            std::fs::write(dest.join(&id), &bytes)?;
253            let why = (!can(kind)).then(|| "not in [tune] edit".to_string());
254            components.push(Component { id, kind: kind.to_string(), name: c.name.clone(), digest: sha256_bytes(&bytes), editable: why.is_none(), why, role: None, sections: Vec::new() });
255        }
256    }
257    // a kind can be added only where the harness has a place for it
258    let placeable = |k: &str| !matches!(k, "subagent" | "middleware") || file_dest(profile, k, "x").is_some();
259    let spec = BundleSpec {
260        harness: harness.to_string(),
261        components,
262        may_add: edit.iter().filter(|k| KINDS.contains(&k.as_str()) && placeable(k)).cloned().collect(),
263        limits: Limits { max_component_bytes: MAX_COMPONENT_BYTES, max_changed_lines: MAX_CHANGED_LINES },
264    };
265    std::fs::write(dest.join("bundle.json"), serde_json::to_string_pretty(&spec)? + "\n")?;
266    Ok(spec)
267}
268
269/// A candidate's identity: the digest of everything in it but `bundle.json`.
270pub fn candidate_digest(dir: &Path) -> String {
271    let part = |d: &str| crate::capture::tree_digest(&dir.join(d));
272    let parts: Vec<String> = ["instructions", "skills", "subagents", "scripts", "middleware"].iter().map(|d| part(d)).collect();
273    sha256_bytes(parts.join("\n").as_bytes())
274}
275
276/// The components in a bundle directory, by id, with their files (relative to the
277/// component) and their bytes.
278fn components_in(dir: &Path) -> Result<BTreeMap<String, BTreeMap<String, Vec<u8>>>> {
279    let mut out = BTreeMap::new();
280    let read = |p: &Path| std::fs::read(p).map_err(|e| crate::error::io_at(p, e));
281    for rel in crate::capture::walk_files(&dir.join("instructions")) {
282        let rel = rel.to_string_lossy().replace('\\', "/");
283        let bytes = read(&dir.join("instructions").join(&rel))?;
284        out.insert(format!("instructions/{rel}"), BTreeMap::from([(String::new(), bytes)]));
285    }
286    let skills = dir.join("skills");
287    if let Ok(rd) = std::fs::read_dir(&skills) {
288        for e in rd.flatten() {
289            let name = e.file_name().to_string_lossy().into_owned();
290            if !e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
291                return Err(err(format!("skills/{name} isn't a skill directory")));
292            }
293            let mut files = BTreeMap::new();
294            for rel in crate::capture::walk_files(&e.path()) {
295                files.insert(rel.to_string_lossy().replace('\\', "/"), read(&e.path().join(&rel))?);
296            }
297            out.insert(format!("skills/{name}"), files);
298        }
299    }
300    for (sub, _) in FILE_DIRS {
301        let Ok(rd) = std::fs::read_dir(dir.join(sub)) else { continue };
302        for e in rd.flatten() {
303            let name = e.file_name().to_string_lossy().into_owned();
304            if !e.file_type().map(|t| t.is_file()).unwrap_or(false) {
305                return Err(err(format!("{sub}/{name} isn't a file")));
306            }
307            out.insert(format!("{sub}/{name}"), BTreeMap::from([(String::new(), read(&e.path())?)]));
308        }
309    }
310    Ok(out)
311}
312
313/// A component a candidate changed or added.
314#[derive(Debug, Clone)]
315pub struct Change {
316    pub id: String,
317    pub kind: String,
318    pub name: String,
319    /// `modify` or `add`.
320    pub op: String,
321    pub before: BTreeMap<String, Vec<u8>>,
322    pub after: BTreeMap<String, Vec<u8>>,
323}
324
325impl Change {
326    /// The lines added and removed, over its files.
327    pub fn changed_lines(&self) -> (usize, usize) {
328        let names: BTreeSet<&String> = self.before.keys().chain(self.after.keys()).collect();
329        let (mut added, mut removed) = (0, 0);
330        for n in names {
331            let text = |m: &BTreeMap<String, Vec<u8>>| m.get(n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
332            let (a, b) = (text(&self.before), text(&self.after));
333            for c in similar::TextDiff::from_lines(&a, &b).iter_all_changes() {
334                match c.tag() {
335                    similar::ChangeTag::Insert => added += 1,
336                    similar::ChangeTag::Delete => removed += 1,
337                    similar::ChangeTag::Equal => {}
338                }
339            }
340        }
341        (added, removed)
342    }
343
344    /// The text of the lines it added.
345    fn added_text(&self) -> String {
346        let mut out = String::new();
347        for (n, after) in &self.after {
348            let a = self.before.get(n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
349            let b = String::from_utf8_lossy(after).into_owned();
350            for c in similar::TextDiff::from_lines(&a, &b).iter_all_changes().filter(|c| c.tag() == similar::ChangeTag::Insert) {
351                out.push_str(c.value());
352            }
353        }
354        out
355    }
356}
357
358/// What `candidate` changes from the seed bundle, or why it isn't a valid candidate: only
359/// editable components changed, only kinds the bundle may add were added, nothing removed,
360/// text only, within the size and changed-line limits.
361pub fn validate(seed: &Path, spec: &BundleSpec, candidate: &Path) -> Result<Vec<Change>> {
362    let rd = std::fs::read_dir(candidate).map_err(|e| err(format!("can't read the candidate {}: {e}", candidate.display())))?;
363    for e in rd.flatten() {
364        let name = e.file_name().to_string_lossy().into_owned();
365        if !matches!(name.as_str(), "instructions" | "skills" | "subagents" | "scripts" | "middleware" | "bundle.json") {
366            return Err(err(format!("the candidate has {name}, which isn't part of a bundle (instructions/, skills/, subagents/, scripts/, middleware/)")));
367        }
368    }
369    let (old, new) = (components_in(seed)?, components_in(candidate)?);
370    let by_id: BTreeMap<&str, &Component> = spec.components.iter().map(|c| (c.id.as_str(), c)).collect();
371    let mut changes = Vec::new();
372    for id in old.keys().filter(|id| !new.contains_key(*id)) {
373        return Err(err(format!("the candidate removes {id}; removing a component isn't supported")));
374    }
375    for (id, files) in &new {
376        let before = old.get(id).cloned().unwrap_or_default();
377        if old.contains_key(id) && &before == files {
378            continue;
379        }
380        let (top, rest) = id.split_once('/').unwrap_or((id.as_str(), ""));
381        let kind = match top {
382            "skills" => "skill",
383            "instructions" => "instructions",
384            other => FILE_DIRS.iter().find(|(d, _)| *d == other).map(|(_, k)| *k).unwrap_or("instructions"),
385        };
386        let name = by_id.get(id.as_str()).map(|c| c.name.clone()).unwrap_or_else(|| if matches!(kind, "skill" | "instructions") { rest.to_string() } else { file_name_of(kind, rest) });
387        let op = match by_id.get(id.as_str()) {
388            Some(c) if !c.editable => return Err(err(format!("{id} isn't editable ({})", c.why.as_deref().unwrap_or("bundle.json"))))?,
389            Some(_) => "modify",
390            None if !spec.may_add.iter().any(|k| k == kind) => return Err(err(format!("the candidate adds {id}, but the bundle may only add {:?}", spec.may_add))),
391            None if kind == "skill" && !crate::fsutil::plain_name(&name) => return Err(err(format!("{id}: a skill's name must be a plain directory name"))),
392            None if kind == "skill" && !files.contains_key("SKILL.md") => return Err(err(format!("{id} has no SKILL.md"))),
393            None if !matches!(kind, "skill" | "instructions") && !crate::fsutil::plain_name(rest) => return Err(err(format!("{id}: a file name must be plain"))),
394            None if !plain_path(&name) => return Err(err(format!("{id} isn't a plain relative path"))),
395            None => "add",
396        };
397        let size: usize = files.values().map(Vec::len).sum();
398        if size > spec.limits.max_component_bytes {
399            return Err(err(format!("{id} is {size} bytes, over the bundle's limit of {}", spec.limits.max_component_bytes)));
400        }
401        if let Some((f, _)) = files.iter().find(|(_, b)| std::str::from_utf8(b).is_err() || b.contains(&0)) {
402            return Err(err(format!("{id}: {} isn't text", if f.is_empty() { id.as_str() } else { f.as_str() })));
403        }
404        changes.push(Change { id: id.clone(), kind: kind.into(), name, op: op.into(), before, after: files.clone() });
405    }
406    let lines: usize = changes.iter().map(|c| {
407        let (a, r) = c.changed_lines();
408        a + r
409    }).sum();
410    if lines > spec.limits.max_changed_lines {
411        return Err(err(format!("the candidate changes {lines} lines, over the bundle's limit of {}", spec.limits.max_changed_lines)));
412    }
413    Ok(changes)
414}
415
416/// The text the instruction files of a bundle give a single-completion trial as its
417/// system prompt: each non-empty file, in order.
418pub fn system_prompt(dir: &Path) -> String {
419    let mut parts = Vec::new();
420    for rel in crate::capture::walk_files(&dir.join("instructions")) {
421        if let Ok(t) = std::fs::read_to_string(dir.join("instructions").join(&rel)) {
422            if !t.trim().is_empty() {
423                parts.push(t.trim().to_string());
424            }
425        }
426    }
427    parts.join("\n\n")
428}
429
430/// The base lock with its instruction files and skills taken from bundle `dir`, saved next
431/// to it as `<dir>.trial.lock` (never inside it, where it would become part of the
432/// candidate), for a code harness's trials (`HLOCK_SKILLS_DIR`, `HLOCK_INSTRUCTIONS_DIR`).
433pub fn trial_lock(base: Option<&Lockfile>, dir: &Path, spec: &BundleSpec) -> Result<(Lockfile, PathBuf)> {
434    let mut lock = base.cloned().unwrap_or_default();
435    let have = components_in(dir)?;
436    let leaf = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "bundle".into());
437    lock.instructions = have
438        .keys()
439        .filter_map(|id| id.strip_prefix("instructions/"))
440        .map(|name| Instructions { name: name.to_string(), scope: "project".into(), vendored: Some(format!("{leaf}/instructions/{name}")), digest: std::fs::read(dir.join("instructions").join(name)).ok().map(|b| sha256_bytes(&b)), ..Default::default() })
441        .collect();
442    let mut skills = Vec::new();
443    for name in have.keys().filter_map(|id| id.strip_prefix("skills/")) {
444        let mut s = lock.skill.iter().find(|s| s.name == name).cloned().unwrap_or_else(|| crate::lockfile::Skill { name: name.to_string(), origin: "tune".into(), enabled: true, ..Default::default() });
445        s.vendored = Some(format!("{leaf}/skills/{name}"));
446        s.digest = Some(crate::capture::tree_digest(&dir.join("skills").join(name)));
447        skills.push(s);
448    }
449    // a skill the bundle doesn't carry (one that couldn't be read) keeps its lock entry
450    lock.skill.retain(|s| !spec.components.iter().any(|c| c.kind == "skill" && c.name == s.name));
451    lock.skill.extend(skills);
452    for (sub, kind) in FILE_DIRS {
453        let entries: Vec<crate::lockfile::FileComponent> = have
454            .iter()
455            .filter_map(|(id, files)| id.strip_prefix(&format!("{sub}/")).map(|f| (f, files)))
456            .map(|(file, files)| {
457                let name = file_name_of(kind, file);
458                let prev = match *kind {
459                    "subagent" => lock.subagent.iter().find(|c| c.name == name),
460                    "script" => lock.script.iter().find(|c| c.name == name),
461                    _ => lock.middleware.iter().find(|c| c.name == name),
462                };
463                crate::lockfile::FileComponent {
464                    path: prev.map(|p| p.path.clone()).unwrap_or_else(|| format!("{sub}/{file}")),
465                    format: prev.and_then(|p| p.format.clone()),
466                    name,
467                    scope: "project".into(),
468                    vendored: Some(format!("{leaf}/{sub}/{file}")),
469                    digest: files.get("").map(|b| sha256_bytes(b)),
470                    ..Default::default()
471                }
472            })
473            .collect();
474        match *kind {
475            "subagent" => lock.subagent = entries,
476            "script" => lock.script = entries,
477            _ => lock.middleware = entries,
478        }
479    }
480    let path = dir.with_file_name(format!("{leaf}.trial.lock"));
481    lock.save(&path)?;
482    Ok((lock, path))
483}
484
485// --------------------------------------------------------------------------- //
486// The evaluation session (`hlock tune eval`)
487// --------------------------------------------------------------------------- //
488
489#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
490pub struct Budget {
491    pub rollouts: Option<u64>,
492    pub usd: Option<f64>,
493}
494
495#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
496pub struct Usage {
497    pub rollouts: u64,
498    pub usd: f64,
499}
500
501/// What `hlock tune eval --session` needs to run trials the way `tune` would, saved in
502/// `<workdir>/tune/<id>/session.json`.
503#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
504pub struct Session {
505    pub id: String,
506    pub manifest: PathBuf,
507    pub lock: Option<PathBuf>,
508    /// The backend that runs the trials (`--backend`, else the manifest's).
509    pub backend: Option<String>,
510    pub harness: String,
511    pub workdir: PathBuf,
512    pub train: Vec<String>,
513    pub dev: Vec<String>,
514    pub trials: u32,
515    pub budget: Budget,
516    pub used: Usage,
517}
518
519impl Session {
520    pub fn dir(workdir: &Path, id: &str) -> PathBuf {
521        workdir.join("tune").join(id)
522    }
523
524    pub fn load(dir: &Path) -> Result<Session> {
525        let text = std::fs::read_to_string(dir.join("session.json")).map_err(|_| err(format!("no tune session at {}", dir.display())))?;
526        serde_json::from_str(&text).map_err(|e| err(format!("{}/session.json: {e}", dir.display())))
527    }
528
529    pub fn save(&self, dir: &Path) -> Result<()> {
530        crate::fsutil::write_atomic(&dir.join("session.json"), serde_json::to_string_pretty(self)? + "\n")
531    }
532
533    /// Whether the budget allows another trial.
534    pub fn exhausted(&self) -> Option<String> {
535        if let Some(r) = self.budget.rollouts.filter(|r| self.used.rollouts >= *r) {
536            return Some(format!("budget exhausted: {} of {r} rollouts", self.used.rollouts));
537        }
538        if let Some(u) = self.budget.usd.filter(|u| self.used.usd >= *u) {
539            return Some(format!("budget exhausted: ${:.2} of ${u:.2}", self.used.usd));
540        }
541        None
542    }
543}
544
545/// A stack running `bundle`: its instruction files reach a worker trial as the system
546/// prompt, and a code harness's trial through the trial lock.
547pub fn overlay(stack: &crate::search::Stack, bundle: &Path) -> crate::search::Stack {
548    let mut s = stack.clone();
549    s.overlay = Some(crate::search::Overlay { digest: candidate_digest(bundle), system_prompt: system_prompt(bundle) });
550    s
551}
552
553/// A resolver set up as `tune` sets one up for `session`, with its tasks loaded: the search
554/// split's and the holdout's.
555pub fn session_resolver(session: &Session) -> Result<(crate::resolver::Resolver, crate::manifest::Manifest, Vec<crate::tasks::Task>)> {
556    let manifest = crate::manifest::Manifest::load(&session.manifest)?;
557    let backend = crate::worker::Backend::resolve(&manifest, session.backend.as_deref())?;
558    let mut m = manifest.clone();
559    m.candidates.harness = vec![crate::manifest::HarnessCandidate { name: session.harness.clone(), ..Default::default() }];
560    let mut resolver = crate::resolver::Resolver::with_backend(m, &session.workdir, backend);
561    resolver.harness_override = Some(session.harness.clone());
562    resolver.prepare_trials()?;
563    let mut tasks = resolver.load_packs();
564    tasks.extend(resolver.holdout().to_vec());
565    Ok((resolver, manifest, tasks))
566}
567
568/// One trial of `stack` on `task`, through the session's cache: a candidate's trial on a
569/// task and seed runs once.
570pub(crate) fn cached_trial(dir: &Path, resolver: &crate::resolver::Resolver, stack: &crate::search::Stack, task: &crate::tasks::Task, seed: u64) -> Result<(crate::search::TrialResult, bool)> {
571    let key = crate::hash::sha256_hex(format!("{}\0{}\0{seed}", stack.hash(), task.id).as_bytes());
572    let path = dir.join("cache").join(format!("{}.json", &key[..32]));
573    if let Some(r) = std::fs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(&t).ok()) {
574        return Ok((r, true));
575    }
576    let r = resolver.run_trial(stack, task, seed, &dir.join("runs"));
577    std::fs::create_dir_all(path.parent().unwrap_or(dir))?;
578    crate::fsutil::write_atomic(&path, serde_json::to_string(&r)?)?;
579    Ok((r, false))
580}
581
582/// `hlock tune eval`: run `candidate` on `tasks` of `split` (`train` or `dev`), `trials`
583/// times each, and grade them. Checks the candidate against the seed first, never runs a
584/// test task, counts each trial that ran against the budget, and stops at it.
585pub fn evaluate(dir: &Path, candidate: &Path, split: &str, tasks: Option<&[String]>, trials: Option<u32>) -> Result<Value> {
586    let mut session = Session::load(dir)?;
587    let allowed = match split {
588        "train" => session.train.clone(),
589        "dev" => session.dev.clone(),
590        "test" => return Err(err("the test split is hlock's: an optimizer never sees it")),
591        other => return Err(err(format!("unknown split {other:?} (train or dev)"))),
592    };
593    let wanted: Vec<String> = tasks.map(<[String]>::to_vec).unwrap_or_else(|| allowed.clone());
594    if let Some(t) = wanted.iter().find(|t| !allowed.contains(t)) {
595        return Err(err(format!("task {t:?} isn't in the {split} split")));
596    }
597    let seed_dir = dir.join("seed");
598    let spec = BundleSpec::load(&seed_dir)?;
599    validate(&seed_dir, &spec, candidate)?;
600    // trials run on a snapshot, so a candidate the optimizer edits later isn't the one cached
601    let digest = candidate_digest(candidate);
602    let snap = dir.join("candidates").join(digest.trim_start_matches("sha256:").chars().take(12).collect::<String>());
603    if !snap.join("bundle.json").is_file() {
604        let _ = std::fs::remove_dir_all(&snap);
605        for sub in ["instructions", "skills"] {
606            if candidate.join(sub).is_dir() {
607                crate::fsutil::copy_tree(&candidate.join(sub), &snap.join(sub))?;
608            }
609        }
610        std::fs::copy(seed_dir.join("bundle.json"), snap.join("bundle.json"))?;
611    }
612    let (mut resolver, _, all) = session_resolver(&session)?;
613    let base_lock = session.lock.as_deref().filter(|p| p.is_file()).map(Lockfile::load).transpose()?;
614    let stack = overlay(&base_stack_for(&session, base_lock.as_ref())?, &snap);
615    resolver.trial_locks.insert(stack.hash(), trial_lock(base_lock.as_ref(), &snap, &spec)?);
616    let by_id: BTreeMap<&str, &crate::tasks::Task> = all.iter().map(|t| (t.id.as_str(), t)).collect();
617    let trials = trials.unwrap_or(session.trials).max(1);
618    let mut results = Vec::new();
619    let mut stopped = None;
620    'run: for id in &wanted {
621        let task = by_id.get(id.as_str()).ok_or_else(|| err(format!("task {id:?} isn't in the eval packs any more")))?;
622        for t in 0..trials {
623            let key_cached = {
624                let key = crate::hash::sha256_hex(format!("{}\0{}\0{t}", stack.hash(), task.id).as_bytes());
625                dir.join("cache").join(format!("{}.json", &key[..32])).is_file()
626            };
627            if !key_cached {
628                if let Some(why) = session.exhausted() {
629                    stopped = Some(why);
630                    break 'run;
631                }
632            }
633            let (r, cached) = cached_trial(dir, &resolver, &stack, task, u64::from(t))?;
634            if !cached {
635                session.used.rollouts += 1;
636                session.used.usd += r.cost_usd;
637                session.save(dir)?;
638            }
639            let short: String = stack.hash().trim_start_matches("sha256:").chars().take(12).collect();
640            results.push(json!({
641                "task": task.id, "trial": t, "success": r.success, "score": r.score,
642                "feedback": r.detail.clone().unwrap_or_else(|| if r.success { "passed".into() } else { "failed".into() }),
643                "workspace": dir.join("runs").join(format!("{short}_{}_{t}", task.id)),
644                "cost_usd": r.cost_usd, "latency_s": r.latency_s, "cached": cached,
645            }));
646        }
647    }
648    if results.is_empty() {
649        if let Some(why) = stopped {
650            return Err(err(why));
651        }
652    }
653    let left = session.budget.rollouts.map(|r| r.saturating_sub(session.used.rollouts));
654    Ok(json!({
655        "candidate": digest,
656        "split": split,
657        "results": results,
658        "budget": {"rollouts_used": session.used.rollouts, "rollouts_left": left, "usd_used": session.used.usd, "exhausted": stopped},
659    }))
660}
661
662/// The stack a session's trials start from: the base lock's, as `tune` builds it.
663fn base_stack_for(session: &Session, base: Option<&Lockfile>) -> Result<crate::search::Stack> {
664    let manifest = crate::manifest::Manifest::load(&session.manifest)?;
665    let mut s = crate::ops::base_stack(base, &manifest, Some(&session.harness));
666    crate::ops::unset_rejected(&mut s, &crate::models::ModelTable::load(&crate::profiles::Ctx::from_process())?);
667    Ok(s)
668}
669
670// --------------------------------------------------------------------------- //
671// Acceptance
672// --------------------------------------------------------------------------- //
673
674/// The one-sided sign test: how likely `wins` or more wins in `wins + losses` tasks that
675/// differ would be if neither side were better.
676pub fn sign_test(wins: usize, losses: usize) -> f64 {
677    let n = wins + losses;
678    if n == 0 {
679        return 1.0;
680    }
681    let mut p = 0.0;
682    let mut c = 1.0f64; // C(n, 0)
683    for k in 0..=n {
684        if k >= wins {
685            p += c;
686        }
687        c = c * (n - k) as f64 / (k + 1) as f64;
688    }
689    p / 2f64.powi(n as i32)
690}
691
692/// Text from the eval pack that an edit mustn't copy: task ids, the literal strings graders
693/// check for, and fixture file names. Short strings are left out: they'd match ordinary words.
694pub fn pack_literals(tasks: &[crate::tasks::Task]) -> BTreeSet<String> {
695    let mut out = BTreeSet::new();
696    for t in tasks {
697        if t.id.len() >= 4 {
698            out.insert(t.id.clone());
699        }
700        for g in &t.graders {
701            for key in ["equals", "contains"] {
702                match g.get(key) {
703                    Some(Value::String(s)) => {
704                        out.insert(s.clone());
705                    }
706                    Some(Value::Array(a)) => out.extend(a.iter().filter_map(Value::as_str).map(str::to_string)),
707                    _ => {}
708                }
709            }
710        }
711        if let (Some(f), Some(p)) = (&t.fixtures, &t.pack_dir) {
712            for rel in crate::capture::walk_files(&p.join(f)) {
713                if let Some(n) = rel.file_name() {
714                    out.insert(n.to_string_lossy().into_owned());
715                }
716            }
717        }
718    }
719    out.retain(|s| s.trim().len() >= 6 || (s.len() >= 4 && s.contains('_')));
720    out
721}
722
723/// The pack text each change's added lines copy, by component id.
724pub fn leaks(changes: &[Change], literals: &BTreeSet<String>) -> BTreeMap<String, Vec<String>> {
725    let mut out = BTreeMap::new();
726    for c in changes {
727        let added = c.added_text();
728        let hits: Vec<String> = literals.iter().filter(|l| added.contains(l.as_str())).cloned().collect();
729        if !hits.is_empty() {
730            out.insert(c.id.clone(), hits);
731        }
732    }
733    out
734}
735
736/// Put `id`'s seed version back into `candidate`, dropping the optimizer's edit to it.
737pub fn revert(seed: &Path, candidate: &Path, id: &str) -> Result<()> {
738    let (from, to) = (seed.join(id), candidate.join(id));
739    if to.is_dir() {
740        std::fs::remove_dir_all(&to)?;
741    } else if to.exists() {
742        std::fs::remove_file(&to)?;
743    }
744    if from.is_dir() {
745        crate::fsutil::copy_tree(&from, &to)?;
746    } else if from.is_file() {
747        std::fs::copy(&from, &to)?;
748    }
749    Ok(())
750}
751
752/// Write each change's content next to the tune lock, under `.hlock/tuned/<digest>/`, and
753/// point the lock's entry for it there. Returns the `[[tune.edit]]` entries.
754pub fn apply_to_lock(lf: &mut Lockfile, profile: Option<&crate::profiles::HarnessProfile>, out_dir: &Path, candidate: &Path, changes: &[Change], ledger: &[Value]) -> Result<Vec<Value>> {
755    let mut edits = Vec::new();
756    for c in changes {
757        let src = candidate.join(&c.id);
758        if matches!(c.kind.as_str(), "subagent" | "script" | "middleware") {
759            edits.push(apply_file(lf, profile, out_dir, &src, c, ledger)?);
760            continue;
761        }
762        let (after, before) = if c.kind == "skill" {
763            (crate::capture::tree_digest(&src), lf.skill.iter().find(|s| s.name == c.name).and_then(|s| s.digest.clone()))
764        } else {
765            (sha256_bytes(&std::fs::read(&src)?), lf.instructions.iter().find(|i| i.name == c.name).and_then(|i| i.digest.clone()))
766        };
767        let short: String = after.trim_start_matches("sha256:").chars().take(8).collect();
768        let rel = if c.kind == "skill" { format!(".hlock/tuned/{short}/skills/{}", c.name) } else { format!(".hlock/tuned/{short}/{}", c.name) };
769        let dest = out_dir.join(&rel);
770        if c.kind == "skill" {
771            let _ = std::fs::remove_dir_all(&dest);
772            crate::fsutil::copy_tree(&src, &dest)?;
773            let scan = crate::scan::record(&crate::scan::scan_path(&dest, &rel), false);
774            match lf.skill.iter_mut().find(|s| s.name == c.name) {
775                Some(s) => {
776                    s.digest = Some(after.clone());
777                    s.vendored = Some(rel.clone());
778                    s.scan = Some(scan);
779                    s.scripts = Some(crate::capture::skill_scripts(&dest));
780                }
781                None => lf.skill.push(crate::lockfile::Skill {
782                    name: c.name.clone(),
783                    origin: "tune".into(),
784                    digest: Some(after.clone()),
785                    enabled: true,
786                    scope: Some("project".into()),
787                    vendored: Some(rel.clone()),
788                    scan: Some(scan),
789                    scripts: Some(crate::capture::skill_scripts(&dest)),
790                    ..Default::default()
791                }),
792            }
793        } else {
794            std::fs::create_dir_all(dest.parent().unwrap_or(out_dir))?;
795            std::fs::copy(&src, &dest)?;
796            let text = std::fs::read_to_string(&dest).unwrap_or_default();
797            let entry = Instructions { name: c.name.clone(), digest: Some(after.clone()), scope: "project".into(), vendored: Some(rel.clone()), source: Some("tune".into()), scan: Some(crate::scan::record(&crate::scan::scan_text(&text, &rel), false)), ..Default::default() };
798            match lf.instructions.iter_mut().find(|i| i.name == c.name) {
799                Some(i) => *i = entry,
800                None => lf.instructions.push(entry),
801            }
802        }
803        let note = ledger.iter().rev().find(|l| l["component"].as_str() == Some(c.id.as_str()));
804        // a file the lock had no entry for is an addition to the lock, whatever the bundle held
805        let op = if before.is_none() { "add" } else { c.op.as_str() };
806        let mut e = json!({"component": c.id, "kind": c.kind, "op": op, "after": after, "path": rel});
807        if let Some(b) = before {
808            e["before"] = json!(b);
809        }
810        if let Some(r) = note.and_then(|l| l["rationale"].as_str()) {
811            e["rationale"] = json!(r);
812        }
813        edits.push(e);
814    }
815    Ok(edits)
816}
817
818/// [`apply_to_lock`] for a subagent, script or middleware file.
819fn apply_file(lf: &mut Lockfile, profile: Option<&crate::profiles::HarnessProfile>, out_dir: &Path, src: &Path, c: &Change, ledger: &[Value]) -> Result<Value> {
820    let bytes = std::fs::read(src)?;
821    let after = sha256_bytes(&bytes);
822    let file = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
823    let short: String = after.trim_start_matches("sha256:").chars().take(8).collect();
824    let sub = FILE_DIRS.iter().find(|(_, k)| *k == c.kind).map(|(d, _)| *d).unwrap_or("files");
825    let rel = format!(".hlock/tuned/{short}/{sub}/{file}");
826    let dest = out_dir.join(&rel);
827    std::fs::create_dir_all(dest.parent().unwrap_or(out_dir))?;
828    std::fs::write(&dest, &bytes)?;
829    #[cfg(unix)]
830    if c.kind == "script" {
831        use std::os::unix::fs::PermissionsExt;
832        let _ = std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755));
833    }
834    let scan = crate::scan::record(&crate::scan::scan_bytes(&bytes, &rel), false);
835    let items = match c.kind.as_str() {
836        "subagent" => &mut lf.subagent,
837        "script" => &mut lf.script,
838        _ => &mut lf.middleware,
839    };
840    let before = items.iter().find(|x| x.name == c.name).and_then(|x| x.digest.clone());
841    match items.iter_mut().find(|x| x.name == c.name) {
842        Some(x) => {
843            x.digest = Some(after.clone());
844            x.vendored = Some(rel.clone());
845            x.source = Some("tune".into());
846            x.scan = Some(scan);
847        }
848        None => {
849            let path = file_dest(profile, &c.kind, &file).ok_or_else(|| err(format!("{} has no place for a {}", profile.map(|p| p.name.as_str()).unwrap_or("the harness"), c.kind)))?;
850            let format = if c.kind == "middleware" { profile.and_then(|p| p.middleware.as_ref()).and_then(|m| m.format.clone()) } else { None };
851            items.push(crate::lockfile::FileComponent { name: c.name.clone(), path, digest: Some(after.clone()), scope: "project".into(), vendored: Some(rel.clone()), format, source: Some("tune".into()), scan: Some(scan) });
852        }
853    }
854    let mut e = json!({"component": c.id, "kind": c.kind, "op": if before.is_none() { "add" } else { "modify" }, "after": after, "path": rel});
855    if let Some(b) = before {
856        e["before"] = json!(b);
857    }
858    if let Some(r) = ledger.iter().rev().find(|l| l["component"].as_str() == Some(c.id.as_str())).and_then(|l| l["rationale"].as_str()) {
859        e["rationale"] = json!(r);
860    }
861    Ok(e)
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    #[test]
869    fn optimizers_are_resolved_apart_from_backends() {
870        let m = |toml: &str| crate::manifest::Manifest::from_str(toml).unwrap();
871        let none = m("");
872        assert_eq!(Optimizer::resolve(&none, "hlock").unwrap().runner, OptimizerRunner::Python { object: None });
873        assert_eq!(Optimizer::resolve(&none, "harness2").unwrap().source(), "built in");
874        let m2 = m("[optimizers.harness2]\noptions = { k = 2 }\n[optimizers.ace]\ncommand = [\"ace\", \"-v\"]\n[optimizers.gepa]\npython = \"hlock_gepa:Gepa\"\n[backends.ray]\ncommand = \"ray\"\n");
875        let h2 = Optimizer::resolve(&m2, "harness2").unwrap();
876        assert_eq!(h2.to_value(), json!({"name": "harness2", "options": {"k": 2}, "object": null, "command": null}));
877        assert_eq!(Optimizer::resolve(&m2, "ace").unwrap().runner, OptimizerRunner::Command(vec!["ace".into(), "-v".into()]));
878        assert_eq!(Optimizer::resolve(&m2, "gepa").unwrap().to_value()["object"], json!("hlock_gepa:Gepa"));
879        let e = Optimizer::resolve(&m2, "ray").unwrap_err().to_string();
880        assert!(e.contains("names a backend") && e.contains("[optimizers.ray]"), "{e}");
881        for (toml, name, why) in [
882            ("[optimizers.hlock]\ncommand = \"x\"\n", "hlock", "can only set options"),
883            ("[optimizers.x]\ncommand = \"x\"\npython = \"a:b\"\n", "x", "keep one"),
884            ("[optimizers.x]\noptions = 3\n", "x", "options must be a table"),
885            ("", "../x", "isn't a valid name"),
886        ] {
887            let e = Optimizer::resolve(&m(toml), name).unwrap_err().to_string();
888            assert!(e.contains(why), "{toml}: {e}");
889        }
890        assert!(m("[optimizers.x]\npyhton = \"a:b\"\n").problems().iter().any(|p| p.contains("unknown key `pyhton` in [optimizers.x]")));
891    }
892
893    fn tmp(tag: &str) -> PathBuf {
894        let d = std::env::temp_dir().join(format!("hlock-optimize-{tag}-{}", std::process::id()));
895        let _ = std::fs::remove_dir_all(&d);
896        std::fs::create_dir_all(&d).unwrap();
897        d
898    }
899
900    fn seed(d: &Path, edit: &[&str]) -> (PathBuf, BundleSpec) {
901        std::fs::write(d.join("CLAUDE.md"), "Be brief.\n").unwrap();
902        std::fs::create_dir_all(d.join("skills/review")).unwrap();
903        std::fs::write(d.join("skills/review/SKILL.md"), "---\nname: review\n---\nRead the diff.\n").unwrap();
904        let lock = Lockfile {
905            instructions: vec![Instructions { name: "CLAUDE.md".into(), scope: "project".into(), ..Default::default() }],
906            skill: vec![crate::lockfile::Skill { name: "review".into(), path: Some("skills/review".into()), enabled: true, ..Default::default() }],
907            ..Default::default()
908        };
909        let edit: Vec<String> = edit.iter().map(|s| s.to_string()).collect();
910        let dest = d.join("seed");
911        let spec = write_seed(Some(&lock), None, d, "claude-code", "CLAUDE.md", &edit, &dest).unwrap();
912        (dest, spec)
913    }
914
915    fn copy(from: &Path, to: &Path) {
916        crate::fsutil::copy_tree(from, to).unwrap();
917    }
918
919    #[test]
920    fn the_seed_bundle_holds_the_lock_s_text_and_says_what_is_editable() {
921        let d = tmp("seed");
922        let (s, spec) = seed(&d, &["instructions"]);
923        assert_eq!(std::fs::read_to_string(s.join("instructions/CLAUDE.md")).unwrap(), "Be brief.\n");
924        assert!(s.join("skills/review/SKILL.md").is_file());
925        let by: BTreeMap<&str, bool> = spec.components.iter().map(|c| (c.id.as_str(), c.editable)).collect();
926        assert_eq!(by, BTreeMap::from([("instructions/CLAUDE.md", true), ("skills/review", false)]));
927        assert_eq!(spec.may_add, ["instructions"]);
928        assert_eq!(BundleSpec::load(&s).unwrap(), spec);
929    }
930
931    #[test]
932    fn validation_allows_editable_changes_and_refuses_the_rest() {
933        let d = tmp("validate");
934        let (s, spec) = seed(&d, &["instructions"]);
935        let cand = d.join("cand");
936        copy(&s, &cand);
937        assert!(validate(&s, &spec, &cand).unwrap().is_empty());
938        std::fs::write(cand.join("instructions/CLAUDE.md"), "Be brief.\nRun the tests first.\n").unwrap();
939        let ch = validate(&s, &spec, &cand).unwrap();
940        assert_eq!((ch[0].id.as_str(), ch[0].op.as_str(), ch[0].changed_lines()), ("instructions/CLAUDE.md", "modify", (1, 0)));
941        std::fs::write(cand.join("skills/review/SKILL.md"), "changed\n").unwrap();
942        assert!(validate(&s, &spec, &cand).unwrap_err().to_string().contains("skills/review isn't editable"));
943        std::fs::write(cand.join("skills/review/SKILL.md"), "---\nname: review\n---\nRead the diff.\n").unwrap();
944        std::fs::create_dir_all(cand.join("skills/new")).unwrap();
945        std::fs::write(cand.join("skills/new/SKILL.md"), "x\n").unwrap();
946        assert!(validate(&s, &spec, &cand).unwrap_err().to_string().contains("may only add"));
947        std::fs::remove_dir_all(cand.join("skills/new")).unwrap();
948        std::fs::write(cand.join("instructions/CLAUDE.md"), "x\n".repeat(200)).unwrap();
949        assert!(validate(&s, &spec, &cand).unwrap_err().to_string().contains("over the bundle's limit"));
950        std::fs::write(cand.join("evil.sh"), "x").unwrap();
951        assert!(validate(&s, &spec, &cand).unwrap_err().to_string().contains("isn't part of a bundle"));
952    }
953
954    #[test]
955    fn subagents_scripts_and_middleware_are_bundle_files() {
956        let d = tmp("files");
957        std::fs::create_dir_all(d.join(".claude/agents")).unwrap();
958        std::fs::write(d.join(".claude/agents/reviewer.md"), "---\nname: reviewer\n---\nRead.\n").unwrap();
959        let lock = Lockfile {
960            subagent: vec![crate::lockfile::FileComponent { name: "reviewer".into(), path: ".claude/agents/reviewer.md".into(), scope: "project".into(), ..Default::default() }],
961            ..Default::default()
962        };
963        let edit: Vec<String> = ["subagent", "script"].iter().map(|s| s.to_string()).collect();
964        let seed = d.join("seed");
965        let spec = write_seed(Some(&lock), None, &d, "claude-code", "CLAUDE.md", &edit, &seed).unwrap();
966        assert!(spec.components.iter().any(|c| c.id == "subagents/reviewer.md" && c.kind == "subagent" && c.name == "reviewer" && c.editable));
967        // with no harness profile there's no place for a new subagent: only scripts can be added
968        assert_eq!(spec.may_add, ["script"]);
969        let cand = d.join("cand");
970        crate::fsutil::copy_tree(&seed, &cand).unwrap();
971        std::fs::write(cand.join("subagents/reviewer.md"), "---\nname: reviewer\n---\nRead, then test.\n").unwrap();
972        std::fs::create_dir_all(cand.join("scripts")).unwrap();
973        std::fs::write(cand.join("scripts/check.py"), "print('ok')\n").unwrap();
974        let ch = validate(&seed, &spec, &cand).unwrap();
975        let by: BTreeMap<&str, (&str, &str, &str)> = ch.iter().map(|c| (c.id.as_str(), (c.kind.as_str(), c.name.as_str(), c.op.as_str()))).collect();
976        assert_eq!(by, BTreeMap::from([("scripts/check.py", ("script", "check.py", "add")), ("subagents/reviewer.md", ("subagent", "reviewer", "modify"))]));
977        let mut lf = lock.clone();
978        let edits = apply_to_lock(&mut lf, None, &d, &cand, &ch, &[]).unwrap();
979        assert_eq!(edits.len(), 2);
980        assert_eq!(lf.script[0].path, ".agents/scripts/check.py");
981        assert_eq!(lf.subagent[0].source.as_deref(), Some("tune"));
982        assert!(lf.subagent[0].vendored.as_deref().unwrap().ends_with("/subagents/reviewer.md"));
983        let (tl, _) = trial_lock(None, &cand, &spec).unwrap();
984        assert_eq!(tl.subagent[0].vendored.as_deref(), Some("cand/subagents/reviewer.md"));
985    }
986
987    #[test]
988    fn the_sign_test() {
989        assert!((sign_test(5, 0) - 1.0 / 32.0).abs() < 1e-12);
990        assert!((sign_test(0, 0) - 1.0).abs() < 1e-12);
991        assert!((sign_test(1, 1) - 0.75).abs() < 1e-12);
992        assert!(sign_test(9, 1) < 0.05 && sign_test(2, 0) > 0.05);
993    }
994
995    #[test]
996    fn an_edit_that_copies_pack_text_is_caught() {
997        let c = Change {
998            id: "instructions/CLAUDE.md".into(),
999            kind: "instructions".into(),
1000            name: "CLAUDE.md".into(),
1001            op: "modify".into(),
1002            before: BTreeMap::from([(String::new(), b"For count_words, be careful.\n".to_vec())]),
1003            after: BTreeMap::from([(String::new(), b"For count_words, be careful.\nThe answer is 42 widgets.\n".to_vec())]),
1004        };
1005        let lits = BTreeSet::from(["count_words".to_string(), "42 widgets".to_string()]);
1006        // only what the edit added counts: the task id was already there
1007        assert_eq!(leaks(&[c], &lits), BTreeMap::from([("instructions/CLAUDE.md".to_string(), vec!["42 widgets".to_string()])]));
1008    }
1009
1010    #[test]
1011    fn applying_writes_tuned_files_and_points_the_lock_at_them() {
1012        let d = tmp("apply");
1013        let (s, spec) = seed(&d, &["instructions", "skill"]);
1014        let cand = d.join("cand");
1015        copy(&s, &cand);
1016        std::fs::write(cand.join("instructions/CLAUDE.md"), "Be brief.\nRun the tests first.\n").unwrap();
1017        let changes = validate(&s, &spec, &cand).unwrap();
1018        let mut lf = Lockfile { instructions: vec![Instructions { name: "CLAUDE.md".into(), digest: Some(sha256_bytes(b"Be brief.\n")), ..Default::default() }], ..Default::default() };
1019        let ledger = vec![json!({"component": "instructions/CLAUDE.md", "op": "modify", "rationale": "tests were skipped"})];
1020        let edits = apply_to_lock(&mut lf, None, &d, &cand, &changes, &ledger).unwrap();
1021        let i = &lf.instructions[0];
1022        assert_eq!(i.source.as_deref(), Some("tune"));
1023        let rel = i.vendored.clone().unwrap();
1024        assert!(rel.starts_with(".hlock/tuned/") && rel.ends_with("/CLAUDE.md"));
1025        assert_eq!(std::fs::read_to_string(d.join(&rel)).unwrap(), "Be brief.\nRun the tests first.\n");
1026        assert_eq!(edits[0]["rationale"], "tests were skipped");
1027        assert_eq!(edits[0]["before"], json!(sha256_bytes(b"Be brief.\n")));
1028    }
1029
1030    #[test]
1031    fn the_trial_lock_places_the_bundle() {
1032        let d = tmp("trial");
1033        let (s, spec) = seed(&d, &["instructions"]);
1034        let (lock, path) = trial_lock(None, &s, &spec).unwrap();
1035        assert_eq!(path, d.join("seed.trial.lock"));
1036        assert_eq!(lock.instructions[0].vendored.as_deref(), Some("seed/instructions/CLAUDE.md"));
1037        assert_eq!(lock.skill[0].vendored.as_deref(), Some("seed/skills/review"));
1038        assert_eq!(system_prompt(&s), "Be brief.");
1039    }
1040}