Skip to main content

harness_lock_core/
profiles.rs

1//! Harness and runtime profiles: declarative descriptions of agent harnesses
2//! (Claude Code, Codex, Pi, OpenCode, …) and local inference runtimes (Ollama,
3//! LM Studio, vLLM, …).
4//!
5//! A profile says where a harness keeps its config, how to find its model, MCP
6//! servers, skills and plugins, how it was installed, and how to relocate its
7//! config root for an isolated session. Built-in profiles ship inside the crate
8//! (`profiles/`); users add or override them with TOML files in a profile
9//! directory (see [`profile_dirs`]), so new harnesses need no code change.
10
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13use std::process::{Command, Stdio};
14use std::time::{Duration, Instant};
15
16use serde::{Deserialize, Serialize};
17
18use crate::error::{Error, Result};
19
20// --------------------------------------------------------------------------- //
21// Built-in profiles
22// --------------------------------------------------------------------------- //
23
24const BUILTIN_HARNESSES: &[(&str, &str)] = &[
25    ("claude-code", include_str!("../profiles/harnesses/claude-code.toml")),
26    ("codex", include_str!("../profiles/harnesses/codex.toml")),
27    ("pi", include_str!("../profiles/harnesses/pi.toml")),
28    ("opencode", include_str!("../profiles/harnesses/opencode.toml")),
29    ("hermes", include_str!("../profiles/harnesses/hermes.toml")),
30    ("cursor-agent", include_str!("../profiles/harnesses/cursor-agent.toml")),
31    ("gemini-cli", include_str!("../profiles/harnesses/gemini-cli.toml")),
32    ("copilot-cli", include_str!("../profiles/harnesses/copilot-cli.toml")),
33    ("goose", include_str!("../profiles/harnesses/goose.toml")),
34    ("amp", include_str!("../profiles/harnesses/amp.toml")),
35    // frameworks: code harnesses a project builds on (`[harnesses.<id>] framework = …`)
36    ("pydantic-ai", include_str!("../profiles/harnesses/pydantic-ai.toml")),
37    ("deepagents", include_str!("../profiles/harnesses/deepagents.toml")),
38    ("langgraph", include_str!("../profiles/harnesses/langgraph.toml")),
39    ("openai-agents", include_str!("../profiles/harnesses/openai-agents.toml")),
40    ("claude-agent-sdk", include_str!("../profiles/harnesses/claude-agent-sdk.toml")),
41    ("google-adk", include_str!("../profiles/harnesses/google-adk.toml")),
42    ("smolagents", include_str!("../profiles/harnesses/smolagents.toml")),
43    ("crewai", include_str!("../profiles/harnesses/crewai.toml")),
44];
45
46const BUILTIN_RUNTIMES: &[(&str, &str)] = &[
47    ("ollama", include_str!("../profiles/runtimes/ollama.toml")),
48    ("lmstudio", include_str!("../profiles/runtimes/lmstudio.toml")),
49    ("llama-cpp", include_str!("../profiles/runtimes/llama-cpp.toml")),
50    ("vllm", include_str!("../profiles/runtimes/vllm.toml")),
51    ("sglang", include_str!("../profiles/runtimes/sglang.toml")),
52    ("mlx-lm", include_str!("../profiles/runtimes/mlx-lm.toml")),
53    ("localai", include_str!("../profiles/runtimes/localai.toml")),
54    ("docker-model-runner", include_str!("../profiles/runtimes/docker-model-runner.toml")),
55    ("jan", include_str!("../profiles/runtimes/jan.toml")),
56];
57
58// --------------------------------------------------------------------------- //
59// Environment context
60// --------------------------------------------------------------------------- //
61
62/// The slice of the process environment that profiles read: home and working
63/// directories, environment variables, and the `PATH` search list. Tests build
64/// one by hand so nothing depends on the real machine.
65#[derive(Debug, Clone)]
66pub struct Ctx {
67    pub home: PathBuf,
68    pub cwd: PathBuf,
69    pub env: BTreeMap<String, String>,
70    pub path: Vec<PathBuf>,
71}
72
73impl Ctx {
74    pub fn from_process() -> Ctx {
75        let env: BTreeMap<String, String> = std::env::vars().collect();
76        let home = env.get("HOME").or_else(|| env.get("USERPROFILE")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
77        let path = env.get("PATH").map(|p| std::env::split_paths(p).collect()).unwrap_or_default();
78        Ctx {
79            home,
80            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
81            env,
82            path,
83        }
84    }
85
86    /// A non-empty environment variable.
87    pub fn var(&self, key: &str) -> Option<&str> {
88        self.env.get(key).map(String::as_str).filter(|v| !v.is_empty())
89    }
90
91    /// Expand `~`, `{root}`, `{home}` and relative (project) paths.
92    pub fn expand(&self, template: &str, root: Option<&Path>) -> PathBuf {
93        let mut s = template.to_string();
94        if let Some(r) = root {
95            s = s.replace("{root}", &r.to_string_lossy());
96        }
97        s = s.replace("{home}", &self.home.to_string_lossy());
98        if s == "~" {
99            return self.home.clone();
100        }
101        if let Some(rest) = s.strip_prefix("~/") {
102            return self.home.join(rest);
103        }
104        let p = PathBuf::from(&s);
105        if p.is_absolute() {
106            p
107        } else {
108            self.cwd.join(p)
109        }
110    }
111
112    /// Resolve a binary name on `PATH`.
113    pub fn which(&self, name: &str) -> Option<PathBuf> {
114        if name.contains('/') {
115            let p = PathBuf::from(name);
116            return p.is_file().then_some(p);
117        }
118        for dir in &self.path {
119            let cand = dir.join(name);
120            if cand.is_file() {
121                return Some(cand);
122            }
123        }
124        None
125    }
126}
127
128// --------------------------------------------------------------------------- //
129// Profile schema
130// --------------------------------------------------------------------------- //
131
132#[derive(Debug, Clone, Serialize, Deserialize, Default)]
133#[serde(default, rename_all = "kebab-case")]
134pub struct VersionProbe {
135    pub args: Vec<String>,
136}
137
138/// Where the harness keeps its user-level config, and the variable that moves it.
139#[derive(Debug, Clone, Serialize, Deserialize, Default)]
140#[serde(default, rename_all = "kebab-case")]
141pub struct ConfigRoot {
142    /// Variable that relocates the root (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, …).
143    pub env: Option<String>,
144    /// Appended to `env` when it names a parent dir (`XDG_CONFIG_HOME` + `opencode`).
145    pub suffix: Option<String>,
146    pub default: String,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize, Default)]
150#[serde(default, rename_all = "kebab-case")]
151pub struct InstallMethod {
152    /// `npm` | `brew` | `brew-cask` | `pip` | `uv-tool` | `script` | `manual`
153    pub method: String,
154    pub package: Option<String>,
155    /// Shell command for `script` / instructions for `manual` (`{version}` is substituted).
156    pub command: Option<String>,
157    /// Substrings of the binary's real path that identify this install method.
158    pub path_hints: Vec<String>,
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize, Default)]
162#[serde(default, rename_all = "kebab-case")]
163pub struct FileSpec {
164    pub path: String,
165    /// Location when the config root is relocated (for files that live outside it).
166    pub isolated: Option<String>,
167    /// `json` | `jsonc` | `toml` | `yaml`
168    pub format: String,
169    /// `whole` (restore the file) | `pointers` (restore only `pointers`) | `record` (digest only)
170    pub restore: String,
171    pub pointers: Vec<String>,
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize, Default)]
175#[serde(default, rename_all = "kebab-case")]
176pub struct ModelSpec {
177    /// Ordered sources (`env:VAR` or `<file>#<json-pointer>`); the first hit wins.
178    pub default: Vec<String>,
179    pub small: Vec<String>,
180    pub provider: Vec<String>,
181    pub base_url: Vec<String>,
182    /// `provider/model` when the model value carries its provider.
183    pub format: Option<String>,
184    pub default_provider: Option<String>,
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize, Default)]
188#[serde(default, rename_all = "kebab-case")]
189pub struct ProviderSpec {
190    pub source: Vec<String>,
191    /// Pointers (relative to one provider entry) to its base URL.
192    pub base_url: Vec<String>,
193    pub models: Vec<String>,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize, Default)]
197#[serde(default, rename_all = "kebab-case")]
198pub struct McpSpec {
199    pub sources: Vec<String>,
200    pub write: Option<String>,
201    /// How servers are written: `standard` (`command`/`args`/`env`, `url`/`headers`),
202    /// `opencode`, `goose`, or `codex`.
203    pub shape: Option<String>,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize, Default)]
207#[serde(default, rename_all = "kebab-case")]
208pub struct SkillsSpec {
209    pub dirs: Vec<String>,
210    pub write: Option<String>,
211    /// Directories whose skills ship with the harness itself.
212    pub builtin_dirs: Vec<String>,
213    /// A file listing the harness's bundled skills, one per line or as keys.
214    pub builtin_manifest: Option<String>,
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize, Default)]
218#[serde(default, rename_all = "kebab-case")]
219pub struct BundleSpec {
220    /// `plugin` | `package` | `extension`
221    pub kind: String,
222    /// `claude-plugins` | `pi-packages` | `npm-list`
223    pub extractor: String,
224    pub source: String,
225    pub lockfile: Option<String>,
226}
227
228#[derive(Debug, Clone, Serialize, Deserialize, Default)]
229#[serde(default, rename_all = "kebab-case")]
230pub struct LaunchSpec {
231    pub args: Vec<String>,
232    pub model_flag: Option<String>,
233}
234
235/// How `hlock localize` points a harness at a local OpenAI-compatible endpoint:
236/// values to set (by JSON pointer) in one of the profile's files. Strings and keys
237/// may use `{provider}`, `{model}`, `{base_url}` and `{host}`.
238#[derive(Debug, Clone, Serialize, Deserialize, Default)]
239#[serde(default, rename_all = "kebab-case")]
240pub struct LocalProvider {
241    pub file: String,
242    pub set: BTreeMap<String, serde_json::Value>,
243}
244
245/// A model `hlock localize` may pick for a runtime.
246#[derive(Debug, Clone, Serialize, Deserialize, Default)]
247#[serde(default, rename_all = "kebab-case")]
248pub struct CatalogModel {
249    pub id: String,
250    pub params_b: Option<f64>,
251    /// Memory the weights plus a working context need.
252    pub min_memory_gb: Option<f64>,
253    /// 3 strong agentic coder, 2 capable, 1 small/fast.
254    pub tier: u8,
255    /// Reliable tool calling.
256    pub tools: bool,
257    /// Roles it suits (empty: any).
258    pub roles: Vec<String>,
259}
260
261/// How hlock runs a code harness (a framework agent or a custom script).
262#[derive(Debug, Clone, Serialize, Deserialize, Default)]
263#[serde(default, rename_all = "kebab-case")]
264pub struct RunSpec {
265    /// Python `module:callable`, called as `fn(prompt, ctx)`.
266    pub entrypoint: Option<String>,
267    /// Any executable; `{prompt}`, `{model}` and `{workspace}` are substituted.
268    pub command: Vec<String>,
269    /// Interpreter for `entrypoint` (default: `HL_PYTHON`, else `python3`).
270    pub python: Option<String>,
271    pub env: BTreeMap<String, String>,
272}
273
274/// A declarative description of one agent harness.
275#[derive(Debug, Clone, Serialize, Deserialize, Default)]
276#[serde(default, rename_all = "kebab-case")]
277pub struct HarnessProfile {
278    pub id: String,
279    pub name: String,
280    /// `cli` (an installed agent CLI), `framework` (a Python/JS agent library), or
281    /// `custom` (a project's own agent, declared under `[harnesses.<id>]`).
282    pub kind: String,
283    pub aliases: Vec<String>,
284    pub vendor: Option<String>,
285    pub homepage: Option<String>,
286    /// `full` (pin, sync and launch are tested) or `basic` (detect, version, MCP, skills).
287    pub support: String,
288    /// Open-source license (for `hlock localize`, which prefers open harnesses).
289    pub open_source: Option<bool>,
290    /// Can use a local OpenAI- or Anthropic-compatible model endpoint.
291    pub local_models: Option<bool>,
292    /// How to configure a local model endpoint (`hlock localize`).
293    pub local_provider: Vec<LocalProvider>,
294    /// Framework profile a custom harness builds on (`pydantic-ai`, `deepagents`, …).
295    pub framework: Option<String>,
296    /// Packages whose installed versions are pinned (`pypi:pydantic-ai`, `npm:…`).
297    pub packages: Vec<String>,
298    /// How to run a code harness.
299    pub run: RunSpec,
300    pub binaries: Vec<String>,
301    pub version: VersionProbe,
302    /// Variables a harness sets in the processes it spawns (detects "running inside").
303    pub active_env: Vec<String>,
304    pub config_root: ConfigRoot,
305    pub instructions: Vec<String>,
306    pub install: Vec<InstallMethod>,
307    pub files: BTreeMap<String, FileSpec>,
308    pub model: ModelSpec,
309    pub providers: Option<ProviderSpec>,
310    pub mcp: McpSpec,
311    pub skills: SkillsSpec,
312    pub bundles: Vec<BundleSpec>,
313    pub launch: LaunchSpec,
314    /// Where the profile came from: `builtin` or a file path.
315    #[serde(skip_deserializing)]
316    pub origin: String,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize, Default)]
320#[serde(default, rename_all = "kebab-case")]
321pub struct RuntimeModels {
322    /// `ollama` | `publisher-repo` | `hf-cache`
323    pub layout: String,
324    /// Ordered model directories (`env:VAR` entries are honored first).
325    pub dirs: Vec<String>,
326}
327
328/// A declarative description of one local inference runtime.
329#[derive(Debug, Clone, Serialize, Deserialize, Default)]
330#[serde(default, rename_all = "kebab-case")]
331pub struct RuntimeProfile {
332    pub id: String,
333    pub name: String,
334    pub aliases: Vec<String>,
335    pub homepage: Option<String>,
336    pub binaries: Vec<String>,
337    pub version: VersionProbe,
338    /// Default ports, used to recognize a provider's base URL.
339    pub ports: Vec<u16>,
340    /// Provider names harness configs use for this runtime.
341    pub provider_names: Vec<String>,
342    /// Command template to fetch a model (`{model}`, `{repo}`, `{revision}`).
343    pub pull: Option<String>,
344    pub serve: Option<String>,
345    pub models: RuntimeModels,
346    pub install: Vec<InstallMethod>,
347    /// Models `hlock localize` may pick.
348    pub catalog: Vec<CatalogModel>,
349    #[serde(skip_deserializing)]
350    pub origin: String,
351}
352
353impl HarnessProfile {
354    pub fn matches(&self, name: &str) -> bool {
355        let n = name.to_ascii_lowercase();
356        self.id == n || self.aliases.iter().any(|a| a.to_ascii_lowercase() == n)
357    }
358
359    /// The live config root: the relocation variable if set, else the default.
360    pub fn config_root(&self, ctx: &Ctx) -> PathBuf {
361        let cr = &self.config_root;
362        if let Some(var) = &cr.env {
363            if let Some(v) = ctx.var(var) {
364                let base = ctx.expand(v, None);
365                return match &cr.suffix {
366                    Some(sfx) => base.join(sfx),
367                    None => base,
368                };
369            }
370        }
371        ctx.expand(&cr.default, None)
372    }
373
374    /// Whether `config_root` is currently relocated by its variable.
375    pub fn root_relocated(&self, ctx: &Ctx) -> bool {
376        self.config_root.env.as_deref().and_then(|v| ctx.var(v)).is_some()
377    }
378
379    /// Resolve a named file to a path for the live environment.
380    pub fn file_path(&self, id: &str, ctx: &Ctx) -> Option<PathBuf> {
381        let f = self.files.get(id)?;
382        let root = self.config_root(ctx);
383        let tpl = match (&f.isolated, self.root_relocated(ctx)) {
384            (Some(iso), true) => iso,
385            _ => &f.path,
386        };
387        Some(ctx.expand(tpl, Some(&root)))
388    }
389
390    /// Environment that relocates this harness's config root to `dir`, used by
391    /// isolated sessions. `None` when the harness has no relocation variable.
392    pub fn isolation_env(&self, dir: &Path) -> Option<(String, PathBuf)> {
393        let var = self.config_root.env.clone()?;
394        let value = match &self.config_root.suffix {
395            // XDG-style: the variable names the parent of the root.
396            Some(_) => dir.parent().map(Path::to_path_buf).unwrap_or_else(|| dir.to_path_buf()),
397            None => dir.to_path_buf(),
398        };
399        Some((var, value))
400    }
401
402    /// True when the current process runs inside this harness.
403    pub fn is_active(&self, ctx: &Ctx) -> bool {
404        self.active_env.iter().any(|v| ctx.var(v).is_some())
405    }
406}
407
408impl RuntimeProfile {
409    pub fn matches(&self, name: &str) -> bool {
410        let n = name.to_ascii_lowercase();
411        self.id == n || self.aliases.iter().any(|a| a.to_ascii_lowercase() == n)
412    }
413
414    /// The first model directory that exists (falls back to the first candidate).
415    pub fn models_dir(&self, ctx: &Ctx) -> Option<PathBuf> {
416        let mut first = None;
417        for d in &self.models.dirs {
418            let p = match d.strip_prefix("env:") {
419                Some(var) => match ctx.var(var) {
420                    Some(v) => ctx.expand(v, None),
421                    None => continue,
422                },
423                None => ctx.expand(d, None),
424            };
425            if p.is_dir() {
426                return Some(p);
427            }
428            first.get_or_insert(p);
429        }
430        first
431    }
432}
433
434// --------------------------------------------------------------------------- //
435// Registry
436// --------------------------------------------------------------------------- //
437
438/// All known profiles: the built-ins, overridden or extended by user profile dirs.
439#[derive(Debug, Clone, Default)]
440pub struct Registry {
441    pub harnesses: Vec<HarnessProfile>,
442    pub runtimes: Vec<RuntimeProfile>,
443}
444
445/// Profile directories, lowest precedence first: `~/.config/hlock/profiles`,
446/// each entry of `HLOCK_PROFILE_PATH`, then `./.hlock/profiles`. Each holds
447/// `harnesses/*.toml` and `runtimes/*.toml`; a later profile with the same `id`
448/// replaces an earlier one.
449pub fn profile_dirs(ctx: &Ctx) -> Vec<PathBuf> {
450    let mut dirs = vec![ctx.expand("~/.config/hlock/profiles", None)];
451    if let Some(p) = ctx.var("HLOCK_PROFILE_PATH") {
452        dirs.extend(std::env::split_paths(p));
453    }
454    dirs.push(ctx.cwd.join(".hlock/profiles"));
455    dirs
456}
457
458pub fn parse_harness(text: &str, origin: &str) -> Result<HarnessProfile> {
459    let mut p: HarnessProfile =
460        toml::from_str(text).map_err(|e| Error::Profile(format!("invalid harness profile {origin}: {e}")))?;
461    if p.id.is_empty() {
462        return Err(Error::Profile(format!("harness profile {origin} has no id")));
463    }
464    if p.name.is_empty() {
465        p.name = p.id.clone();
466    }
467    if p.support.is_empty() {
468        p.support = "basic".into();
469    }
470    if p.kind.is_empty() {
471        p.kind = if p.run.entrypoint.is_some() || !p.run.command.is_empty() { "custom" } else { "cli" }.into();
472    }
473    p.origin = origin.to_string();
474    Ok(p)
475}
476
477pub fn parse_runtime(text: &str, origin: &str) -> Result<RuntimeProfile> {
478    let mut p: RuntimeProfile =
479        toml::from_str(text).map_err(|e| Error::Profile(format!("invalid runtime profile {origin}: {e}")))?;
480    if p.id.is_empty() {
481        return Err(Error::Profile(format!("runtime profile {origin} has no id")));
482    }
483    if p.name.is_empty() {
484        p.name = p.id.clone();
485    }
486    p.origin = origin.to_string();
487    Ok(p)
488}
489
490impl Registry {
491    /// Only the profiles compiled into this build.
492    pub fn builtin() -> Registry {
493        let harnesses = BUILTIN_HARNESSES
494            .iter()
495            .map(|(id, text)| parse_harness(text, "builtin").unwrap_or_else(|e| panic!("builtin profile {id}: {e}")))
496            .collect();
497        let runtimes = BUILTIN_RUNTIMES
498            .iter()
499            .map(|(id, text)| parse_runtime(text, "builtin").unwrap_or_else(|e| panic!("builtin profile {id}: {e}")))
500            .collect();
501        Registry { harnesses, runtimes }
502    }
503
504    /// Built-ins plus every profile found in [`profile_dirs`].
505    pub fn load(ctx: &Ctx) -> Result<Registry> {
506        let mut reg = Registry::builtin();
507        for dir in profile_dirs(ctx) {
508            reg.extend_from_dir(&dir)?;
509        }
510        Ok(reg)
511    }
512
513    /// Add (or replace by id) the profiles in `dir/harnesses` and `dir/runtimes`.
514    pub fn extend_from_dir(&mut self, dir: &Path) -> Result<()> {
515        for path in toml_files(&dir.join("harnesses")) {
516            let text = std::fs::read_to_string(&path)?;
517            let p = parse_harness(&text, &path.to_string_lossy())?;
518            self.harnesses.retain(|h| h.id != p.id);
519            self.harnesses.push(p);
520        }
521        for path in toml_files(&dir.join("runtimes")) {
522            let text = std::fs::read_to_string(&path)?;
523            let p = parse_runtime(&text, &path.to_string_lossy())?;
524            self.runtimes.retain(|r| r.id != p.id);
525            self.runtimes.push(p);
526        }
527        Ok(())
528    }
529
530    /// Built-ins, profile dirs, then the manifest's own `[harnesses.<id>]` tables.
531    pub fn load_for(ctx: &Ctx, manifest: Option<&crate::manifest::Manifest>) -> Result<Registry> {
532        let mut reg = Registry::load(ctx)?;
533        if let Some(m) = manifest {
534            reg.add_project_harnesses(m)?;
535        }
536        Ok(reg)
537    }
538
539    /// Register a manifest's `[harnesses.<id>]` tables as `custom` profiles. A
540    /// table with `framework = "<id>"` inherits that framework's packages.
541    pub fn add_project_harnesses(&mut self, m: &crate::manifest::Manifest) -> Result<()> {
542        let origin = m
543            .source_path
544            .as_ref()
545            .map(|p| p.to_string_lossy().into_owned())
546            .unwrap_or_else(|| crate::MANIFEST_PATH.to_string());
547        for (id, table) in &m.harnesses {
548            let mut v = table.clone();
549            if let Some(obj) = v.as_object_mut() {
550                obj.entry("id").or_insert_with(|| serde_json::json!(id));
551                // `entrypoint`, `command`, `python` and `env` may sit at the top level.
552                let mut run = obj.remove("run").and_then(|r| r.as_object().cloned()).unwrap_or_default();
553                for key in ["entrypoint", "command", "python", "env"] {
554                    if let Some(val) = obj.remove(key) {
555                        run.insert(key.to_string(), val);
556                    }
557                }
558                obj.insert("run".into(), serde_json::Value::Object(run));
559            }
560            let mut p: HarnessProfile = serde_json::from_value(v)
561                .map_err(|e| Error::Profile(format!("invalid [harnesses.{id}] in {origin}: {e}")))?;
562            if p.name.is_empty() {
563                p.name = id.clone();
564            }
565            if p.kind.is_empty() {
566                p.kind = "custom".into();
567            }
568            if p.support.is_empty() {
569                p.support = "basic".into();
570            }
571            if let Some(fw) = &p.framework {
572                let base = self
573                    .harness(fw)
574                    .filter(|h| h.kind == "framework")
575                    .ok_or_else(|| Error::Profile(format!("[harnesses.{id}] framework {fw:?} is not a known framework")))?;
576                for pkg in &base.packages {
577                    if !p.packages.contains(pkg) {
578                        p.packages.push(pkg.clone());
579                    }
580                }
581                if p.homepage.is_none() {
582                    p.homepage = base.homepage.clone();
583                }
584            }
585            if p.kind == "custom" && p.run.entrypoint.is_none() && p.run.command.is_empty() {
586                return Err(Error::Profile(format!(
587                    "[harnesses.{id}] needs an `entrypoint` (python module:callable) or a `command`"
588                )));
589            }
590            p.origin = origin.clone();
591            self.harnesses.retain(|h| h.id != p.id);
592            self.harnesses.push(p);
593        }
594        Ok(())
595    }
596
597    pub fn harness(&self, name: &str) -> Option<&HarnessProfile> {
598        self.harnesses.iter().find(|h| h.matches(name))
599    }
600
601    pub fn runtime(&self, name: &str) -> Option<&RuntimeProfile> {
602        self.runtimes.iter().find(|r| r.matches(name))
603    }
604
605    /// Look a harness up by id or alias, with a helpful error listing what exists.
606    pub fn require_harness(&self, name: &str) -> Result<&HarnessProfile> {
607        self.harness(name).ok_or_else(|| {
608            let known: Vec<&str> = self.harnesses.iter().map(|h| h.id.as_str()).collect();
609            Error::Profile(format!("unknown harness {name:?} (known: {})", known.join(", ")))
610        })
611    }
612
613    /// The harness this process is running inside, if any.
614    pub fn active(&self, ctx: &Ctx) -> Option<&HarnessProfile> {
615        self.harnesses.iter().find(|h| h.is_active(ctx))
616    }
617
618    /// Pick the harness a command should target, in precedence order: an explicit
619    /// name, `HLOCK_HARNESS`, the manifest's `[target] harness`, the harness this
620    /// process runs inside, then the only installed harness.
621    pub fn select(&self, explicit: Option<&str>, manifest_target: Option<&str>, ctx: &Ctx) -> Result<Selection> {
622        let named = explicit
623            .map(|n| (n.to_string(), "--harness"))
624            .or_else(|| ctx.var("HLOCK_HARNESS").map(|n| (n.to_string(), "HLOCK_HARNESS")))
625            .or_else(|| manifest_target.map(|n| (n.to_string(), "harness.toml [target]")));
626        if let Some((name, why)) = named {
627            let p = self.require_harness(&name)?;
628            return Ok(Selection { id: p.id.clone(), reason: why.to_string() });
629        }
630        if let Some(p) = self.active(ctx) {
631            return Ok(Selection { id: p.id.clone(), reason: "running inside it".into() });
632        }
633        let installed: Vec<&HarnessProfile> = self
634            .harnesses
635            .iter()
636            .filter(|h| h.kind == "cli" && h.binaries.iter().any(|b| ctx.which(b).is_some()))
637            .collect();
638        match installed.as_slice() {
639            [one] => Ok(Selection { id: one.id.clone(), reason: "the only installed harness".into() }),
640            [] => Err(Error::Profile("no supported harness found on PATH".into())),
641            many => Err(Error::Profile(format!(
642                "several harnesses are installed ({}); pick one with --harness",
643                many.iter().map(|h| h.id.as_str()).collect::<Vec<_>>().join(", ")
644            ))),
645        }
646    }
647}
648
649/// The outcome of [`Registry::select`]: which harness, and why it was chosen.
650#[derive(Debug, Clone, Serialize)]
651pub struct Selection {
652    pub id: String,
653    pub reason: String,
654}
655
656fn toml_files(dir: &Path) -> Vec<PathBuf> {
657    let mut out: Vec<PathBuf> = std::fs::read_dir(dir)
658        .map(|rd| {
659            rd.flatten()
660                .map(|e| e.path())
661                .filter(|p| p.extension().is_some_and(|x| x == "toml"))
662                .collect()
663        })
664        .unwrap_or_default();
665    out.sort();
666    out
667}
668
669// --------------------------------------------------------------------------- //
670// Probing an installed harness / runtime
671// --------------------------------------------------------------------------- //
672
673/// What's installed on this machine for one profile.
674#[derive(Debug, Clone, Serialize, Default)]
675pub struct Probe {
676    pub id: String,
677    pub installed: bool,
678    pub binary: Option<String>,
679    pub version: Option<String>,
680    /// Detected install method (`npm`, `brew-cask`, `script`, …).
681    pub method: Option<String>,
682    /// Reproducible source spec, e.g. `npm:@openai/codex@0.51.0`.
683    pub source: Option<String>,
684    pub config_root: Option<String>,
685    pub active: bool,
686    /// Installed versions of the profile's `packages` (code harnesses).
687    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
688    pub packages: BTreeMap<String, String>,
689}
690
691const VERSION_TIMEOUT: Duration = Duration::from_secs(8);
692
693pub fn probe_harness(p: &HarnessProfile, ctx: &Ctx) -> Probe {
694    if p.kind != "cli" {
695        return probe_code_harness(p, ctx);
696    }
697    let mut out = probe_binary(&p.id, &p.binaries, &p.version, &p.install, ctx);
698    out.config_root = Some(p.config_root(ctx).to_string_lossy().into_owned());
699    out.active = p.is_active(ctx);
700    out
701}
702
703/// Frameworks and custom harnesses: "installed" means their packages import
704/// (or a custom command resolves), and the version is the first package's.
705fn probe_code_harness(p: &HarnessProfile, ctx: &Ctx) -> Probe {
706    let mut out = Probe { id: p.id.clone(), active: p.is_active(ctx), ..Default::default() };
707    out.packages = python_package_versions(&p.packages, p.run.python.as_deref(), ctx);
708    let first = p.packages.iter().find_map(|pkg| out.packages.get(pkg).map(|v| (pkg, v)));
709    if let Some((pkg, v)) = first {
710        out.version = Some(v.clone());
711        out.method = Some("pip".into());
712        out.source = Some(format!("pypi:{}=={v}", pkg.trim_start_matches("pypi:")));
713    }
714    out.installed = match (p.kind.as_str(), p.run.command.first()) {
715        ("custom", Some(cmd)) => {
716            out.binary = ctx.which(cmd).or_else(|| Some(ctx.expand(cmd, None)).filter(|x| x.is_file())).map(|b| b.to_string_lossy().into_owned());
717            out.binary.is_some()
718        }
719        ("custom", None) => p.run.entrypoint.is_some(),
720        _ => first.is_some(),
721    };
722    out
723}
724
725/// The Python interpreter for code harnesses: an explicit one, `HL_PYTHON`, then `python3`.
726pub fn python_for(explicit: Option<&str>, ctx: &Ctx) -> Option<PathBuf> {
727    let name = explicit.map(str::to_string).or_else(|| ctx.var("HL_PYTHON").map(str::to_string)).unwrap_or_else(|| "python3".into());
728    ctx.which(&name)
729}
730
731/// Installed versions of `pypi:` packages, read with one interpreter call.
732pub fn python_package_versions(packages: &[String], python: Option<&str>, ctx: &Ctx) -> BTreeMap<String, String> {
733    let names: Vec<&str> = packages.iter().filter_map(|p| p.strip_prefix("pypi:")).collect();
734    let mut out = BTreeMap::new();
735    if names.is_empty() {
736        return out;
737    }
738    let Some(py) = python_for(python, ctx) else { return out };
739    let script = format!(
740        "import json, importlib.metadata as m\nout = {{}}\nfor n in {names:?}:\n    try: out[n] = m.version(n)\n    except Exception: pass\nprint(json.dumps(out))"
741    );
742    let Some(text) = run_capture(&py, &["-c".to_string(), script], ctx, VERSION_TIMEOUT) else { return out };
743    let Some(line) = text.lines().find(|l| l.trim_start().starts_with('{')) else { return out };
744    if let Ok(serde_json::Value::Object(map)) = serde_json::from_str::<serde_json::Value>(line) {
745        for (k, v) in map {
746            if let Some(v) = v.as_str() {
747                out.insert(format!("pypi:{k}"), v.to_string());
748            }
749        }
750    }
751    out
752}
753
754pub fn probe_runtime(p: &RuntimeProfile, ctx: &Ctx) -> Probe {
755    probe_binary(&p.id, &p.binaries, &p.version, &p.install, ctx)
756}
757
758fn probe_binary(id: &str, binaries: &[String], version: &VersionProbe, install: &[InstallMethod], ctx: &Ctx) -> Probe {
759    let mut out = Probe { id: id.to_string(), ..Default::default() };
760    let Some(bin) = binaries.iter().find_map(|b| ctx.which(b)) else {
761        return out;
762    };
763    out.installed = true;
764    out.binary = Some(bin.to_string_lossy().into_owned());
765    if !version.args.is_empty() {
766        out.version = run_capture(&bin, &version.args, ctx, VERSION_TIMEOUT).and_then(|t| extract_version(&t));
767    }
768    let real = std::fs::canonicalize(&bin).unwrap_or(bin.clone());
769    let (method, package) = detect_install(&real, install);
770    out.source = method.as_deref().map(|m| source_spec(m, package.as_deref(), out.version.as_deref()));
771    out.method = method;
772    out
773}
774
775/// Format a reproducible source spec for an install method.
776pub fn source_spec(method: &str, package: Option<&str>, version: Option<&str>) -> String {
777    match (method, package, version) {
778        ("pip", Some(p), Some(v)) => format!("pypi:{p}=={v}"),
779        ("uv-tool", Some(p), Some(v)) => format!("pypi:{p}=={v}"),
780        (m, Some(p), Some(v)) => format!("{m}:{p}@{v}"),
781        (m, Some(p), None) => format!("{m}:{p}"),
782        (m, None, Some(v)) => format!("{m}@{v}"),
783        (m, None, None) => m.to_string(),
784    }
785}
786
787/// Infer how a binary was installed from its real path.
788pub fn detect_install(real: &Path, install: &[InstallMethod]) -> (Option<String>, Option<String>) {
789    let s = real.to_string_lossy().replace('\\', "/");
790    if s.contains("/node_modules/") {
791        let pkg = npm_package_name(real).or_else(|| find_method(install, "npm").and_then(|m| m.package.clone()));
792        return (Some("npm".into()), pkg);
793    }
794    if let Some(rest) = s.split("/Caskroom/").nth(1) {
795        return (Some("brew-cask".into()), rest.split('/').next().map(str::to_string));
796    }
797    if let Some(rest) = s.split("/Cellar/").nth(1) {
798        return (Some("brew".into()), rest.split('/').next().map(str::to_string));
799    }
800    if s.contains("/uv/tools/") {
801        let pkg = s.split("/uv/tools/").nth(1).and_then(|r| r.split('/').next()).map(str::to_string);
802        return (Some("uv-tool".into()), pkg);
803    }
804    if s.contains("/site-packages/") || s.contains("/pipx/venvs/") {
805        return (Some("pip".into()), find_method(install, "pip").and_then(|m| m.package.clone()));
806    }
807    for m in install {
808        if m.path_hints.iter().any(|h| s.contains(h.as_str())) {
809            return (Some(m.method.clone()), m.package.clone());
810        }
811    }
812    (None, None)
813}
814
815fn find_method<'a>(install: &'a [InstallMethod], method: &str) -> Option<&'a InstallMethod> {
816    install.iter().find(|m| m.method == method)
817}
818
819/// The `name` of the nearest `package.json` above a file inside `node_modules`.
820fn npm_package_name(file: &Path) -> Option<String> {
821    let mut dir = file.parent();
822    while let Some(d) = dir {
823        let pj = d.join("package.json");
824        if pj.is_file() {
825            let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&pj).ok()?).ok()?;
826            if let Some(name) = v.get("name").and_then(|n| n.as_str()) {
827                return Some(name.to_string());
828            }
829        }
830        if d.file_name().is_some_and(|n| n == "node_modules") {
831            break;
832        }
833        dir = d.parent();
834    }
835    None
836}
837
838/// Run a command with a timeout, returning stdout+stderr on success.
839pub fn run_capture(bin: &Path, args: &[String], ctx: &Ctx, timeout: Duration) -> Option<String> {
840    let mut child = Command::new(bin)
841        .args(args)
842        .current_dir(&ctx.cwd)
843        .env_clear()
844        .envs(&ctx.env)
845        .stdin(Stdio::null())
846        .stdout(Stdio::piped())
847        .stderr(Stdio::piped())
848        .spawn()
849        .ok()?;
850    let start = Instant::now();
851    loop {
852        match child.try_wait() {
853            Ok(Some(_)) => break,
854            Ok(None) if start.elapsed() > timeout => {
855                let _ = child.kill();
856                let _ = child.wait();
857                return None;
858            }
859            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
860            Err(_) => return None,
861        }
862    }
863    let out = child.wait_with_output().ok()?;
864    let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
865    text.push('\n');
866    text.push_str(&String::from_utf8_lossy(&out.stderr));
867    Some(text)
868}
869
870/// The first dotted version number in `text`, e.g. `2.1.4` or `2026.05.28-a70ca7c`.
871/// ANSI escape sequences are skipped.
872pub fn extract_version(text: &str) -> Option<String> {
873    let clean = strip_ansi(text);
874    let b = clean.as_bytes();
875    let mut i = 0;
876    while i < b.len() {
877        let boundary = i == 0
878            || !(b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'.')
879            || (matches!(b[i - 1], b'v' | b'V') && (i == 1 || !b[i - 2].is_ascii_alphanumeric()));
880        if b[i].is_ascii_digit() && boundary {
881            let start = i;
882            let mut dots = 0;
883            while i < b.len() && (b[i].is_ascii_digit() || (b[i] == b'.' && i + 1 < b.len() && b[i + 1].is_ascii_digit())) {
884                if b[i] == b'.' {
885                    dots += 1;
886                }
887                i += 1;
888            }
889            if dots >= 1 {
890                // optional pre-release / build suffix
891                if i < b.len() && (b[i] == b'-' || b[i] == b'+') && i + 1 < b.len() && b[i + 1].is_ascii_alphanumeric() {
892                    i += 1;
893                    while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'.') {
894                        i += 1;
895                    }
896                }
897                return Some(clean[start..i].trim_end_matches('.').to_string());
898            }
899        }
900        i += 1;
901    }
902    None
903}
904
905fn strip_ansi(s: &str) -> String {
906    let mut out = String::with_capacity(s.len());
907    let mut chars = s.chars().peekable();
908    while let Some(c) = chars.next() {
909        if c == '\u{1b}' {
910            if chars.peek() == Some(&'[') {
911                chars.next();
912                for n in chars.by_ref() {
913                    if n.is_ascii_alphabetic() {
914                        break;
915                    }
916                }
917            }
918            continue;
919        }
920        out.push(c);
921    }
922    out
923}
924
925#[cfg(test)]
926mod tests {
927    use super::*;
928
929    #[test]
930    fn builtins_parse() {
931        let r = Registry::builtin();
932        assert!(r.harnesses.len() >= 10);
933        for id in ["claude-code", "codex", "pi", "opencode", "hermes", "cursor-agent"] {
934            let h = r.harness(id).unwrap();
935            assert_eq!(h.support, "full", "{id}");
936            for (fid, f) in &h.files {
937                assert!(["json", "jsonc", "toml", "yaml"].contains(&f.format.as_str()), "{id}.{fid}");
938                assert!(["whole", "pointers", "record"].contains(&f.restore.as_str()), "{id}.{fid}");
939            }
940            // every `<file>#<pointer>` reference names a declared file
941            let refs = h.model.default.iter().chain(&h.model.small).chain(&h.model.provider).chain(&h.mcp.sources);
942            for r in refs {
943                if let Some((file, _)) = r.split_once('#') {
944                    assert!(h.files.contains_key(file), "{id}: {r}");
945                }
946            }
947        }
948        for fw in ["pydantic-ai", "deepagents", "langgraph", "openai-agents", "claude-agent-sdk"] {
949            let h = r.harness(fw).unwrap();
950            assert_eq!(h.kind, "framework", "{fw}");
951            assert!(h.packages.iter().all(|p| p.starts_with("pypi:")), "{fw}");
952        }
953        assert!(r.harnesses.iter().filter(|h| h.kind == "cli").count() >= 10);
954        assert!(r.runtime("ollama").is_some());
955        assert_eq!(r.harness("claude").unwrap().id, "claude-code");
956        assert_eq!(r.runtime("lms").unwrap().id, "lmstudio");
957    }
958
959    #[test]
960    fn versions() {
961        assert_eq!(extract_version("2.1.285 (Claude Code)").as_deref(), Some("2.1.285"));
962        assert_eq!(extract_version("Hermes Agent v0.20.0 (2026.8.3)").as_deref(), Some("0.20.0"));
963        assert_eq!(extract_version("2026.05.28-a70ca7c").as_deref(), Some("2026.05.28-a70ca7c"));
964        assert_eq!(extract_version("Warning: client version is 0.35.1").as_deref(), Some("0.35.1"));
965        assert_eq!(extract_version("\u{1b}[38;5;166m art \u{1b}[0m\nCLI commit: 1.2.3").as_deref(), Some("1.2.3"));
966        assert_eq!(extract_version("no version"), None);
967    }
968
969    #[test]
970    fn install_detection() {
971        let install = vec![InstallMethod {
972            method: "script".into(),
973            path_hints: vec!["/.local/share/cursor-agent/".into()],
974            ..Default::default()
975        }];
976        let (m, p) = detect_install(Path::new("/opt/homebrew/Caskroom/claude-code/2.1.285/claude"), &[]);
977        assert_eq!((m.as_deref(), p.as_deref()), (Some("brew-cask"), Some("claude-code")));
978        let (m, p) = detect_install(Path::new("/opt/homebrew/Cellar/opencode/1.18.18/bin/opencode"), &[]);
979        assert_eq!((m.as_deref(), p.as_deref()), (Some("brew"), Some("opencode")));
980        let (m, _) = detect_install(Path::new("/home/u/.local/share/cursor-agent/versions/x/cursor-agent"), &install);
981        assert_eq!(m.as_deref(), Some("script"));
982        assert_eq!(source_spec("npm", Some("@openai/codex"), Some("0.5.0")), "npm:@openai/codex@0.5.0");
983        assert_eq!(source_spec("pip", Some("vllm"), Some("0.11.2")), "pypi:vllm==0.11.2");
984    }
985
986    fn ctx_with(env: &[(&str, &str)]) -> Ctx {
987        Ctx {
988            home: PathBuf::from("/home/u"),
989            cwd: PathBuf::from("/work"),
990            env: env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
991            path: vec![],
992        }
993    }
994
995    #[test]
996    fn config_roots_and_isolation() {
997        let r = Registry::builtin();
998        let claude = r.harness("claude-code").unwrap();
999        let ctx = ctx_with(&[]);
1000        assert_eq!(claude.config_root(&ctx), PathBuf::from("/home/u/.claude"));
1001        assert_eq!(claude.file_path("state", &ctx).unwrap(), PathBuf::from("/home/u/.claude.json"));
1002        assert_eq!(claude.file_path("project-mcp", &ctx).unwrap(), PathBuf::from("/work/.mcp.json"));
1003        let iso = ctx_with(&[("CLAUDE_CONFIG_DIR", "/tmp/env/claude")]);
1004        assert_eq!(claude.file_path("state", &iso).unwrap(), PathBuf::from("/tmp/env/claude/.claude.json"));
1005
1006        let oc = r.harness("opencode").unwrap();
1007        let xdg = ctx_with(&[("XDG_CONFIG_HOME", "/tmp/env/xdg")]);
1008        assert_eq!(oc.config_root(&xdg), PathBuf::from("/tmp/env/xdg/opencode"));
1009        let (var, val) = oc.isolation_env(Path::new("/tmp/env/xdg/opencode")).unwrap();
1010        assert_eq!((var.as_str(), val), ("XDG_CONFIG_HOME", PathBuf::from("/tmp/env/xdg")));
1011    }
1012
1013    #[test]
1014    fn selection_precedence() {
1015        let r = Registry::builtin();
1016        let ctx = ctx_with(&[("CLAUDECODE", "1"), ("HLOCK_HARNESS", "pi")]);
1017        assert_eq!(r.select(Some("codex"), Some("opencode"), &ctx).unwrap().id, "codex");
1018        assert_eq!(r.select(None, Some("opencode"), &ctx).unwrap().id, "pi");
1019        let ctx = ctx_with(&[("CLAUDECODE", "1")]);
1020        assert_eq!(r.select(None, Some("opencode"), &ctx).unwrap().id, "opencode");
1021        let s = r.select(None, None, &ctx).unwrap();
1022        assert_eq!((s.id.as_str(), s.reason.as_str()), ("claude-code", "running inside it"));
1023        assert!(r.select(Some("nope"), None, &ctx).unwrap_err().to_string().contains("known:"));
1024    }
1025
1026    #[test]
1027    fn project_harnesses() {
1028        let m = crate::manifest::Manifest::from_str(
1029            r#"
1030[target]
1031harness = "triage"
1032
1033[harnesses.triage]
1034framework = "pydantic-ai"
1035entrypoint = "triage.agent:run"
1036
1037[harnesses.loop]
1038command = ["./bin/agent", "{prompt}"]
1039packages = ["pypi:httpx"]
1040"#,
1041        )
1042        .unwrap();
1043        let mut r = Registry::builtin();
1044        r.add_project_harnesses(&m).unwrap();
1045        let t = r.harness("triage").unwrap();
1046        assert_eq!(t.kind, "custom");
1047        assert_eq!(t.run.entrypoint.as_deref(), Some("triage.agent:run"));
1048        assert!(t.packages.contains(&"pypi:pydantic-ai-slim".to_string()));
1049        assert_eq!(r.harness("loop").unwrap().run.command[0], "./bin/agent");
1050        assert_eq!(r.select(None, m.target_harness().as_deref(), &ctx_with(&[])).unwrap().id, "triage");
1051
1052        let bad = crate::manifest::Manifest::from_str("[harnesses.x]\nframework = \"nope\"\nentrypoint = \"a:b\"\n").unwrap();
1053        assert!(Registry::builtin().add_project_harnesses(&bad).unwrap_err().to_string().contains("not a known framework"));
1054        let bare = crate::manifest::Manifest::from_str("[harnesses.x]\nframework = \"langgraph\"\n").unwrap();
1055        assert!(Registry::builtin().add_project_harnesses(&bare).unwrap_err().to_string().contains("entrypoint"));
1056    }
1057
1058    #[test]
1059    fn user_profiles_override_and_extend() {
1060        let dir = std::env::temp_dir().join(format!("hlock-prof-{}", std::process::id()));
1061        std::fs::create_dir_all(dir.join("harnesses")).unwrap();
1062        std::fs::write(dir.join("harnesses/my.toml"), "id = \"my-agent\"\nbinaries = [\"my-agent\"]\n").unwrap();
1063        std::fs::write(dir.join("harnesses/pi.toml"), "id = \"pi\"\nname = \"Pi (fork)\"\n").unwrap();
1064        let mut r = Registry::builtin();
1065        r.extend_from_dir(&dir).unwrap();
1066        assert_eq!(r.harness("my-agent").unwrap().support, "basic");
1067        assert_eq!(r.harness("pi").unwrap().name, "Pi (fork)");
1068        assert_eq!(r.harnesses.iter().filter(|h| h.id == "pi").count(), 1);
1069        let _ = std::fs::remove_dir_all(&dir);
1070    }
1071}