openlatch-client 0.6.1

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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
//! The settings-key sink (I-2 D-25, D-33, D-34): a top-level key of a customer's own JSON/JSONC
//! settings file, carrying a proxy URL, edited as a byte-range splice on the raw text so every
//! byte outside the key's own span — comments included — is copied verbatim.
//!
//! Built on the existing `model_relay_endpoints` ledger, under the `proxy:` key prefix
//! ([`RECORD_PREFIX`]): every field a settings key needs (`prior`, `last_written`, the
//! `Pending → Wired → Released` state machine) is already on [`EndpointRecord`], and isolation
//! from Cline's provider slots is by prefix alone — `endpoint_records("cline:")` never sees a
//! `proxy:` record and vice versa.

use std::path::Path;

use jsonc_parser::ast::Value;
use jsonc_parser::common::Ranged;
use jsonc_parser::tokens::{Token, TokenAndRange};
use jsonc_parser::{parse_to_ast, CollectOptions, CommentCollectionStrategy, ParseOptions};

use crate::core::path_compat;
use crate::error::{OlError, ERR_MODEL_RELAY_IO, ERR_MODEL_RELAY_SETTINGS};
use crate::hooks::atomic::{self, RewriteLimits, RewriteOutcome};
use crate::hooks::model_relay_endpoints::{self, EndpointRecord, ReleasedBy, SlotState, SlotValue};
use crate::hooks::provider_endpoints::now_unix;
use crate::model_relay::preflight;

/// The key prefix under which every settings-key record lives in the shared ledger. Not a new
/// record kind — an ordinary [`EndpointRecord`] under this prefix.
pub const RECORD_PREFIX: &str = "proxy:";

/// The bound every settings file is read under — [`crate::hooks::cline_providers::MAX_STATE_FILE_BYTES`],
/// reused rather than redeclared: a customer's editor settings file is exactly the kind of
/// agent state file that constant already bounds.
const LIMITS: RewriteLimits = RewriteLimits {
    max_bytes: crate::hooks::cline_providers::MAX_STATE_FILE_BYTES,
};

/// The layout-trial URL `observe_key` splices in (and immediately discards) to prove a settings
/// file's layout can safely take a NEW key. Never written anywhere for real.
const LAYOUT_PROBE_URL: &str = "http://127.0.0.1:1";

/// What [`write_proxy_key`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyWrite {
    /// The key now holds `url`, freshly written.
    Written,
    /// The key already held `url`, written by us.
    AlreadyOurs,
    /// The key holds a value OpenLatch did not write. Never overwritten (D-34).
    Foreign(String),
    /// The file could not be parsed as JSONC, or its layout could not safely take the key.
    Unparseable(String),
}

/// What a key holds right now, judged against the ledger. Read-only; also what plan 04's
/// `OL-RELAY-SETTINGS` detector calls.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Observed {
    Unset(SlotValue),
    Ours(String),
    Foreign(String),
    Unparseable(String),
    NoFile,
}

fn collect_options() -> CollectOptions {
    CollectOptions {
        comments: CommentCollectionStrategy::Off,
        tokens: true,
    }
}

fn parse_options() -> ParseOptions {
    ParseOptions::default()
}

/// The ledger key one settings key lives under. A key containing `@` is refused by
/// [`write_proxy_key`] before this is ever called, because the release path parses the key back
/// out of the record key.
fn record_key(agent: &str, key: &str, file: &Path) -> String {
    format!(
        "{RECORD_PREFIX}{agent}:{key}@{}",
        path_compat::display_path(file)
    )
}

/// The exact-match record for `rk`, if the ledger holds one. [`model_relay_endpoints::endpoint_records`]
/// filters by prefix, so this narrows to the one exact key.
fn find_record(rk: &str) -> Result<Option<EndpointRecord>, OlError> {
    Ok(model_relay_endpoints::endpoint_records(rk)?
        .into_iter()
        .find(|(k, _)| k == rk)
        .map(|(_, r)| r))
}

/// Whether `new`'s text, re-parsed, holds `url` at `key` as the LAST property of that name — the
/// read-back half of every write.
fn reads_back(new: &str, key: &str, url: &str) -> bool {
    let Ok(parsed) = parse_to_ast(new, &collect_options(), &parse_options()) else {
        return false;
    };
    match parsed.value {
        Some(Value::Object(obj)) => matches!(
            obj.properties.iter().rev().find(|p| p.name.as_str() == key).map(|p| &p.value),
            Some(Value::StringLit(s)) if s.value == url
        ),
        _ => false,
    }
}

pub(crate) fn observe_key(file: &Path, key: &str, agent: &str) -> Result<Observed, OlError> {
    let bytes = match std::fs::read(file) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Observed::NoFile),
        Err(e) => {
            return Err(OlError::new(
                ERR_MODEL_RELAY_IO,
                format!("cannot read {}: {e}", file.display()),
            ))
        }
    };
    if bytes.len() as u64 > LIMITS.max_bytes {
        return Ok(Observed::Unparseable(format!(
            "the settings file is over the {} byte limit for a file OpenLatch edits",
            LIMITS.max_bytes
        )));
    }
    let raw = match String::from_utf8(bytes) {
        Ok(s) => s,
        Err(e) => return Ok(Observed::Unparseable(e.to_string())),
    };
    let parsed = match parse_to_ast(&raw, &collect_options(), &parse_options()) {
        Ok(p) => p,
        Err(e) => return Ok(Observed::Unparseable(e.to_string())),
    };
    let obj = match parsed.value {
        None => return Ok(Observed::Unset(SlotValue::Absent)),
        Some(Value::Object(obj)) => obj,
        Some(_) => {
            return Ok(Observed::Unparseable(
                "the settings file is not a JSON object".to_string(),
            ))
        }
    };
    let current = match obj.properties.iter().rev().find(|p| p.name.as_str() == key) {
        None => SlotValue::Absent,
        Some(p) => match &p.value {
            Value::NullKeyword(_) => SlotValue::Null,
            Value::StringLit(s) => SlotValue::Text(s.value.to_string()),
            other => return Ok(Observed::Foreign(other.text(&raw).to_string())),
        },
    };

    // LAYOUT TRIAL (02-31): only when the key is absent — the root is an object here — prove
    // that a NEW key can be inserted safely, without writing anything for real.
    if matches!(current, SlotValue::Absent) {
        if let Some(new) = splice_set(&raw, key, LAYOUT_PROBE_URL, &SlotValue::Absent)? {
            if !reads_back(&new, key, LAYOUT_PROBE_URL) {
                return Ok(Observed::Unparseable(
                    preflight::SETTINGS_LAYOUT.to_string(),
                ));
            }
        }
    }

    match current {
        SlotValue::Text(s) => {
            let rk = record_key(agent, key, file);
            let rec = find_record(&rk)?;
            if rec.as_ref().and_then(|r| r.last_written.as_deref()) == Some(s.as_str()) {
                Ok(Observed::Ours(s))
            } else if s.trim().is_empty() {
                Ok(Observed::Unset(SlotValue::Text(s)))
            } else {
                // INCLUDING a 127.0.0.1 URL with no record: loopback is not authorship.
                Ok(Observed::Foreign(s))
            }
        }
        SlotValue::Absent | SlotValue::Null => Ok(Observed::Unset(current)),
    }
}

fn parse_port(url: &str) -> Result<u16, OlError> {
    reqwest::Url::parse(url)
        .ok()
        .and_then(|u| u.port())
        .ok_or_else(|| {
            OlError::new(
                ERR_MODEL_RELAY_IO,
                format!("{url} is not a URL with a port"),
            )
        })
}

enum CreateOutcome {
    Written,
    AlreadyExists,
    Err(OlError),
}

/// `OpenOptions::create_new`: refuses to overwrite anything that appeared between the NoFile
/// observation and this call.
fn create_new_file(file: &Path, key: &str, url: &str) -> CreateOutcome {
    let json_url = match serde_json::to_string(url) {
        Ok(j) => j,
        Err(e) => return CreateOutcome::Err(OlError::new(ERR_MODEL_RELAY_IO, e.to_string())),
    };
    let content = format!("{{\n  \"{key}\": {json_url}\n}}\n");
    use std::io::Write;
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(file)
    {
        Ok(mut f) => match f.write_all(content.as_bytes()) {
            Ok(()) => CreateOutcome::Written,
            Err(e) => CreateOutcome::Err(OlError::new(ERR_MODEL_RELAY_IO, e.to_string())),
        },
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => CreateOutcome::AlreadyExists,
        Err(e) => CreateOutcome::Err(OlError::new(
            ERR_MODEL_RELAY_IO,
            format!("cannot create {}: {e}", file.display()),
        )),
    }
}

pub fn write_proxy_key(
    file: &Path,
    key: &str,
    url: &str,
    agent: &str,
) -> Result<KeyWrite, OlError> {
    if !file.parent().is_some_and(std::path::Path::is_dir) {
        return Err(OlError::new(
            ERR_MODEL_RELAY_SETTINGS,
            preflight::SETTINGS_NO_FILE.to_string(),
        ));
    }
    if key.contains('@') {
        return Err(OlError::new(
            ERR_MODEL_RELAY_IO,
            format!("proxy settings key {key:?} must not contain '@'"),
        ));
    }
    let rk = record_key(agent, key, file);
    let port = parse_port(url)?;

    for _ in 0..crate::hooks::provider_endpoints::CONTENDED_ATTEMPTS {
        let observed = observe_key(file, key, agent)?;
        match &observed {
            Observed::Foreign(v) => return Ok(KeyWrite::Foreign(v.clone())),
            Observed::Unparseable(why) => return Ok(KeyWrite::Unparseable(why.clone())),
            Observed::Ours(v) if v == url => {
                if find_record(&rk)?.is_some_and(|r| r.state != SlotState::Wired) {
                    model_relay_endpoints::update_endpoint(&rk, |r| {
                        r.state = SlotState::Wired;
                        r.changed_at = now_unix();
                    })?;
                }
                return Ok(KeyWrite::AlreadyOurs);
            }
            Observed::Ours(_) | Observed::Unset(_) | Observed::NoFile => {}
        }

        let prior = match find_record(&rk)? {
            Some(rec) => rec.prior,
            None => match &observed {
                Observed::NoFile => SlotValue::Absent,
                Observed::Unset(v) => v.clone(),
                Observed::Ours(v) => SlotValue::Text(v.clone()),
                Observed::Foreign(_) | Observed::Unparseable(_) => unreachable!("handled above"),
            },
        };

        model_relay_endpoints::put_endpoint(
            &rk,
            EndpointRecord {
                port,
                origin: String::new(),
                prior,
                last_written: Some(url.to_string()),
                file: file.to_path_buf(),
                state: SlotState::Pending,
                released_by: None,
                changed_at: now_unix(),
                proven_at: None,
                proven_by: None,
                family: None,
                pending_event: None,
                misconfigured_event: None,
            },
        )?;

        if matches!(observed, Observed::NoFile) {
            match create_new_file(file, key, url) {
                CreateOutcome::Written => {
                    model_relay_endpoints::update_endpoint(&rk, |r| r.state = SlotState::Wired)?;
                    return Ok(KeyWrite::Written);
                }
                // It exists now: loop back to re-observe.
                CreateOutcome::AlreadyExists => continue,
                CreateOutcome::Err(e) => return Err(e),
            }
        }

        let expect = match &observed {
            Observed::Unset(v) => v.clone(),
            Observed::Ours(v) => SlotValue::Text(v.clone()),
            _ => SlotValue::Absent,
        };
        let mut refused = false;
        let outcome = atomic::rewrite_existing_text(file, LIMITS, |raw| {
            match splice_set(raw, key, url, &expect)? {
                Some(new) if !reads_back(&new, key, url) => {
                    refused = true;
                    Ok(None)
                }
                other => Ok(other),
            }
        })?;

        if refused {
            model_relay_endpoints::update_endpoint(&rk, |r| {
                r.state = SlotState::Released;
                r.released_by = Some(ReleasedBy::Wiring);
                r.changed_at = now_unix();
            })?;
            return Ok(KeyWrite::Unparseable(
                preflight::SETTINGS_LAYOUT.to_string(),
            ));
        }

        match outcome {
            RewriteOutcome::Written => {
                model_relay_endpoints::update_endpoint(&rk, |r| r.state = SlotState::Wired)?;
                return Ok(KeyWrite::Written);
            }
            RewriteOutcome::Unchanged | RewriteOutcome::Contended | RewriteOutcome::Absent => {
                // Somebody saved between observe and write, or the file vanished: re-observe on
                // the next attempt.
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
        }
    }

    model_relay_endpoints::update_endpoint(&rk, |r| {
        r.state = SlotState::Released;
        r.released_by = Some(ReleasedBy::Wiring);
        r.changed_at = now_unix();
    })?;
    Err(OlError::new(
        ERR_MODEL_RELAY_SETTINGS,
        preflight::SETTINGS_CONTENDED.to_string(),
    ))
}

pub fn release_proxy_key(
    file: &Path,
    key: &str,
    agent: &str,
    by: ReleasedBy,
) -> Result<bool, OlError> {
    let rk = record_key(agent, key, file);
    let Some(rec) = find_record(&rk)? else {
        return Ok(false);
    };
    if rec.state != SlotState::Released {
        model_relay_endpoints::update_endpoint(&rk, |r| {
            r.state = SlotState::Released;
            r.released_by = Some(by);
            r.changed_at = now_unix();
        })?;
    }

    for _ in 0..crate::hooks::provider_endpoints::CONTENDED_ATTEMPTS {
        let outcome = atomic::rewrite_existing_text(file, LIMITS, |raw| {
            splice_restore(raw, key, rec.last_written.as_deref(), &rec.prior)
        })?;
        match outcome {
            RewriteOutcome::Written => return Ok(true),
            // The developer changed it, or the file is gone: their value stays.
            RewriteOutcome::Unchanged | RewriteOutcome::Absent => return Ok(false),
            RewriteOutcome::Contended => {
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
        }
    }
    Err(OlError::new(
        ERR_MODEL_RELAY_SETTINGS,
        "the file kept changing under the restore".to_string(),
    ))
}

// ---------------------------------------------------------------------------
// The splices — the only place either file's bytes are touched
// ---------------------------------------------------------------------------

/// Two spaces — what `serde_json::to_string_pretty` and this crate's other writers produce, used
/// as the unit of indentation only when nothing can be detected (an empty object).
const INDENT_UNIT: &str = "  ";

fn splice_set(
    raw: &str,
    key: &str,
    url: &str,
    expect: &SlotValue,
) -> Result<Option<String>, OlError> {
    let parsed = parse_to_ast(raw, &collect_options(), &parse_options())
        .map_err(|e| OlError::new(ERR_MODEL_RELAY_IO, e.to_string()))?;
    let json_url =
        serde_json::to_string(url).map_err(|e| OlError::new(ERR_MODEL_RELAY_IO, e.to_string()))?;

    let Some(value) = parsed.value else {
        // NO ROOT VALUE (empty, whitespace-only or comment-only file).
        if !matches!(expect, SlotValue::Absent) {
            return Ok(None);
        }
        let mut out = raw.to_string();
        if !out.is_empty() && !out.ends_with('\n') {
            out.push('\n');
        }
        out.push_str(&format!("{{\n{INDENT_UNIT}\"{key}\": {json_url}\n}}\n"));
        return Ok(Some(out));
    };
    let Value::Object(obj) = value else {
        return Ok(None);
    };

    let current_prop = obj.properties.iter().rev().find(|p| p.name.as_str() == key);
    let current = match current_prop {
        None => Some(SlotValue::Absent),
        Some(p) => match &p.value {
            Value::NullKeyword(_) => Some(SlotValue::Null),
            Value::StringLit(s) => Some(SlotValue::Text(s.value.to_string())),
            _ => None,
        },
    };
    if current.as_ref() != Some(expect) {
        return Ok(None);
    }

    let tokens = parsed.tokens.unwrap_or_default();
    match current_prop {
        Some(p) => {
            // KEY PRESENT: replace the value span only.
            let vr = p.value.range();
            Ok(Some(format!(
                "{}{json_url}{}",
                &raw[..vr.start],
                &raw[vr.end..]
            )))
        }
        None => Ok(Some(insert_property(raw, &obj, &tokens, key, &json_url))),
    }
}

fn comma_between(
    tokens: &[TokenAndRange],
    from: usize,
    to: usize,
) -> Option<jsonc_parser::common::Range> {
    tokens
        .iter()
        .find(|t| matches!(t.token, Token::Comma) && t.range.start >= from && t.range.end <= to)
        .map(|t| t.range)
}

fn comma_before(
    tokens: &[TokenAndRange],
    before: usize,
    object_start: usize,
) -> Option<jsonc_parser::common::Range> {
    tokens
        .iter()
        .rfind(|t| {
            matches!(t.token, Token::Comma)
                && t.range.end <= before
                && t.range.start >= object_start
        })
        .map(|t| t.range)
}

fn line_indent(raw: &str, pos: usize) -> String {
    let line_start = raw[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
    raw[line_start..pos]
        .chars()
        .take_while(|c| *c == ' ' || *c == '\t')
        .collect()
}

fn insert_property(
    raw: &str,
    obj: &jsonc_parser::ast::Object,
    tokens: &[TokenAndRange],
    key: &str,
    json_url: &str,
) -> String {
    let c = obj.range.end - 1; // the `}` byte
    let insertion = format!("\"{key}\": {json_url}");

    if obj.properties.is_empty() {
        let inner_has_newline = raw[obj.range.start + 1..c].contains('\n');
        if !inner_has_newline {
            return format!("{}{insertion}{}", &raw[..c], &raw[c..]);
        }
        let after_brace = obj.range.start + 1;
        let nl_at = raw[after_brace..]
            .find('\n')
            .map(|off| after_brace + off + 1)
            .unwrap_or(after_brace);
        let close_indent = line_indent(raw, c);
        let indent = format!("{close_indent}{INDENT_UNIT}");
        return format!("{}{indent}{insertion}\n{}", &raw[..nl_at], &raw[nl_at..]);
    }

    let p = obj.properties.last().expect("non-empty checked above");
    let p_end = p.value.range().end;
    let single_line = !raw[obj.range.start..c].contains('\n');

    if single_line {
        return match comma_between(tokens, p_end, c) {
            None => format!("{}, {insertion}{}", &raw[..p_end], &raw[p_end..]),
            Some(cr) => format!("{} {insertion},{}", &raw[..cr.end], &raw[cr.end..]),
        };
    }

    let indent = line_indent(raw, p.range.start);
    let comma = comma_between(tokens, p_end, c);
    let m = comma.map(|cr| cr.end).unwrap_or(p_end);
    let brace_shared = !raw[m..c].contains('\n');

    if brace_shared {
        return match comma {
            None => format!("{},\n{indent}{insertion}{}", &raw[..p_end], &raw[p_end..]),
            Some(cr) => format!("{}\n{indent}{insertion},{}", &raw[..cr.end], &raw[cr.end..]),
        };
    }

    // OWN-LINE brace: e = the first '\n' after m, before c.
    let e = raw[m..c].find('\n').map(|off| m + off).unwrap_or(m);
    match comma {
        None => format!(
            "{},{}\n{indent}{insertion}{}",
            &raw[..p_end],
            &raw[p_end..e],
            &raw[e..]
        ),
        Some(_) => format!("{}\n{indent}{insertion},{}", &raw[..e], &raw[e..]),
    }
}

fn splice_restore(
    raw: &str,
    key: &str,
    ours: Option<&str>,
    prior: &SlotValue,
) -> Result<Option<String>, OlError> {
    let parsed = parse_to_ast(raw, &collect_options(), &parse_options())
        .map_err(|e| OlError::new(ERR_MODEL_RELAY_IO, e.to_string()))?;
    let Some(Value::Object(obj)) = parsed.value else {
        return Ok(None);
    };
    let Some(prop) = obj.properties.iter().rev().find(|p| p.name.as_str() == key) else {
        return Ok(None);
    };
    let holds_ours = matches!(&prop.value, Value::StringLit(s) if Some(s.value.as_ref()) == ours);
    if !holds_ours {
        return Ok(None);
    }

    match prior {
        SlotValue::Text(t) => {
            let json = serde_json::to_string(t)
                .map_err(|e| OlError::new(ERR_MODEL_RELAY_IO, e.to_string()))?;
            let vr = prop.value.range();
            Ok(Some(format!(
                "{}{json}{}",
                &raw[..vr.start],
                &raw[vr.end..]
            )))
        }
        SlotValue::Null => {
            let vr = prop.value.range();
            Ok(Some(format!("{}null{}", &raw[..vr.start], &raw[vr.end..])))
        }
        SlotValue::Absent => {
            let tokens = parsed.tokens.unwrap_or_default();
            Ok(Some(delete_property(raw, &obj, &tokens, prop)))
        }
    }
}

fn delete_property(
    raw: &str,
    obj: &jsonc_parser::ast::Object,
    tokens: &[TokenAndRange],
    p: &jsonc_parser::ast::ObjectProp,
) -> String {
    let c = obj.range.end - 1;
    let following = comma_between(tokens, p.range.end, c);
    let preceding = comma_before(tokens, p.range.start, obj.range.start);
    let single_line = !raw[obj.range.start..c].contains('\n');

    if single_line {
        return match following {
            Some(cr) => {
                let mut start = p.range.start;
                if start > 0 && raw.as_bytes()[start - 1] == b' ' {
                    start -= 1;
                }
                format!("{}{}", &raw[..start], &raw[cr.end..])
            }
            None => match preceding {
                Some(pcr) => format!("{}{}", &raw[..pcr.start], &raw[p.range.end..]),
                None => format!("{}{}", &raw[..p.range.start], &raw[p.range.end..]),
            },
        };
    }

    let m = following.map(|cr| cr.end).unwrap_or(p.range.end);
    let brace_shared = !raw[m..c].contains('\n');

    if brace_shared {
        return match (following, preceding) {
            (Some(fcr), Some(pcr)) => format!("{}{}", &raw[..pcr.end], &raw[fcr.end..]),
            (Some(fcr), None) => format!("{}{}", &raw[..p.range.start], &raw[fcr.end..]),
            (None, Some(pcr)) => format!("{}{}", &raw[..pcr.start], &raw[p.range.end..]),
            (None, None) => format!("{}{}", &raw[..p.range.start], &raw[p.range.end..]),
        };
    }

    // p ALONE ON ITS LINE: delete its whole line, including the '\n' that ends it.
    let line_start = raw[..p.range.start].rfind('\n').map(|i| i + 1).unwrap_or(0);
    let after = following.map(|cr| cr.end).unwrap_or(p.range.end);
    let line_end = raw[after..]
        .find('\n')
        .map(|off| after + off + 1)
        .unwrap_or(raw.len());

    if following.is_some() {
        format!("{}{}", &raw[..line_start], &raw[line_end..])
    } else if let Some(pcr) = preceding {
        format!(
            "{}{}{}",
            &raw[..pcr.start],
            &raw[pcr.end..line_start],
            &raw[line_end..]
        )
    } else {
        format!("{}{}", &raw[..line_start], &raw[line_end..])
    }
}

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

    /// 02-25: every test here runs its whole body inside a temp `OPENLATCH_DIR`, under the
    /// crate's env-var lock — a private copy of `hooks::tests::with_openlatch_dir`, which is not
    /// callable from this module.
    fn with_openlatch_dir<T>(f: impl FnOnce() -> T) -> T {
        let _guard = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().expect("tempdir");
        let prev = std::env::var_os("OPENLATCH_DIR");
        std::env::set_var("OPENLATCH_DIR", tmp.path());
        let out = f();
        match prev {
            Some(v) => std::env::set_var("OPENLATCH_DIR", v),
            None => std::env::remove_var("OPENLATCH_DIR"),
        }
        out
    }

    const URL: &str = "http://127.0.0.1:7600";
    const AGENT: &str = "fake-a";
    const KEY: &str = "fake.proxy";

    /// The write gives back exactly the byte-identity table's shape 1 (comments, no trailing
    /// comma), and the release restores the original bytes exactly.
    #[test]
    fn insert_then_release_is_byte_identical_for_a_commented_file() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            let original = "{\n  // customer\n  \"a\": 1 // note\n}\n";
            std::fs::write(&file, original).expect("seed");

            let write = write_proxy_key(&file, KEY, URL, AGENT).expect("write");
            assert_eq!(write, KeyWrite::Written);
            let after_write = std::fs::read_to_string(&file).expect("read after write");
            assert_eq!(
                after_write,
                format!(
                    "{{\n  // customer\n  \"a\": 1, // note\n  \"{KEY}\": {}\n}}\n",
                    serde_json::to_string(URL).unwrap()
                )
            );
            assert!(reads_back(&after_write, KEY, URL));

            // A second write of the same URL is a no-op read (AlreadyOurs), byte-identical.
            assert_eq!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("second write"),
                KeyWrite::AlreadyOurs
            );
            assert_eq!(std::fs::read_to_string(&file).unwrap(), after_write);

            assert!(release_proxy_key(&file, KEY, AGENT, ReleasedBy::Teardown).expect("release"));
            assert_eq!(std::fs::read_to_string(&file).unwrap(), original);
        });
    }

    /// D-34: a value OpenLatch did not write is never overwritten, and never recorded.
    #[test]
    fn a_foreign_value_is_never_overwritten_and_never_recorded() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            let original = "{\n  \"fake.proxy\": \"http://corp:3128\"\n}\n";
            std::fs::write(&file, original).expect("seed");

            let write = write_proxy_key(&file, KEY, URL, AGENT).expect("write");
            assert_eq!(write, KeyWrite::Foreign("http://corp:3128".to_string()));
            assert_eq!(std::fs::read_to_string(&file).unwrap(), original);
            assert!(model_relay_endpoints::endpoint_records(RECORD_PREFIX)
                .expect("read ledger")
                .is_empty());
        });
    }

    /// A bare loopback value with no ledger record is foreign too: loopback is not authorship,
    /// and a customer's own local gateway must never be claimed.
    #[test]
    fn our_loopback_without_a_record_is_foreign() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            std::fs::write(&file, format!("{{\n  \"fake.proxy\": \"{URL}\"\n}}\n")).unwrap();
            assert_eq!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("write over loopback"),
                KeyWrite::Foreign(URL.to_string())
            );
        });
    }

    /// An absent file is created only when its directory exists; the created file is exactly the
    /// two-line object the plan's byte-identity table names, and it comes back empty (not
    /// deleted) after release.
    #[test]
    fn an_absent_file_is_created_only_when_its_directory_exists() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            assert_eq!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("write"),
                KeyWrite::Written
            );
            assert_eq!(
                std::fs::read_to_string(&file).unwrap(),
                format!(
                    "{{\n  \"{KEY}\": {}\n}}\n",
                    serde_json::to_string(URL).unwrap()
                )
            );

            assert!(release_proxy_key(&file, KEY, AGENT, ReleasedBy::Teardown).expect("release"));
            assert_eq!(std::fs::read_to_string(&file).unwrap(), "{\n}\n");

            let missing_dir = dir.path().join("nope").join("settings.json");
            let err = write_proxy_key(&missing_dir, KEY, URL, AGENT).expect_err("no directory");
            assert_eq!(err.code, ERR_MODEL_RELAY_SETTINGS);
            assert!(!missing_dir.exists());
        });
    }

    /// A present, "unset" value (`null`) changes only its own span — every other byte, the
    /// comments and the trailing comma included, is untouched.
    #[test]
    fn a_present_unset_key_changes_only_its_value_span() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            let original = "{\n  // customer\n  \"fake.proxy\": null,\n  \"b\": 2,\n}\n";
            std::fs::write(&file, original).expect("seed");

            assert_eq!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("write"),
                KeyWrite::Written
            );
            assert_eq!(
                std::fs::read_to_string(&file).unwrap(),
                format!(
                    "{{\n  // customer\n  \"fake.proxy\": {},\n  \"b\": 2,\n}}\n",
                    serde_json::to_string(URL).unwrap()
                )
            );
        });
    }

    /// The new property is inserted using the FILE's own indentation character (a tab, four
    /// spaces — never a hardcoded two), and a comma is added only where JSON needs one.
    #[test]
    fn an_absent_key_is_inserted_in_the_files_indentation() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let json_url = serde_json::to_string(URL).unwrap();

            let tab_file = dir.path().join("tab.json");
            std::fs::write(&tab_file, "{\n\t\"a\": 1\n}\n").unwrap();
            assert_eq!(
                write_proxy_key(&tab_file, KEY, URL, "tab-agent").expect("tab write"),
                KeyWrite::Written
            );
            assert_eq!(
                std::fs::read_to_string(&tab_file).unwrap(),
                format!("{{\n\t\"a\": 1,\n\t\"{KEY}\": {json_url}\n}}\n")
            );

            let four_file = dir.path().join("four.json");
            std::fs::write(&four_file, "{\n    \"a\": 1,\n}\n").unwrap();
            assert_eq!(
                write_proxy_key(&four_file, KEY, URL, "four-agent").expect("four write"),
                KeyWrite::Written
            );
            assert_eq!(
                std::fs::read_to_string(&four_file).unwrap(),
                format!("{{\n    \"a\": 1,\n    \"{KEY}\": {json_url},\n}}\n")
            );
        });
    }

    /// The seven §3.3 byte-identity-table shapes: the write gives exactly the table's "after the
    /// write" bytes (which read back), and the release restores the ORIGINAL bytes exactly.
    #[test]
    fn insert_then_release_is_byte_identical_across_every_shape() {
        with_openlatch_dir(|| {
            let u = format!("\"{KEY}\": {}", serde_json::to_string(URL).unwrap());
            let shapes: [(&str, String); 7] = [
                (
                    "{\n  // customer\n  \"a\": 1 // note\n}\n",
                    format!("{{\n  // customer\n  \"a\": 1, // note\n  {u}\n}}\n"),
                ),
                (
                    "{\n  \"a\": 1,\n}\n",
                    format!("{{\n  \"a\": 1,\n  {u},\n}}\n"),
                ),
                ("{ \"a\": 1 }\n", format!("{{ \"a\": 1, {u} }}\n")),
                ("{}\n", format!("{{{u}}}\n")),
                (
                    "{ \"a\": 1,\n  \"b\": 2 }\n",
                    format!("{{ \"a\": 1,\n  \"b\": 2,\n  {u} }}\n"),
                ),
                (
                    "{ \"a\": 1,\n  \"b\": 2 }",
                    format!("{{ \"a\": 1,\n  \"b\": 2,\n  {u} }}"),
                ),
                (
                    "{ \"a\": 1,\n  \"b\": 2, }\n",
                    format!("{{ \"a\": 1,\n  \"b\": 2,\n  {u}, }}\n"),
                ),
            ];

            for (i, (original, expected_after_write)) in shapes.iter().enumerate() {
                let dir = tempfile::tempdir().expect("tempdir");
                let file = dir.path().join("settings.json");
                std::fs::write(&file, original).expect("seed");
                let agent = format!("shape-{i}");

                assert_eq!(
                    write_proxy_key(&file, KEY, URL, &agent).expect("write"),
                    KeyWrite::Written,
                    "shape {i}"
                );
                let after_write = std::fs::read_to_string(&file).unwrap();
                assert_eq!(
                    after_write, *expected_after_write,
                    "shape {i} after the write"
                );
                assert!(
                    reads_back(&after_write, KEY, URL),
                    "shape {i} must read back"
                );

                assert!(
                    release_proxy_key(&file, KEY, &agent, ReleasedBy::Teardown).expect("release"),
                    "shape {i}"
                );
                assert_eq!(
                    std::fs::read_to_string(&file).unwrap(),
                    *original,
                    "shape {i} restore"
                );
            }

            // The refused-layout row (02-26): a block comment opening on the last property's
            // line and closing on a later one. The splice would land the key inside the
            // comment, so the read-back refuses it before any record.
            let refused_dir = tempfile::tempdir().expect("tempdir");
            let refused_file = refused_dir.path().join("settings.json");
            let refused = "{ \"a\": 1 /* see\n  ticket */\n}\n";
            std::fs::write(&refused_file, refused).unwrap();
            assert_eq!(
                write_proxy_key(&refused_file, KEY, URL, "refused-agent").expect("write refused"),
                KeyWrite::Unparseable(preflight::SETTINGS_LAYOUT.to_string())
            );
            assert_eq!(std::fs::read_to_string(&refused_file).unwrap(), refused);
            let refused_rk = record_key("refused-agent", KEY, &refused_file);
            assert!(
                find_record(&refused_rk).expect("ledger").is_none(),
                "step 1 refuses the layout before any record is put"
            );
        });
    }

    /// 02-31: `observe_key` runs the same layout trial `write_proxy_key` does, purely — nothing
    /// is ever written by the trial itself.
    #[test]
    fn observe_key_sees_the_refused_layout() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");

            let refused = "{ \"a\": 1 /* see\n  ticket */\n}";
            std::fs::write(&file, refused).unwrap();
            assert_eq!(
                observe_key(&file, KEY, AGENT).expect("observe"),
                Observed::Unparseable(preflight::SETTINGS_LAYOUT.to_string())
            );
            assert_eq!(std::fs::read_to_string(&file).unwrap(), refused);

            let seven_shapes = [
                "{\n  // customer\n  \"a\": 1 // note\n}\n",
                "{\n  \"a\": 1,\n}\n",
                "{ \"a\": 1 }\n",
                "{}\n",
                "{ \"a\": 1,\n  \"b\": 2 }\n",
                "{ \"a\": 1,\n  \"b\": 2 }",
                "{ \"a\": 1,\n  \"b\": 2, }\n",
            ];
            for shape in seven_shapes {
                std::fs::write(&file, shape).unwrap();
                assert_eq!(
                    observe_key(&file, KEY, AGENT).expect("observe shape"),
                    Observed::Unset(SlotValue::Absent),
                    "{shape:?}"
                );
                assert_eq!(std::fs::read_to_string(&file).unwrap(), shape);
            }
        });
    }

    #[test]
    fn an_unparseable_or_non_object_file_is_skipped() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");

            std::fs::write(&file, "{ \"a\": ").unwrap();
            assert!(matches!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("write on garbage"),
                KeyWrite::Unparseable(_)
            ));
            assert_eq!(std::fs::read_to_string(&file).unwrap(), "{ \"a\": ");

            std::fs::write(&file, "[]").unwrap();
            assert!(matches!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("write on array"),
                KeyWrite::Unparseable(_)
            ));
            assert_eq!(std::fs::read_to_string(&file).unwrap(), "[]");

            assert!(model_relay_endpoints::endpoint_records(RECORD_PREFIX)
                .expect("ledger")
                .is_empty());
        });
    }

    #[test]
    fn a_second_write_is_already_ours_and_writes_nothing() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            std::fs::write(&file, "{\n  \"a\": 1\n}\n").unwrap();

            assert_eq!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("first"),
                KeyWrite::Written
            );
            let fp_before = crate::fs_secure::fingerprint(&file).expect("fingerprint");

            assert_eq!(
                write_proxy_key(&file, KEY, URL, AGENT).expect("second"),
                KeyWrite::AlreadyOurs
            );
            let fp_after = crate::fs_secure::fingerprint(&file).expect("fingerprint");
            assert_eq!(fp_before, fp_after, "the file must not be touched");
        });
    }

    #[test]
    fn a_port_change_rewrites_our_value_and_keeps_the_prior() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            // The customer's original value: `null`. It must survive every later rewrite.
            std::fs::write(&file, "{\n  \"fake.proxy\": null\n}\n").unwrap();

            assert_eq!(
                write_proxy_key(&file, KEY, "http://127.0.0.1:7600", AGENT).expect("first"),
                KeyWrite::Written
            );
            assert_eq!(
                write_proxy_key(&file, KEY, "http://127.0.0.1:7700", AGENT).expect("second"),
                KeyWrite::Written
            );
            let content = std::fs::read_to_string(&file).unwrap();
            assert!(content.contains("7700"));
            assert!(!content.contains("7600"));

            let rk = record_key(AGENT, KEY, &file);
            let rec = find_record(&rk)
                .expect("read ledger")
                .expect("record exists");
            assert_eq!(
                rec.prior,
                SlotValue::Null,
                "the customer's original null must survive a port change"
            );
        });
    }

    /// The restore mechanism alone, for each of `SlotValue`'s three shapes — seeded straight into
    /// the ledger record so the test proves `release_proxy_key`/`splice_restore`, not the write
    /// gate that would otherwise refuse a foreign starting value like `Text("x")`.
    #[test]
    fn release_restores_the_prior_representation() {
        with_openlatch_dir(|| {
            for (prior, expected) in [
                (SlotValue::Null, "null".to_string()),
                (SlotValue::Text(String::new()), "\"\"".to_string()),
                (SlotValue::Text("x".to_string()), "\"x\"".to_string()),
            ] {
                let dir = tempfile::tempdir().expect("tempdir");
                let file = dir.path().join("settings.json");
                std::fs::write(
                    &file,
                    format!(
                        "{{\n  \"fake.proxy\": {}\n}}\n",
                        serde_json::to_string(URL).unwrap()
                    ),
                )
                .unwrap();

                let rk = record_key(AGENT, KEY, &file);
                model_relay_endpoints::put_endpoint(
                    &rk,
                    EndpointRecord {
                        port: 7600,
                        origin: String::new(),
                        prior: prior.clone(),
                        last_written: Some(URL.to_string()),
                        file: file.clone(),
                        state: SlotState::Wired,
                        released_by: None,
                        changed_at: 0,
                        proven_at: None,
                        proven_by: None,
                        family: None,
                        pending_event: None,
                        misconfigured_event: None,
                    },
                )
                .expect("seed record");

                assert!(
                    release_proxy_key(&file, KEY, AGENT, ReleasedBy::Teardown).expect("release"),
                    "{prior:?}"
                );
                assert_eq!(
                    std::fs::read_to_string(&file).unwrap(),
                    format!("{{\n  \"fake.proxy\": {expected}\n}}\n"),
                    "{prior:?}"
                );
            }
        });
    }

    #[test]
    fn release_leaves_a_value_the_developer_changed() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            std::fs::write(&file, "{\n  \"a\": 1\n}\n").unwrap();
            write_proxy_key(&file, KEY, URL, AGENT).expect("write");

            let developer_changed = std::fs::read_to_string(&file)
                .unwrap()
                .replace(URL, "http://mine");
            std::fs::write(&file, &developer_changed).unwrap();

            assert!(
                !release_proxy_key(&file, KEY, AGENT, ReleasedBy::Teardown).expect("release"),
                "the developer's own value must never be touched"
            );
            assert_eq!(std::fs::read_to_string(&file).unwrap(), developer_changed);

            let rk = record_key(AGENT, KEY, &file);
            let rec = find_record(&rk)
                .expect("read ledger")
                .expect("record exists");
            assert_eq!(rec.state, SlotState::Released);
        });
    }

    #[test]
    fn release_tombstones_even_when_the_file_is_gone() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            std::fs::write(&file, "{\n  \"a\": 1\n}\n").unwrap();
            write_proxy_key(&file, KEY, URL, AGENT).expect("write");

            std::fs::remove_file(&file).unwrap();
            assert!(!release_proxy_key(&file, KEY, AGENT, ReleasedBy::Teardown).expect("release"));

            let rk = record_key(AGENT, KEY, &file);
            let rec = find_record(&rk)
                .expect("read ledger")
                .expect("record exists");
            assert_eq!(rec.state, SlotState::Released);
            assert_eq!(rec.released_by, Some(ReleasedBy::Teardown));
        });
    }

    #[test]
    fn records_live_under_the_proxy_prefix_only() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            std::fs::write(&file, "{\n  \"a\": 1\n}\n").unwrap();
            write_proxy_key(&file, KEY, URL, AGENT).expect("write");

            assert!(model_relay_endpoints::endpoint_records("cline:")
                .expect("cline records")
                .is_empty());
            let proxy_records =
                model_relay_endpoints::endpoint_records(RECORD_PREFIX).expect("proxy records");
            assert_eq!(proxy_records.len(), 1);
            assert_eq!(proxy_records[0].1.origin, "");
        });
    }
}