harness-lock-core 0.3.1

Core library for hlock (also published as harness-lock): manifest, lockfile, store, tuning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! The lockfile: `harness.lock`.

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};
use crate::{LOCK_VERSION, LOCKFILE_PATH};

pub const HEADER: &str = "# This file is generated by harness-lock. Do not edit by hand.";

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LLM {
    pub role: String,
    pub provider: String,
    pub model: String,
    #[serde(rename = "resolved-from")]
    pub resolved_from: Option<String>,
    #[serde(default)]
    pub params: BTreeMap<String, serde_json::Value>,
    pub fingerprint: Option<String>,
    /// Base URL the harness sends this model's requests to (pinned locks).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    /// Local inference runtime serving the model, matching a `[[runtime]]` name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime: Option<String>,
}

impl Default for LLM {
    fn default() -> Self {
        LLM {
            role: String::new(),
            provider: "reference".into(),
            model: String::new(),
            resolved_from: None,
            params: BTreeMap::new(),
            fingerprint: None,
            endpoint: None,
            runtime: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Decision {
    pub kind: String,
    pub model: Option<String>,
    pub revision: Option<String>,
    #[serde(default)]
    pub decisions: Vec<String>,
    #[serde(default)]
    pub thresholds: BTreeMap<String, f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Harness {
    pub name: String,
    pub version: Option<String>,
    pub source: Option<String>,
    pub integrity: Option<String>,
    pub adapter: Option<String>,
    pub config: Option<String>,
    pub pattern: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Tool {
    pub name: String,
    pub kind: String,
    pub source: Option<String>,
    pub integrity: Option<String>,
    #[serde(rename = "schema")]
    pub tool_schema: Option<String>,
    #[serde(default)]
    pub permissions: Vec<String>,
    /// MCP servers: `stdio`, `http`, or `sse`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transport: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Environment for the server; secret values are `${HLOCK_SECRET_…}` placeholders.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub headers: BTreeMap<String, String>,
    /// `user` or `project`: the config scope the server came from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Skill {
    pub name: String,
    pub origin: String,
    pub source: Option<String>,
    pub digest: Option<String>,
    pub registry: Option<String>,
    #[serde(rename = "provided-by")]
    pub provided_by: Option<String>,
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default)]
    pub editable: bool,
    #[serde(rename = "evidence-digest")]
    pub evidence_digest: Option<String>,
    #[serde(default)]
    pub requires: Vec<String>,
    /// `user` or `project` (pinned locks).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// Where the skill was installed, as a portable path (`{root}/skills/x`, `~/…`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// Copy of the skill next to the lock (`.hlock/vendor/…`), for skills with no fetchable source.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vendored: Option<String>,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Instructions {
    pub name: String,
    pub digest: Option<String>,
    pub scope: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vendored: Option<String>,
}

/// A harness-native component: plugin, package, extension, or marketplace (§5.3).
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct Native {
    /// Namespaced kind, e.g. `claude-code.plugin`, `pi.package`, `opencode.plugin`.
    pub kind: String,
    pub name: String,
    pub version: Option<String>,
    pub source: Option<String>,
    pub revision: Option<String>,
    pub integrity: Option<String>,
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Extra harness-specific settings (e.g. a Pi package's extension filter).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config: Option<serde_json::Value>,
}

/// A local inference runtime and the models the harness uses on it (pinned locks).
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct Runtime {
    pub name: String,
    /// `local` (this machine) or `network` (a self-hosted server on a private network).
    pub location: String,
    pub version: Option<String>,
    pub source: Option<String>,
    pub endpoint: Option<String>,
    #[serde(default)]
    pub model: Vec<RuntimeModel>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct RuntimeModel {
    pub id: String,
    /// Where the weights come from: `ollama:qwen3:8b`, `hf://org/repo`, …
    pub source: Option<String>,
    pub revision: Option<String>,
    pub digest: Option<String>,
    #[serde(rename = "size-bytes")]
    pub size_bytes: Option<u64>,
    /// Whether the weights were found in the runtime's local store at pin time.
    pub present: bool,
}

/// A harness config file captured by `hlock pin`.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct ConfigFile {
    /// The profile's file id (`settings`, `state`, …).
    pub id: String,
    pub path: String,
    pub format: String,
    /// `whole` | `pointers` | `record`
    pub restore: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pointers: Vec<String>,
    pub digest: Option<String>,
    /// Redacted copy next to the lock that `sync` restores from.
    pub vendored: Option<String>,
}

/// A secret `pin` replaced with a placeholder; `sync`/`launch` fill it from the environment.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default, rename_all = "kebab-case")]
pub struct SecretRef {
    /// The environment variable that supplies it (`HLOCK_SECRET_…`).
    pub name: String,
    pub used_by: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default, rename_all = "kebab-case")]
pub struct Policy {
    pub retries: u32,
    pub tool_timeout_seconds: Option<u64>,
    pub max_steps: u32,
    pub max_cost_usd_per_task: Option<f64>,
    pub sandbox: BTreeMap<String, serde_json::Value>,
    pub human_approval: String,
    pub risky_actions: Vec<String>,
    pub tool_allowlist: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Context {
    pub isolation: String,
    pub compaction: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default, rename_all = "kebab-case")]
pub struct Evidence {
    #[serde(alias = "task-pack")]
    pub eval_pack: Option<String>,
    #[serde(alias = "task-pack-version")]
    pub eval_pack_version: Option<String>,
    pub split: String,
    pub trials: usize,
    pub success_rate: BTreeMap<String, f64>,
    pub cost_usd_per_task: BTreeMap<String, f64>,
    pub latency_s_per_task: BTreeMap<String, f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default, rename_all = "kebab-case")]
pub struct Verify {
    pub canary_tasks: usize,
    pub min_success_rate: f64,
    pub fingerprint_tolerance: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Provenance {
    pub backend: String,
    pub run: Option<String>,
    #[serde(default)]
    pub search: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Lockfile {
    pub lock_version: i64,
    pub generated_by: String,
    pub generated_at: String,
    pub manifest_hash: Option<String>,
    #[serde(default)]
    pub stack: BTreeMap<String, serde_json::Value>,
    #[serde(default)]
    pub llm: Vec<LLM>,
    #[serde(default)]
    pub decision: Decision,
    #[serde(default)]
    pub harness: Harness,
    #[serde(default)]
    pub tool: Vec<Tool>,
    #[serde(default)]
    pub skill: Vec<Skill>,
    #[serde(default)]
    pub instructions: Vec<Instructions>,
    #[serde(default)]
    pub policy: Policy,
    #[serde(default)]
    pub context: Context,
    #[serde(default)]
    pub evidence: Evidence,
    #[serde(default)]
    pub verify: Verify,
    #[serde(default)]
    pub provenance: Provenance,
    // Pinned-lock sections (`hlock pin`, SPEC §7.8.4); empty in resolved locks.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub native: Vec<Native>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub runtime: Vec<Runtime>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub config: Vec<ConfigFile>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secret: Vec<SecretRef>,
    /// Tune-lock-only fields (see §5.9 / `harness.tune.lock`).
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "base-lock")]
    pub base_lock: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tune: Option<serde_json::Value>,
    /// What `hlock localize` replaced and how it chose (localized locks only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub localize: Option<serde_json::Value>,
}

impl Default for Lockfile {
    fn default() -> Self {
        Lockfile {
            lock_version: LOCK_VERSION,
            generated_by: format!("harness-lock {}", env!("CARGO_PKG_VERSION")),
            generated_at: String::new(),
            manifest_hash: None,
            stack: BTreeMap::new(),
            llm: Vec::new(),
            decision: Decision::default(),
            harness: Harness::default(),
            tool: Vec::new(),
            skill: Vec::new(),
            instructions: Vec::new(),
            policy: Policy::default(),
            context: Context::default(),
            evidence: Evidence::default(),
            verify: Verify::default(),
            provenance: Provenance::default(),
            native: Vec::new(),
            runtime: Vec::new(),
            config: Vec::new(),
            secret: Vec::new(),
            base_lock: None,
            kind: None,
            tune: None,
            localize: None,
        }
    }
}

impl Lockfile {
    pub fn load(path: &Path) -> Result<Lockfile> {
        let text = std::fs::read_to_string(path)
            .map_err(|e| Error::Lockfile(format!("cannot read {}: {e}", path.display())))?;
        Lockfile::from_str(&text)
    }

    pub fn from_str(text: &str) -> Result<Lockfile> {
        // strip the leading comment header before parsing
        let body = text
            .lines()
            .filter(|l| !l.starts_with('#'))
            .collect::<Vec<_>>()
            .join("\n");
        let lf: Lockfile =
            toml::from_str(&body).map_err(|e| Error::Lockfile(format!("invalid harness.lock: {e}")))?;
        if lf.lock_version != LOCK_VERSION {
            return Err(Error::Lockfile(format!(
                "unsupported lock-version {} (this build supports {})",
                lf.lock_version, LOCK_VERSION
            )));
        }
        Ok(lf)
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let body = toml::to_string(self).map_err(|e| Error::Lockfile(e.to_string()))?;
        std::fs::write(path, format!("{HEADER}\n{body}"))?;
        Ok(())
    }

    /// True for locks written by `hlock pin` (no manifest, no evidence).
    pub fn is_pin(&self) -> bool {
        self.kind.as_deref() == Some("pin")
    }

    pub fn default_path(&self) -> &str {
        LOCKFILE_PATH
    }

    /// Vector of manifest-drift violation strings (empty means clean).
    pub fn check_manifest(&self, live_hash: &str) -> Vec<String> {
        match &self.manifest_hash {
            None => vec!["lock has no manifest-hash".to_string()],
            Some(pinned) => {
                let pinned_hex = pinned.split(':').nth(1).unwrap_or(pinned);
                let live_hex = live_hash.split(':').nth(1).unwrap_or(live_hash);
                if pinned_hex == live_hex {
                    Vec::new()
                } else {
                    vec![format!(
                        "manifest drift: lock pinned {pinned:?}, live {live_hash:?}"
                    )]
                }
            }
        }
    }

    pub fn summary(&self) -> String {
        let model = self.llm.first().map(|l| l.model.as_str()).unwrap_or("?");
        let sr = self.evidence.success_rate.get("mean").unwrap_or(&f64::NAN);
        format!(
            "stack={:?} harness={} llm={} decision={} success-rate={:.2} trials={}",
            self.stack.get("name").and_then(serde_json::Value::as_str).unwrap_or("agent"),
            self.harness.name,
            model,
            self.decision.kind,
            sr,
            self.evidence.trials
        )
    }
}