openlatch-client 0.5.6

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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use std::fs;
use std::path::Path;

use jsonc_parser::cst::CstRootNode;
use jsonc_parser::ParseOptions;

use crate::error::{
    OlError, ERR_HOOK_MALFORMED_JSONC, ERR_HOOK_MALFORMED_TOML, ERR_HOOK_WRITE_FAILED,
    ERR_MODEL_RELAY_STATE_FILE,
};

pub const ERR_ATOMIC_WRITE_FAILED: &str = "OL-1910";
pub const ERR_SYMLINK_CANONICALIZE_FAILED: &str = "OL-1911";

pub fn atomic_rewrite_jsonc<F>(path: &Path, mutate: F) -> Result<(), OlError>
where
    F: FnOnce(&CstRootNode) -> Result<(), OlError>,
{
    let real_path = if path.is_symlink() || path.exists() {
        fs::canonicalize(path).map_err(|e| {
            OlError::new(
                ERR_SYMLINK_CANONICALIZE_FAILED,
                format!("Cannot resolve settings path '{}': {e}", path.display()),
            )
            .with_suggestion("Check that the symlink target exists and is accessible.")
        })?
    } else {
        path.to_path_buf()
    };

    if let Some(parent) = real_path.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            OlError::new(
                ERR_HOOK_WRITE_FAILED,
                format!("Cannot create settings directory: {e}"),
            )
        })?;
    }

    let raw_jsonc = if real_path.exists() {
        fs::read_to_string(&real_path).map_err(|e| {
            OlError::new(
                ERR_HOOK_WRITE_FAILED,
                format!("Cannot read settings file: {e}"),
            )
        })?
    } else {
        "{}".to_string()
    };

    let root = CstRootNode::parse(&raw_jsonc, &ParseOptions::default()).map_err(|e| {
        OlError::new(
            ERR_HOOK_MALFORMED_JSONC,
            format!("Cannot parse settings.json as JSONC: {e}"),
        )
        .with_suggestion("Fix the JSON syntax in your settings.json file.")
    })?;

    mutate(&root)?;

    write_replacing(&real_path, root.to_string().as_bytes())
}

/// Durably replace `real_path` with `body`: `create_new` temp file, the
/// original file's mode, rename.
///
/// Both format writers used to open their temp file with `File::create`, which
/// FOLLOWS a symlink planted at the temp path, and let it take the umask's mode
/// — so a rewrite of Cline's `providers.json`, which holds API keys at `0600`,
/// left it `0644`. One helper, [`crate::fs_secure::write_preserving_mode`], owns
/// both properties for every writer here.
fn write_replacing(real_path: &Path, body: &[u8]) -> Result<(), OlError> {
    crate::fs_secure::write_preserving_mode(real_path, body).map_err(|e| {
        OlError::new(
            ERR_ATOMIC_WRITE_FAILED,
            format!(
                "Cannot replace '{}': {e}",
                crate::core::path_compat::display_path(real_path)
            ),
        )
    })
}

/// Bounds for [`rewrite_existing_json`].
#[derive(Clone, Copy, Debug)]
pub struct RewriteLimits {
    /// The largest file this rewrite will read. Larger is refused with a code,
    /// never truncated.
    pub max_bytes: u64,
}

/// How [`rewrite_existing_json`] ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RewriteOutcome {
    /// The edit changed nothing, so nothing was written — the file's mtime and
    /// inode are untouched.
    Unchanged,
    /// The edited file replaced the original.
    Written,
    /// The file changed between our read and our rename. It keeps the other
    /// writer's bytes; the caller decides whether to try again.
    Contended,
    /// There is no file. Nothing was created.
    Absent,
}

/// Edit a JSON(C) file that belongs to somebody else — only if it exists, only
/// if the edit changes it, and never over a write that landed after our read.
///
/// The writer for a third-party agent's own state: Cline's `globalState.json`
/// and `settings/providers.json`, which a running editor saves at moments we do
/// not choose. What [`atomic_rewrite_jsonc`] does differently, and why each
/// difference matters there:
///
/// - **It never creates the file or its parent.** A file the agent has not
///   written is not ours to invent; an absent file is [`RewriteOutcome::Absent`].
/// - **It refuses a file over `limits.max_bytes`** with `OL-RELAY-STATEFILE`.
///   A truncated read would parse as a different document and the rewrite
///   would then discard everything past the cut.
/// - **It writes nothing when the edit is a no-op**, so re-applying a value
///   already there does not look like a change to anyone watching the file —
///   including our own watcher.
/// - **It compares before it renames** ([`crate::fs_secure::replace_preserving`]),
///   so an editor save between the read and the write wins.
///
/// A symlinked path is resolved and the real file is replaced; the temp file is
/// opened with `create_new`, and the original's mode is kept.
pub fn rewrite_existing_json<F>(
    path: &Path,
    limits: RewriteLimits,
    mutate: F,
) -> Result<RewriteOutcome, OlError>
where
    F: FnOnce(&CstRootNode) -> Result<(), OlError>,
{
    let real_path = match fs::canonicalize(path) {
        Ok(p) => p,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(RewriteOutcome::Absent),
        Err(e) => {
            return Err(OlError::new(
                ERR_SYMLINK_CANONICALIZE_FAILED,
                format!(
                    "Cannot resolve '{}': {e}",
                    crate::core::path_compat::display_path(path)
                ),
            ))
        }
    };
    let display = crate::core::path_compat::display_path(&real_path);
    let too_large = |size: u64| {
        OlError::new(
            ERR_MODEL_RELAY_STATE_FILE,
            format!(
                "'{display}' is {size} bytes, over the {} byte limit for an agent state file \
                 OpenLatch edits",
                limits.max_bytes
            ),
        )
    };
    let seen = match crate::fs_secure::fingerprint(&real_path) {
        Ok(fp) => fp,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(RewriteOutcome::Absent),
        Err(e) => {
            return Err(OlError::new(
                ERR_HOOK_WRITE_FAILED,
                format!("Cannot read '{display}': {e}"),
            ))
        }
    };
    if seen.size() > limits.max_bytes {
        return Err(too_large(seen.size()));
    }
    let raw = match fs::read(&real_path) {
        Ok(raw) => raw,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(RewriteOutcome::Absent),
        Err(e) => {
            return Err(OlError::new(
                ERR_HOOK_WRITE_FAILED,
                format!("Cannot read '{display}': {e}"),
            ))
        }
    };
    // The file grew between the fingerprint and the read: that is a writer at
    // work, and the compare below would abandon anyway.
    if raw.len() as u64 != seen.size() {
        return Ok(RewriteOutcome::Contended);
    }
    let raw = String::from_utf8(raw).map_err(|_| {
        OlError::new(
            ERR_HOOK_MALFORMED_JSONC,
            format!("'{display}' is not UTF-8 text"),
        )
    })?;
    let root = CstRootNode::parse(&raw, &ParseOptions::default()).map_err(|e| {
        OlError::new(
            ERR_HOOK_MALFORMED_JSONC,
            format!("Cannot parse '{display}' as JSON: {e}"),
        )
    })?;

    mutate(&root)?;

    let edited = root.to_string();
    if edited == raw {
        return Ok(RewriteOutcome::Unchanged);
    }
    match crate::fs_secure::replace_preserving(&real_path, edited.as_bytes(), &seen) {
        Ok(crate::fs_secure::ReplaceOutcome::Replaced) => Ok(RewriteOutcome::Written),
        Ok(crate::fs_secure::ReplaceOutcome::Contended) => Ok(RewriteOutcome::Contended),
        Err(e) => Err(OlError::new(
            ERR_ATOMIC_WRITE_FAILED,
            format!("Cannot replace '{display}': {e}"),
        )),
    }
}

/// The TOML sibling of [`atomic_rewrite_jsonc`], for the one agent that names
/// its model provider in a `config.toml` rather than in a JSONC settings file.
///
/// Same discipline, same temp-file-then-rename, same symlink resolution — the
/// only difference is the parser, and factoring that out is what stops a second
/// call site re-deriving the durability dance. The document handed to `mutate`
/// is `toml_edit`'s format-preserving one: comments, key order and spacing
/// outside the edited keys survive, which is the whole reason this exists
/// rather than a `toml::from_str` / `to_string` round trip.
///
/// A missing file starts from an empty document. **This never deletes one** —
/// removing the last of our keys leaves an empty `config.toml` behind, because
/// nothing records whether we created it and a customer's own empty file is
/// not ours to remove.
pub fn atomic_rewrite_toml<F>(path: &Path, mutate: F) -> Result<(), OlError>
where
    F: FnOnce(&mut toml_edit::DocumentMut) -> Result<(), OlError>,
{
    let real_path = if path.is_symlink() || path.exists() {
        fs::canonicalize(path).map_err(|e| {
            OlError::new(
                ERR_SYMLINK_CANONICALIZE_FAILED,
                format!("Cannot resolve config path '{}': {e}", path.display()),
            )
            .with_suggestion("Check that the symlink target exists and is accessible.")
        })?
    } else {
        path.to_path_buf()
    };

    if let Some(parent) = real_path.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            OlError::new(
                ERR_HOOK_WRITE_FAILED,
                format!("Cannot create config directory: {e}"),
            )
        })?;
    }

    let raw_toml = if real_path.exists() {
        fs::read_to_string(&real_path).map_err(|e| {
            OlError::new(
                ERR_HOOK_WRITE_FAILED,
                format!("Cannot read config file: {e}"),
            )
        })?
    } else {
        String::new()
    };

    let mut doc = raw_toml.parse::<toml_edit::DocumentMut>().map_err(|e| {
        OlError::new(
            ERR_HOOK_MALFORMED_TOML,
            format!(
                "Cannot parse '{}' as TOML: {e}",
                crate::core::path_compat::display_path(&real_path)
            ),
        )
        .with_suggestion("Fix the TOML syntax in the file, then re-run the command.")
    })?;

    mutate(&mut doc)?;

    write_replacing(&real_path, doc.to_string().as_bytes())
}

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

    #[test]
    fn atomic_rewrite_creates_file_if_missing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");

        atomic_rewrite_jsonc(&path, |root| {
            let obj = root.object_value_or_set();
            obj.append(
                "test",
                jsonc_parser::cst::CstInputValue::String("value".into()),
            );
            Ok(())
        })
        .unwrap();

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("\"test\""));
        assert!(content.contains("\"value\""));
    }

    #[test]
    fn atomic_rewrite_preserves_existing_content() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "{\n  \"existing\": 42\n}").unwrap();

        atomic_rewrite_jsonc(&path, |root| {
            let obj = root.object_value_or_set();
            obj.append("added", jsonc_parser::cst::CstInputValue::Bool(true));
            Ok(())
        })
        .unwrap();

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("\"existing\": 42"));
        assert!(content.contains("\"added\""));
    }

    #[test]
    fn atomic_rewrite_is_atomic_on_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let original = "{\"keep\": true}";
        fs::write(&path, original).unwrap();

        let result = atomic_rewrite_jsonc(&path, |_root| {
            Err(OlError::new("OL-TEST", "intentional failure"))
        });

        assert!(result.is_err());
        let content = fs::read_to_string(&path).unwrap();
        assert_eq!(content, original);
    }

    #[test]
    fn no_temp_file_left_on_success() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "{}").unwrap();

        atomic_rewrite_jsonc(&path, |_root| Ok(())).unwrap();

        let tmp = path.with_extension("json.openlatch-tmp");
        assert!(!tmp.exists());
    }

    const LIMITS: RewriteLimits = RewriteLimits { max_bytes: 1 << 16 };

    fn set_key(root: &CstRootNode, key: &str, value: &str) {
        let obj = root.object_value_or_set();
        let v = jsonc_parser::cst::CstInputValue::String(value.into());
        match obj.get(key) {
            Some(prop) => prop.set_value(v),
            None => {
                obj.append(key, v);
            }
        }
    }

    #[test]
    fn rewrite_never_creates_a_missing_file_or_parent() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("data").join("globalState.json");

        let outcome = rewrite_existing_json(&path, LIMITS, |root| {
            set_key(root, "ollamaBaseUrl", "http://127.0.0.1:7601");
            Ok(())
        })
        .unwrap();

        assert_eq!(outcome, RewriteOutcome::Absent);
        assert!(!path.exists());
        assert!(
            !path.parent().unwrap().exists(),
            "no parent directory either"
        );
    }

    #[test]
    fn rewrite_refuses_a_file_over_the_cap_with_a_code() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("globalState.json");
        let big = format!("{{\"taskHistory\":\"{}\"}}", "x".repeat(200));
        fs::write(&path, &big).unwrap();

        let err = rewrite_existing_json(&path, RewriteLimits { max_bytes: 64 }, |root| {
            set_key(root, "ollamaBaseUrl", "http://127.0.0.1:7601");
            Ok(())
        })
        .expect_err("over the cap");
        assert_eq!(err.code, ERR_MODEL_RELAY_STATE_FILE);
        assert_eq!(fs::read_to_string(&path).unwrap(), big, "never truncated");
    }

    #[test]
    fn rewrite_is_a_noop_when_bytes_are_unchanged() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("globalState.json");
        fs::write(&path, "{\"ollamaBaseUrl\":\"http://127.0.0.1:7601\"}").unwrap();
        let before = crate::fs_secure::fingerprint(&path).unwrap();

        let outcome = rewrite_existing_json(&path, LIMITS, |root| {
            set_key(root, "ollamaBaseUrl", "http://127.0.0.1:7601");
            Ok(())
        })
        .unwrap();

        assert_eq!(outcome, RewriteOutcome::Unchanged);
        assert_eq!(
            crate::fs_secure::fingerprint(&path).unwrap(),
            before,
            "mtime, size and inode untouched"
        );
    }

    /// The editor saves while we are mid-edit: its bytes win.
    #[test]
    fn rewrite_aborts_when_the_file_changed_under_it() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("globalState.json");
        fs::write(&path, "{\"actModeApiProvider\":\"ollama\"}").unwrap();
        let theirs = "{\"actModeApiProvider\":\"gemini\",\"geminiBaseUrl\":\"\"}";

        let outcome = rewrite_existing_json(&path, LIMITS, |root| {
            // A concurrent writer, deterministically between our read and our
            // rename: temp file then rename, the way the editor saves.
            let tmp = dir.path().join("editor-save");
            fs::write(&tmp, theirs).unwrap();
            fs::rename(&tmp, &path).unwrap();
            set_key(root, "ollamaBaseUrl", "http://127.0.0.1:7601");
            Ok(())
        })
        .unwrap();

        assert_eq!(outcome, RewriteOutcome::Contended);
        assert_eq!(fs::read_to_string(&path).unwrap(), theirs);
    }

    #[test]
    #[cfg(unix)]
    fn rewrite_preserves_mode_0600() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("providers.json");
        fs::write(&path, "{}").unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();

        let outcome = rewrite_existing_json(&path, LIMITS, |root| {
            set_key(root, "lastUsedProvider", "ollama");
            Ok(())
        })
        .unwrap();

        assert_eq!(outcome, RewriteOutcome::Written);
        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
    }

    /// The live defect: every rewrite of an existing agent file reset its mode to
    /// the umask, so `providers.json` (API keys, `0600`) became `0644`.
    #[test]
    #[cfg(unix)]
    fn atomic_rewrite_jsonc_keeps_an_existing_files_mode() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("providers.json");
        fs::write(&path, "{}").unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();

        atomic_rewrite_jsonc(&path, |root| {
            set_key(root, "k", "v");
            Ok(())
        })
        .unwrap();

        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
    }

    #[test]
    #[cfg(unix)]
    fn a_planted_temp_symlink_is_not_followed() {
        let dir = tempfile::tempdir().unwrap();
        let victim = dir.path().join("victim");
        fs::write(&victim, "PRECIOUS").unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "{}").unwrap();
        std::os::unix::fs::symlink(&victim, dir.path().join("settings.json.openlatch-tmp"))
            .unwrap();

        atomic_rewrite_jsonc(&path, |root| {
            set_key(root, "k", "v");
            Ok(())
        })
        .unwrap();
        assert_eq!(fs::read_to_string(&victim).unwrap(), "PRECIOUS");

        std::os::unix::fs::symlink(&victim, dir.path().join("settings.json.openlatch-tmp"))
            .unwrap();
        rewrite_existing_json(&path, LIMITS, |root| {
            set_key(root, "k", "w");
            Ok(())
        })
        .unwrap();
        assert_eq!(fs::read_to_string(&victim).unwrap(), "PRECIOUS");
        assert!(fs::read_to_string(&path).unwrap().contains("\"w\""));
    }

    #[test]
    #[cfg(unix)]
    fn atomic_rewrite_through_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.json");
        let link = dir.path().join("link.json");
        fs::write(&real, "{}").unwrap();
        std::os::unix::fs::symlink(&real, &link).unwrap();

        atomic_rewrite_jsonc(&link, |root| {
            let obj = root.object_value_or_set();
            obj.append("via_symlink", jsonc_parser::cst::CstInputValue::Bool(true));
            Ok(())
        })
        .unwrap();

        let content = fs::read_to_string(&real).unwrap();
        assert!(content.contains("\"via_symlink\""));
        assert!(link.is_symlink());
    }
}