openlatch-client 0.5.8

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Pure parsing and selection for independently versioned wire families.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

pub use crate::generated::contract_catalog::{SELECTED_HEADER, SUPPORT_HEADER};

pub const POLICY_BUNDLE_FAMILY: &str = "policy_bundle";
pub const DECISION_EVENT_FAMILY: &str = "decision_event";
pub const COMPATIBILITY_PROBLEM_TYPE: &str =
    "https://openlatch.ai/problems/protocol-compatibility-unavailable";
pub const COMPATIBILITY_FILE: &str = "compatibility.json";

static COMPATIBILITY_WRITE_LOCK: Mutex<()> = Mutex::new(());

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct VersionRange {
    pub oldest: u32,
    pub newest: u32,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
pub struct CompatibilityState {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub selections: BTreeMap<String, CompatibilitySelection>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub diagnostics: BTreeMap<String, CompatibilityDiagnostic>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CompatibilitySelection {
    pub version: u32,
    pub selected_at: String,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CompatibilityDiagnostic {
    pub family: String,
    pub client_range: VersionRange,
    pub platform_range: Option<VersionRange>,
    pub last_selection: Option<u32>,
    pub observed_at: String,
    pub detail: String,
}

#[derive(Debug, thiserror::Error)]
pub enum CompatibilityStoreError {
    #[error("compatibility sidecar I/O error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("compatibility sidecar is malformed: {0}")]
    Malformed(String),
}

pub fn compatibility_path(base: &Path) -> PathBuf {
    base.join("policy").join(COMPATIBILITY_FILE)
}

pub fn read_compatibility(base: &Path) -> Result<CompatibilityState, CompatibilityStoreError> {
    let path = compatibility_path(base);
    match std::fs::read(&path) {
        Ok(raw) => serde_json::from_slice(&raw)
            .map_err(|error| CompatibilityStoreError::Malformed(error.to_string())),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            Ok(CompatibilityState::default())
        }
        Err(source) => Err(CompatibilityStoreError::Io { path, source }),
    }
}

pub fn record_selection(
    base: &Path,
    family: &str,
    version: u32,
) -> Result<(), CompatibilityStoreError> {
    update_compatibility(base, |state| {
        state.selections.insert(
            family.to_string(),
            CompatibilitySelection {
                version,
                selected_at: now_rfc3339(),
            },
        );
        state.diagnostics.remove(family);
    })
}

pub fn record_diagnostic(
    base: &Path,
    mut diagnostic: CompatibilityDiagnostic,
) -> Result<(), CompatibilityStoreError> {
    update_compatibility(base, |state| {
        diagnostic.last_selection = state.selections.get(&diagnostic.family).map(|s| s.version);
        state
            .diagnostics
            .insert(diagnostic.family.clone(), diagnostic);
    })
}

fn update_compatibility(
    base: &Path,
    update: impl FnOnce(&mut CompatibilityState),
) -> Result<(), CompatibilityStoreError> {
    let _guard = COMPATIBILITY_WRITE_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let mut state = read_compatibility(base)?;
    update(&mut state);
    let path = compatibility_path(base);
    let dir = path.parent().expect("compatibility sidecar has parent");
    std::fs::create_dir_all(dir).map_err(|source| CompatibilityStoreError::Io {
        path: dir.to_path_buf(),
        source,
    })?;
    let bytes = serde_json::to_vec_pretty(&state)
        .map_err(|error| CompatibilityStoreError::Malformed(error.to_string()))?;
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, bytes).map_err(|source| CompatibilityStoreError::Io {
        path: tmp.clone(),
        source,
    })?;
    std::fs::rename(&tmp, &path).map_err(|source| CompatibilityStoreError::Io { path, source })
}

fn now_rfc3339() -> String {
    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
}

impl VersionRange {
    pub const fn new(oldest: u32, newest: u32) -> Option<Self> {
        if oldest == 0 || newest == 0 || oldest > newest {
            None
        } else {
            Some(Self { oldest, newest })
        }
    }

    pub fn select(self, peer: Self) -> Option<u32> {
        let oldest = self.oldest.max(peer.oldest);
        let newest = self.newest.min(peer.newest);
        (oldest <= newest).then_some(newest)
    }
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum MapError {
    #[error("contract map is empty")]
    Empty,
    #[error("malformed contract member: {0}")]
    Malformed(String),
    #[error("duplicate contract family: {0}")]
    Duplicate(String),
    #[error("contract versions must be positive and ranges must not be reversed")]
    InvalidRange,
}

pub fn supported_ranges() -> BTreeMap<String, VersionRange> {
    let mut result: BTreeMap<String, VersionRange> = BTreeMap::new();
    for entry in crate::generated::contract_catalog::CONTRACT_VERSIONS {
        result
            .entry(entry.family.to_string())
            .and_modify(|range| {
                range.oldest = range.oldest.min(entry.version);
                range.newest = range.newest.max(entry.version);
            })
            .or_insert(VersionRange {
                oldest: entry.version,
                newest: entry.version,
            });
    }
    result
}

pub fn support_header_value() -> String {
    supported_ranges()
        .into_iter()
        .map(|(family, range)| format!("{family}={}-{}", range.oldest, range.newest))
        .collect::<Vec<_>>()
        .join(",")
}

pub fn baseline(family: &str) -> Option<u32> {
    crate::generated::contract_catalog::CONTRACT_VERSIONS
        .iter()
        .find(|entry| entry.family == family && entry.baseline)
        .map(|entry| entry.version)
}

pub fn has_reader(family: &str, version: u32) -> bool {
    crate::generated::contract_catalog::CONTRACT_VERSIONS
        .iter()
        .any(|entry| entry.family == family && entry.version == version && !entry.reader.is_empty())
}

pub fn has_writer(family: &str, version: u32) -> bool {
    crate::generated::contract_catalog::CONTRACT_VERSIONS
        .iter()
        .any(|entry| entry.family == family && entry.version == version && !entry.writer.is_empty())
}

pub fn parse_ranges(raw: &str) -> Result<BTreeMap<String, VersionRange>, MapError> {
    parse_map(raw, |value| {
        let (oldest, newest) = value
            .split_once('-')
            .ok_or_else(|| MapError::Malformed(value.to_string()))?;
        let oldest = parse_version(oldest)?;
        let newest = parse_version(newest)?;
        VersionRange::new(oldest, newest).ok_or(MapError::InvalidRange)
    })
}

pub fn parse_selected(raw: &str) -> Result<BTreeMap<String, u32>, MapError> {
    parse_map(raw, parse_version)
}

fn parse_map<T>(
    raw: &str,
    parse_value: impl Fn(&str) -> Result<T, MapError>,
) -> Result<BTreeMap<String, T>, MapError> {
    if raw.trim().is_empty() {
        return Err(MapError::Empty);
    }
    let mut result = BTreeMap::new();
    for member in raw.split(',') {
        let member = member.trim();
        let (family, value) = member
            .split_once('=')
            .ok_or_else(|| MapError::Malformed(member.to_string()))?;
        if !valid_family(family) || value.is_empty() || value.contains('=') {
            return Err(MapError::Malformed(member.to_string()));
        }
        if result.contains_key(family) {
            return Err(MapError::Duplicate(family.to_string()));
        }
        result.insert(family.to_string(), parse_value(value)?);
    }
    Ok(result)
}

fn parse_version(raw: &str) -> Result<u32, MapError> {
    let version = raw.parse::<u32>().map_err(|_| MapError::InvalidRange)?;
    (version > 0)
        .then_some(version)
        .ok_or(MapError::InvalidRange)
}

fn valid_family(raw: &str) -> bool {
    let mut chars = raw.chars();
    chars.next().is_some_and(|c| c.is_ascii_lowercase())
        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

/// Record-v2 facts cannot be silently erased to satisfy a v1 acknowledgement.
pub fn decision_event_can_write(envelope: &serde_json::Value, version: u32) -> bool {
    if version >= 2 {
        return true;
    }
    let Some(object) = envelope.as_object() else {
        return false;
    };
    const V2_ONLY: &[&str] = &[
        "olatomid",
        "olpolicyid",
        "oldimension",
        "ollayer",
        "olmode",
        "olenforced",
        "olresult",
        "oltier",
        "olspechash",
        "olbinding",
        "oleffects",
        "olinconclusive",
        "olrewrite",
        "olreinforce",
        "ollever",
        "olhostprompted",
        "olundecided",
        "olverdictshadow",
    ];
    !V2_ONLY.iter().any(|key| object.contains_key(*key))
        && object
            .get("olverdict")
            .and_then(serde_json::Value::as_str)
            .is_none_or(|verdict| matches!(verdict, "allow" | "deny"))
}

/// A schema-1 acknowledgement may activate only a genuinely schema-1 policy
/// representation. Merely changing `schema_version` while retaining compiled
/// artifacts or their supporting data would silently disarm that policy.
pub fn policy_bundle_can_read(document: &serde_json::Value, version: u32) -> bool {
    if version >= 2 {
        return true;
    }
    const V2_ONLY: &[&str] = &[
        "artifacts",
        "facts",
        "effect_classes",
        "directive_templates",
        "install_id",
        "client_floor",
        "meta",
    ];
    V2_ONLY.iter().all(|key| {
        document
            .get(*key)
            .is_none_or(|value| !contains_contract_facts(value))
    })
}

fn contains_contract_facts(value: &serde_json::Value) -> bool {
    match value {
        serde_json::Value::Null => false,
        serde_json::Value::Array(values) => !values.is_empty(),
        serde_json::Value::Object(values) => !values.is_empty(),
        _ => true,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn published_catalogue_deserializes_to_the_schema_generated_type() {
        let catalog: crate::generated::types::ContractCatalog =
            serde_json::from_str(include_str!("../../../schemas/contracts/catalog.json"))
                .expect("catalogue matches contract-catalog.schema.json");
        assert_eq!(catalog.families.len(), 2);
        assert!(catalog
            .families
            .iter()
            .all(|family| family.versions.len() == 2));
    }

    #[test]
    fn retained_fixtures_are_readable_by_their_local_readers() {
        for raw in [
            include_str!("../../../schemas/contracts/policy_bundle/v1.json"),
            include_str!("../../../schemas/contracts/policy_bundle/v2.json"),
        ] {
            let value = serde_json::from_str(raw).expect("policy fixture is JSON");
            crate::core::policy::project_document(value)
                .expect("retained policy fixture has a live local reader");
        }
        for raw in [
            include_str!("../../../schemas/contracts/decision_event/v1.json"),
            include_str!("../../../schemas/contracts/decision_event/v2.json"),
        ] {
            serde_json::from_str::<crate::generated::types::EventEnvelope>(raw)
                .expect("retained decision-event fixture has a live local reader");
        }
    }

    #[test]
    fn parses_ranges_and_selects_greatest_intersection() {
        let parsed = parse_ranges("policy_bundle=1-2, decision_event=2-4").unwrap();
        assert_eq!(
            parsed[POLICY_BUNDLE_FAMILY],
            VersionRange {
                oldest: 1,
                newest: 2
            }
        );
        assert_eq!(
            VersionRange::new(2, 6)
                .unwrap()
                .select(VersionRange::new(1, 5).unwrap()),
            Some(5)
        );
    }

    #[test]
    fn exact_retention_boundary_is_n_minus_four_not_n_minus_five() {
        let retained = VersionRange::new(2, 6).unwrap();
        assert_eq!(retained.select(VersionRange::new(2, 2).unwrap()), Some(2));
        assert_eq!(retained.select(VersionRange::new(1, 1).unwrap()), None);
    }

    #[test]
    fn rejects_malformed_duplicate_zero_and_reversed_ranges() {
        assert!(matches!(parse_ranges(""), Err(MapError::Empty)));
        assert!(matches!(
            parse_ranges("policy_bundle"),
            Err(MapError::Malformed(_))
        ));
        assert!(matches!(
            parse_ranges("policy_bundle=0-2"),
            Err(MapError::InvalidRange)
        ));
        assert!(matches!(
            parse_ranges("policy_bundle=2-1"),
            Err(MapError::InvalidRange)
        ));
        assert!(matches!(
            parse_ranges("policy_bundle=1-2,policy_bundle=1-2"),
            Err(MapError::Duplicate(_))
        ));
        assert!(matches!(
            parse_selected("policy_bundle=0"),
            Err(MapError::InvalidRange)
        ));
    }

    #[test]
    fn generated_support_map_contains_only_real_catalogue_history() {
        assert_eq!(
            support_header_value(),
            "decision_event=1-2,policy_bundle=1-2"
        );
        assert_eq!(baseline(POLICY_BUNDLE_FAMILY), Some(2));
        assert_eq!(baseline(DECISION_EVENT_FAMILY), Some(2));
    }

    #[test]
    fn v2_decision_facts_refuse_lossy_v1_lowering() {
        assert!(!decision_event_can_write(
            &serde_json::json!({"olverdict":"block","olresult":"blocked"}),
            1
        ));
        assert!(decision_event_can_write(
            &serde_json::json!({"olverdict":"allow"}),
            1
        ));
        assert!(decision_event_can_write(
            &serde_json::json!({"olverdict":"block","olresult":"blocked"}),
            2
        ));
    }

    #[test]
    fn compiled_policy_refuses_a_schema_one_acknowledgement() {
        assert!(!policy_bundle_can_read(
            &serde_json::json!({
                "schema_version": 1,
                "artifacts": [{"artifact_id": "would-be-lost"}]
            }),
            1
        ));
        assert!(policy_bundle_can_read(
            &serde_json::json!({"schema_version": 1, "artifacts": []}),
            1
        ));
        assert!(policy_bundle_can_read(
            &serde_json::json!({"schema_version": 2, "artifacts": [{"artifact_id": "kept"}]}),
            2
        ));
    }

    #[test]
    fn first_boot_diagnostic_and_later_selection_are_sidecar_only() {
        let dir = tempfile::tempdir().unwrap();
        record_diagnostic(
            dir.path(),
            CompatibilityDiagnostic {
                family: POLICY_BUNDLE_FAMILY.to_string(),
                client_range: VersionRange::new(1, 2).unwrap(),
                platform_range: Some(VersionRange::new(3, 4).unwrap()),
                last_selection: None,
                observed_at: now_rfc3339(),
                detail: "no intersection".to_string(),
            },
        )
        .unwrap();
        let state = read_compatibility(dir.path()).unwrap();
        assert!(state.diagnostics.contains_key(POLICY_BUNDLE_FAMILY));
        assert!(!dir.path().join("policy/bundle.json").exists());
        assert!(!dir.path().join("policy/bundle.meta.json").exists());

        record_selection(dir.path(), POLICY_BUNDLE_FAMILY, 2).unwrap();
        let state = read_compatibility(dir.path()).unwrap();
        assert_eq!(state.selections[POLICY_BUNDLE_FAMILY].version, 2);
        assert!(!state.diagnostics.contains_key(POLICY_BUNDLE_FAMILY));
    }
}