openlatch-client 0.6.24

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
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
//! 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 — or a boolean flag set beside one ([`write_flag`]) —
//! 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 our value, freshly written.
    Written,
    /// The key already held our value, 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()
}

/// How a value we write is recorded in [`EndpointRecord::last_written`] and reported by
/// [`Observed::Ours`]: the URL itself, or `true`/`false`. A proxy key never holds the bare text
/// `true`, so the two never collide.
fn repr(v: &SlotValue) -> Option<String> {
    match v {
        SlotValue::Text(t) => Some(t.clone()),
        SlotValue::Bool(b) => Some(b.to_string()),
        SlotValue::Absent | SlotValue::Null => None,
    }
}

/// The JSON literal a value is spliced in as.
fn literal(v: &SlotValue) -> Result<String, OlError> {
    match v {
        SlotValue::Text(t) => {
            serde_json::to_string(t).map_err(|e| OlError::new(ERR_MODEL_RELAY_IO, e.to_string()))
        }
        SlotValue::Bool(b) => Ok(b.to_string()),
        SlotValue::Null => Ok("null".to_string()),
        SlotValue::Absent => Err(OlError::new(
            ERR_MODEL_RELAY_IO,
            "an absent value has no literal".to_string(),
        )),
    }
}

/// A property's value as a [`SlotValue`]; `None` for any other JSON value (a number, an object…).
fn slot_of(value: &Value) -> Option<SlotValue> {
    match value {
        Value::NullKeyword(_) => Some(SlotValue::Null),
        Value::StringLit(s) => Some(SlotValue::Text(s.value.to_string())),
        Value::BooleanLit(b) => Some(SlotValue::Bool(b.value)),
        _ => None,
    }
}

/// 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 `rec` says the key holds our write: live, with a value we wrote.
fn owns_key(rec: &EndpointRecord) -> bool {
    rec.is_live() && rec.last_written.is_some()
}

/// The keys the ledger says `agent` owns right now, as `(file, key)`, and whether its keys were
/// handed back instead — no live record, and one released by [`ReleasedBy::Teardown`]
/// (`uninstall`, the relay switched off). The wiring supervisor's drift check reads this: a key
/// handed back is not a key lost.
pub(crate) fn owned_keys(
    agent: &str,
) -> Result<(Vec<(std::path::PathBuf, String)>, bool), OlError> {
    let prefix = format!("{RECORD_PREFIX}{agent}:");
    let recs = model_relay_endpoints::endpoint_records(&prefix)?;
    let owned: Vec<_> = recs
        .iter()
        .filter(|(_, r)| owns_key(r))
        .filter_map(|(rk, r)| {
            let (key, _) = rk[prefix.len()..].split_once('@')?;
            Some((r.file.clone(), key.to_string()))
        })
        .collect();
    let handed_back = owned.is_empty()
        && recs
            .iter()
            .any(|(_, r)| r.released_by == Some(ReleasedBy::Teardown));
    Ok((owned, handed_back))
}

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

pub(crate) fn observe_key(file: &Path, key: &str, agent: &str) -> Result<Observed, OlError> {
    match env_name(key) {
        Some(name) => observe_env(file, name, agent).map(|(o, _)| o),
        None => observe_with_current(file, key, agent).map(|(o, _)| o),
    }
}

/// [`observe_key`], plus the key's current value as it sits in the file (`Absent` when there is no
/// file or no usable value) — what the write path splices against and records as the prior.
fn observe_with_current(
    file: &Path,
    key: &str,
    agent: &str,
) -> Result<(Observed, SlotValue), OlError> {
    let absent = |o: Observed| Ok((o, SlotValue::Absent));
    let bytes = match std::fs::read(file) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return absent(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 absent(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 absent(Observed::Unparseable(e.to_string())),
    };
    let parsed = match parse_to_ast(&raw, &collect_options(), &parse_options()) {
        Ok(p) => p,
        Err(e) => return absent(Observed::Unparseable(e.to_string())),
    };
    let obj = match parsed.value {
        None => return absent(Observed::Unset(SlotValue::Absent)),
        Some(Value::Object(obj)) => obj,
        Some(_) => {
            return absent(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 slot_of(&p.value) {
            Some(v) => v,
            None => return absent(Observed::Foreign(p.value.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) {
        let probe = SlotValue::Text(LAYOUT_PROBE_URL.to_string());
        if let Some(new) = splice_set(&raw, key, &probe, &SlotValue::Absent)? {
            if !reads_back(&new, key, &probe) {
                return absent(Observed::Unparseable(
                    preflight::SETTINGS_LAYOUT.to_string(),
                ));
            }
        }
    }

    let observed = match &current {
        SlotValue::Text(_) | SlotValue::Bool(_) => {
            let shown = repr(&current).unwrap_or_default();
            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(shown.as_str()) {
                Observed::Ours(shown)
            } else if current.is_unset() {
                Observed::Unset(current.clone())
            } else {
                // INCLUDING a 127.0.0.1 URL with no record: loopback is not authorship.
                Observed::Foreign(shown)
            }
        }
        SlotValue::Absent | SlotValue::Null => Observed::Unset(current.clone()),
    };
    Ok((observed, 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, json_value: &str) -> CreateOutcome {
    let content = format!("{{\n  \"{key}\": {json_value}\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> {
    write_setting(
        file,
        key,
        &SlotValue::Text(url.to_string()),
        parse_port(url)?,
        agent,
    )
}

/// Set a boolean flag beside a proxy key (`ProxyDelivery::SettingsKey::flags`), with the same
/// record, heal and byte-identical restore as the key itself. `port` is the relay port the flag
/// serves. A value the developer set themselves is never overwritten (D-34): it comes back as
/// [`KeyWrite::Foreign`] — the caller decides whether a foreign value that already equals ours is
/// good enough.
pub fn write_flag(
    file: &Path,
    key: &str,
    value: bool,
    port: u16,
    agent: &str,
) -> Result<KeyWrite, OlError> {
    write_setting(file, key, &SlotValue::Bool(value), port, agent)
}

fn write_setting(
    file: &Path,
    key: &str,
    ours: &SlotValue,
    port: u16,
    agent: &str,
) -> Result<KeyWrite, OlError> {
    let ours_repr = repr(ours).ok_or_else(|| {
        OlError::new(
            ERR_MODEL_RELAY_IO,
            format!("{key}: only a text or boolean value is written"),
        )
    })?;
    let json_value = literal(ours)?;
    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('@') || env_name(key).is_some() {
        return Err(OlError::new(
            ERR_MODEL_RELAY_IO,
            format!(
                "proxy settings key {key:?} must not contain '@' or start with \"{ENV_KEY_PREFIX}\""
            ),
        ));
    }
    let rk = record_key(agent, key, file);

    for _ in 0..crate::hooks::provider_endpoints::CONTENDED_ATTEMPTS {
        let (observed, current) = observe_with_current(file, key, agent)?;
        match &observed {
            // The heal (tamper item 2): a live record is the ledger's word that the key is ours,
            // so a value that replaced our write is overwritten and the recorded prior kept.
            // Without one — our value never went there, or was handed back — D-34 holds.
            Observed::Foreign(_) if find_record(&rk)?.is_some_and(|r| owns_key(&r)) => {}
            Observed::Foreign(v) => return Ok(KeyWrite::Foreign(v.clone())),
            Observed::Unparseable(why) => return Ok(KeyWrite::Unparseable(why.clone())),
            Observed::Ours(v) if *v == ours_repr => {
                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(_) | Observed::Ours(_) => current.clone(),
                // A foreign value reaches here only with a record: the arm above.
                Observed::Foreign(_) | Observed::Unparseable(_) => unreachable!("handled above"),
            },
        };

        model_relay_endpoints::put_endpoint(
            &rk,
            EndpointRecord {
                port,
                origin: String::new(),
                prior,
                last_written: Some(ours_repr.clone()),
                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, &json_value) {
                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 = current;
        let mut refused = false;
        let outcome = atomic::rewrite_existing_text(file, LIMITS, |raw| {
            match splice_set(raw, key, ours, &expect)? {
                Some(new) if !reads_back(&new, key, ours) => {
                    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> {
    if let Some(name) = env_name(key) {
        return release_env_key(file, name, agent, by);
    }
    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 nested sink (#734): `env.<NAME>` of a settings file
// ---------------------------------------------------------------------------

/// How a nested `env.<NAME>` value is spelled as a record key — `proxy:<agent>:env.<NAME>@<file>` —
/// and told apart from a top-level key on the way back out ([`observe_key`], [`release_proxy_key`]).
/// Unambiguous because [`write_setting`] refuses a top-level key spelled this way.
pub(crate) const ENV_KEY_PREFIX: &str = "env.";

/// The record-key spelling of `env.<name>`.
pub(crate) fn env_key(name: &str) -> String {
    format!("{ENV_KEY_PREFIX}{name}")
}

/// `Some(name)` for a record key naming `env.<name>`.
fn env_name(key: &str) -> Option<&str> {
    key.strip_prefix(ENV_KEY_PREFIX)
}

/// [`observe_with_current`] for `env.<name>`: the same verdicts against the same ledger, read
/// through the JSONC value rather than a top-level splice.
fn observe_env(file: &Path, name: &str, agent: &str) -> Result<(Observed, SlotValue), OlError> {
    let absent = |o: Observed| Ok((o, SlotValue::Absent));
    let bytes = match std::fs::read(file) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return absent(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 absent(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 absent(Observed::Unparseable(e.to_string())),
    };
    let root = match crate::hooks::jsonc::parse_settings_value(&raw) {
        Ok(serde_json::Value::Object(root)) => root,
        Ok(_) => {
            return absent(Observed::Unparseable(
                "the settings file is not a JSON object".to_string(),
            ))
        }
        Err(e) => return absent(Observed::Unparseable(e.message)),
    };
    let current = match root.get("env") {
        None => SlotValue::Absent,
        Some(serde_json::Value::Object(env)) => match env.get(name) {
            None => SlotValue::Absent,
            Some(serde_json::Value::Null) => SlotValue::Null,
            Some(serde_json::Value::String(t)) => SlotValue::Text(t.clone()),
            Some(other) => return absent(Observed::Foreign(other.to_string())),
        },
        Some(_) => {
            return absent(Observed::Unparseable(
                "the settings file's `env` is not an object".to_string(),
            ))
        }
    };
    let observed = match &current {
        SlotValue::Text(t) => {
            let rec = find_record(&record_key(agent, &env_key(name), file))?;
            if rec.as_ref().and_then(|r| r.last_written.as_deref()) == Some(t.as_str()) {
                Observed::Ours(t.clone())
            } else if current.is_unset() {
                Observed::Unset(current.clone())
            } else {
                // INCLUDING a 127.0.0.1 URL with no record: loopback is not authorship.
                Observed::Foreign(t.clone())
            }
        }
        _ => Observed::Unset(current.clone()),
    };
    Ok((observed, current))
}

/// [`write_proxy_key`] for `env.<name>` (`ProxyDelivery::SettingsEnvKey`): record before the write
/// commits, never overwrite a value OpenLatch did not write (D-34) unless a live record says the
/// key is ours (the heal, which keeps the recorded prior). The rest of the file is edited through
/// the JSONC CST, comments included.
pub fn write_env_key(file: &Path, name: &str, url: &str, agent: &str) -> Result<KeyWrite, OlError> {
    let port = parse_port(url)?;
    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 name.contains('@') {
        return Err(OlError::new(
            ERR_MODEL_RELAY_IO,
            format!("proxy settings key {name:?} must not contain '@'"),
        ));
    }
    let rk = record_key(agent, &env_key(name), file);
    let (observed, current) = observe_env(file, name, agent)?;
    match &observed {
        Observed::Foreign(_) if find_record(&rk)?.is_some_and(|r| owns_key(&r)) => {}
        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 => current.clone(),
    };
    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,
        },
    )?;
    // The value we observed is the one we replace: a save in between is somebody else's, and wins.
    let expect = match &current {
        SlotValue::Text(t) => Some(t.clone()),
        _ => None,
    };
    let write = atomic::atomic_rewrite_jsonc(file, |root| {
        if crate::hooks::jsonc::get_env_var_cst(root, name) != expect {
            return Err(OlError::new(
                ERR_MODEL_RELAY_SETTINGS,
                preflight::SETTINGS_CONTENDED.to_string(),
            ));
        }
        crate::hooks::jsonc::set_env_var_cst(root, name, url)
    });
    if let Err(e) = write {
        model_relay_endpoints::update_endpoint(&rk, |r| {
            r.state = SlotState::Released;
            r.released_by = Some(ReleasedBy::Wiring);
            r.changed_at = now_unix();
        })?;
        return Err(e);
    }
    model_relay_endpoints::update_endpoint(&rk, |r| r.state = SlotState::Wired)?;
    Ok(KeyWrite::Written)
}

/// [`release_proxy_key`] for `env.<name>`: only while the value is still the one we wrote, put the
/// recorded prior back, or remove the key (and an `env` this removal empties) when there was none.
fn release_env_key(file: &Path, name: &str, agent: &str, by: ReleasedBy) -> Result<bool, OlError> {
    let rk = record_key(agent, &env_key(name), 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();
        })?;
    }
    let Some(ours) = rec.last_written else {
        return Ok(false);
    };
    // The developer changed it, or the file is gone: their value stays, and nothing is rewritten.
    if !matches!(observe_env(file, name, agent)?.1, SlotValue::Text(ref t) if *t == ours) {
        return Ok(false);
    }
    let mut restored = false;
    atomic::atomic_rewrite_jsonc(file, |root| {
        if crate::hooks::jsonc::get_env_var_cst(root, name).as_deref() != Some(ours.as_str()) {
            return Ok(());
        }
        restored = true;
        match &rec.prior {
            SlotValue::Text(prior) => crate::hooks::jsonc::set_env_var_cst(root, name, prior),
            SlotValue::Absent | SlotValue::Null | SlotValue::Bool(_) => {
                crate::hooks::jsonc::remove_env_var_cst(root, name)
            }
        }
    })?;
    Ok(restored)
}

// ---------------------------------------------------------------------------
// 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,
    ours: &SlotValue,
    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 = literal(ours)?;

    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) => slot_of(&p.value),
    };
    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 = slot_of(&prop.value)
        .filter(|v| matches!(v, SlotValue::Text(_) | SlotValue::Bool(_)))
        .and_then(|v| repr(&v))
        .is_some_and(|v| Some(v.as_str()) == ours);
    if !holds_ours {
        return Ok(None);
    }

    match prior {
        SlotValue::Text(_) | SlotValue::Null | SlotValue::Bool(_) => {
            let json = literal(prior)?;
            let vr = prop.value.range();
            Ok(Some(format!(
                "{}{json}{}",
                &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";

    /// A flag is written as a JSON boolean, read back as ours (`"true"`), and released to the
    /// developer's prior: absent → removed, their own `false` → never overwritten.
    #[test]
    fn a_flag_is_a_boolean_with_the_same_record_and_restore() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            let seed = "{\n  // mine\n  \"a\": 1\n}\n";
            std::fs::write(&file, seed).unwrap();

            assert_eq!(
                write_flag(&file, "x.flag", true, 7600, AGENT).expect("write"),
                KeyWrite::Written
            );
            let raw = std::fs::read_to_string(&file).unwrap();
            assert!(raw.contains("\"x.flag\": true"), "{raw}");
            assert!(raw.contains("// mine"), "{raw}");
            assert_eq!(
                observe_key(&file, "x.flag", AGENT).expect("observe"),
                Observed::Ours("true".into())
            );
            assert_eq!(
                write_flag(&file, "x.flag", true, 7600, AGENT).expect("again"),
                KeyWrite::AlreadyOurs
            );
            assert!(
                release_proxy_key(&file, "x.flag", AGENT, ReleasedBy::Teardown).expect("release")
            );
            assert_eq!(std::fs::read_to_string(&file).unwrap(), seed);

            let theirs = "{\n  \"x.flag\": false\n}\n";
            std::fs::write(&file, theirs).unwrap();
            assert_eq!(
                write_flag(&file, "x.flag", true, 7600, AGENT).expect("write"),
                KeyWrite::Foreign("false".into())
            );
            assert_eq!(std::fs::read_to_string(&file).unwrap(), theirs);
        });
    }

    /// #734: `env.<NAME>` rides the same ledger — written, read back as ours, released byte for
    /// byte whether or not the file had an `env` before; a top-level key spelled `env.` is refused
    /// so the record key stays unambiguous.
    #[test]
    fn an_env_key_is_written_and_restored_byte_for_byte() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            for seed in [
                "{\n  // mine\n  \"a\": 1\n}\n",
                "{\n  \"env\": {\n    \"FOO\": \"bar\"\n  },\n  \"a\": 1\n}\n",
            ] {
                std::fs::write(&file, seed).unwrap();
                assert_eq!(
                    write_env_key(&file, "HTTPS_PROXY", URL, AGENT).expect("write"),
                    KeyWrite::Written
                );
                let key = env_key("HTTPS_PROXY");
                assert_eq!(
                    observe_key(&file, &key, AGENT).expect("observe"),
                    Observed::Ours(URL.into())
                );
                assert_eq!(
                    write_env_key(&file, "HTTPS_PROXY", URL, AGENT).expect("again"),
                    KeyWrite::AlreadyOurs
                );
                assert!(
                    release_proxy_key(&file, &key, AGENT, ReleasedBy::Teardown).expect("release")
                );
                assert_eq!(std::fs::read_to_string(&file).unwrap(), seed);
            }
            assert!(write_proxy_key(&file, "env.HTTPS_PROXY", URL, AGENT).is_err());
        });
    }

    /// #734 / D-34: a foreign `env.HTTPS_PROXY` is never overwritten or recorded; one that
    /// replaced our live write is the heal, which keeps the recorded prior (none), so the release
    /// removes the key rather than "restoring" the tampered value.
    #[test]
    fn a_foreign_env_key_is_refused_and_a_tampered_one_healed_to_its_prior() {
        with_openlatch_dir(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let file = dir.path().join("settings.json");
            let corp = "{\n  \"env\": {\n    \"HTTPS_PROXY\": \"http://corp:3128\"\n  }\n}\n";
            std::fs::write(&file, corp).unwrap();
            assert_eq!(
                write_env_key(&file, "HTTPS_PROXY", URL, AGENT).expect("write"),
                KeyWrite::Foreign("http://corp:3128".into())
            );
            assert_eq!(std::fs::read_to_string(&file).unwrap(), corp);
            assert!(model_relay_endpoints::endpoint_records(RECORD_PREFIX)
                .expect("ledger")
                .is_empty());

            let seed = "{\n  \"a\": 1\n}\n";
            std::fs::write(&file, seed).unwrap();
            write_env_key(&file, "HTTPS_PROXY", URL, AGENT).expect("ours");
            let tampered = std::fs::read_to_string(&file)
                .unwrap()
                .replace(URL, "http://other:1");
            std::fs::write(&file, tampered).unwrap();
            assert_eq!(
                write_env_key(&file, "HTTPS_PROXY", URL, AGENT).expect("heal"),
                KeyWrite::Written
            );
            let key = env_key("HTTPS_PROXY");
            assert!(release_proxy_key(&file, &key, AGENT, ReleasedBy::Teardown).expect("release"));
            assert_eq!(std::fs::read_to_string(&file).unwrap(), seed);
        });
    }

    /// 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, &SlotValue::Text(URL.into())));

            // 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, &SlotValue::Text(URL.into())),
                    "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, "");
        });
    }
}