xchecker-utils 1.2.0

Foundation utilities for xchecker
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
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
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
//! File locking system for xchecker with advisory semantics and crash recovery
//!
//! This module provides exclusive file locking per spec ID directory to prevent
//! concurrent execution. The locking is advisory and coordinates xchecker processes
//! but is not a security boundary.

use crate::atomic_write::write_file_atomic;
pub use crate::error::LockError;
use crate::types::{DriftPair, LockDrift};
use anyhow::Result;
use camino::Utf8PathBuf;
use chrono::{DateTime, Utc};
use fd_lock::RwLock;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};

/// Default age threshold for considering a lock stale (in seconds)
const DEFAULT_STALE_THRESHOLD_SECS: u64 = 3600; // 1 hour

/// Lock information stored in the lock file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockInfo {
    /// Process ID that created the lock
    pub pid: u32,
    /// Process start time (seconds since UNIX epoch)
    pub start_time: u64,
    /// Timestamp when the lock was created (seconds since UNIX epoch)
    pub created_at: u64,
    /// Spec ID being locked
    pub spec_id: String,
    /// xchecker version that created the lock
    pub xchecker_version: String,
}

/// `XChecker` lockfile for reproducibility tracking (schema v1)
/// Pins model, CLI version, and schema version to detect drift
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XCheckerLock {
    /// Schema version for this lockfile format
    pub schema_version: String,
    /// RFC3339 UTC timestamp when the lockfile was created
    pub created_at: DateTime<Utc>,
    /// Full model name that was used (e.g., "haiku")
    pub model_full_name: String,
    /// Claude CLI version that was used
    pub claude_cli_version: String,
}

/// Context for current run to compare against lockfile
#[derive(Debug, Clone)]
pub struct RunContext {
    pub model_full_name: String,
    pub claude_cli_version: String,
    pub schema_version: String,
}

impl XCheckerLock {
    /// Create a new lockfile with current context
    #[must_use]
    pub fn new(model_full_name: String, claude_cli_version: String) -> Self {
        Self {
            schema_version: "1".to_string(),
            created_at: Utc::now(),
            model_full_name,
            claude_cli_version,
        }
    }

    /// Detect drift between locked values and current run context
    /// Returns None if no drift detected, Some(LockDrift) if drift exists
    #[must_use]
    pub fn detect_drift(&self, current: &RunContext) -> Option<LockDrift> {
        let mut drift = LockDrift {
            model_full_name: None,
            claude_cli_version: None,
            schema_version: None,
        };

        // Check model drift
        if self.model_full_name != current.model_full_name {
            drift.model_full_name = Some(DriftPair {
                locked: self.model_full_name.clone(),
                current: current.model_full_name.clone(),
            });
        }

        // Check Claude CLI version drift
        if self.claude_cli_version != current.claude_cli_version {
            drift.claude_cli_version = Some(DriftPair {
                locked: self.claude_cli_version.clone(),
                current: current.claude_cli_version.clone(),
            });
        }

        // Check schema version drift
        if self.schema_version != current.schema_version {
            drift.schema_version = Some(DriftPair {
                locked: self.schema_version.clone(),
                current: current.schema_version.clone(),
            });
        }

        // Return None if no drift detected
        if drift.model_full_name.is_none()
            && drift.claude_cli_version.is_none()
            && drift.schema_version.is_none()
        {
            None
        } else {
            Some(drift)
        }
    }

    /// Load lockfile from spec directory
    pub fn load(spec_id: &str) -> Result<Option<Self>, io::Error> {
        let lock_path = Self::get_lock_path(spec_id);

        if !lock_path.exists() {
            return Ok(None);
        }

        let content = fs::read_to_string(&lock_path)?;
        let lock: Self = serde_json::from_str(&content)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

        Ok(Some(lock))
    }

    /// Save lockfile to spec directory
    pub fn save(&self, spec_id: &str) -> Result<(), io::Error> {
        let lock_path = Self::get_lock_path_utf8(spec_id);

        let json = serde_json::to_string_pretty(self)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

        write_file_atomic(&lock_path, &json).map_err(io::Error::other)?;

        Ok(())
    }

    /// Get the path to the lockfile for a spec ID
    fn get_lock_path(spec_id: &str) -> PathBuf {
        Self::get_lock_path_utf8(spec_id).into_std_path_buf()
    }

    /// Get the UTF-8 path to the lockfile for a spec ID
    fn get_lock_path_utf8(spec_id: &str) -> Utf8PathBuf {
        crate::paths::spec_root(spec_id).join("lock.json")
    }
}

/// File lock manager for spec directories
pub struct FileLock {
    /// Path to the lock file
    lock_path: PathBuf,
    /// File descriptor lock (held while active)
    _fd_lock: Option<Box<RwLock<fs::File>>>,
    /// Lock information
    lock_info: LockInfo,
}

impl FileLock {
    /// Attempt to acquire an exclusive lock for the given spec ID
    ///
    /// Uses atomic O_EXCL/create_new semantics to prevent TOCTOU race conditions.
    /// If the lock file already exists, validates the existing lock before deciding
    /// whether to override it.
    ///
    /// # Arguments
    /// * `spec_id` - The spec ID to lock
    /// * `force` - Whether to override stale locks
    /// * `ttl_seconds` - Time-to-live for lock staleness detection (None uses default)
    ///
    /// # Returns
    /// * `Ok(FileLock)` - Successfully acquired lock
    /// * `Err(LockError)` - Failed to acquire lock (concurrent execution, stale lock, etc.)
    pub fn acquire(
        spec_id: &str,
        force: bool,
        ttl_seconds: Option<u64>,
    ) -> Result<Self, LockError> {
        let spec_root = crate::paths::spec_root(spec_id);

        // Ensure the spec directory exists (ignore benign races)
        crate::paths::ensure_dir_all(&spec_root).map_err(|e| LockError::AcquisitionFailed {
            reason: format!("Failed to create spec directory: {e}"),
        })?;

        let lock_path = Self::get_lock_path(spec_id);
        let ttl = ttl_seconds.unwrap_or(DEFAULT_STALE_THRESHOLD_SECS);

        // Attempt atomic lock acquisition with retries for stale lock handling
        Self::acquire_with_retry(spec_id, &lock_path, force, ttl, 3)
    }

    /// Internal helper for atomic lock acquisition with retry logic
    fn acquire_with_retry(
        spec_id: &str,
        lock_path: &Path,
        force: bool,
        ttl_seconds: u64,
        max_retries: u32,
    ) -> Result<Self, LockError> {
        for attempt in 0..max_retries {
            // Create lock info for this attempt
            let lock_info = LockInfo {
                pid: process::id(),
                start_time: Self::get_process_start_time()?,
                created_at: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                spec_id: spec_id.to_string(),
                xchecker_version: env!("CARGO_PKG_VERSION").to_string(),
            };

            // Attempt atomic file creation with O_EXCL semantics (create_new)
            match fs::OpenOptions::new()
                .create_new(true)
                .write(true)
                .open(lock_path)
            {
                Ok(lock_file) => {
                    // Successfully created the file atomically - no race possible
                    return Self::finalize_lock(lock_path.to_path_buf(), lock_file, lock_info);
                }
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                    // Lock file exists - validate it
                    match Self::check_existing_lock(lock_path, spec_id, force, ttl_seconds) {
                        Ok(()) => {
                            // Lock is stale/overridable - attempt atomic removal and retry
                            match Self::try_remove_stale_lock(lock_path, spec_id) {
                                Ok(()) => {
                                    // Immediately attempt acquisition after removing stale lock
                                    match fs::OpenOptions::new()
                                        .create_new(true)
                                        .write(true)
                                        .open(lock_path)
                                    {
                                        Ok(lock_file) => {
                                            return Self::finalize_lock(
                                                lock_path.to_path_buf(),
                                                lock_file,
                                                lock_info,
                                            );
                                        }
                                        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                                            // Another process grabbed it - apply backoff if retries remain
                                            if attempt + 1 < max_retries {
                                                let base_delay_ms = 10u64
                                                    .saturating_mul(2u64.saturating_pow(attempt));
                                                // Deterministic jitter based on PID to avoid lockstep retries
                                                // without requiring RNG (0-6ms based on attempt and PID)
                                                let jitter_ms = ((attempt as u64)
                                                    .wrapping_mul(3)
                                                    .wrapping_add((process::id() as u64) % 7))
                                                    % 7;
                                                let delay_ms =
                                                    base_delay_ms.saturating_add(jitter_ms);
                                                std::thread::sleep(
                                                    std::time::Duration::from_millis(
                                                        delay_ms.min(100),
                                                    ),
                                                );
                                                continue;
                                            }
                                            // Max retries reached after another process grabbed lock
                                            return Err(LockError::AcquisitionFailed {
                                                reason: format!(
                                                    "Max retries exceeded for spec '{}': another process acquired lock immediately after stale removal",
                                                    spec_id
                                                ),
                                            });
                                        }
                                        Err(e) => {
                                            return Err(LockError::AcquisitionFailed {
                                                reason: format!(
                                                    "Failed to create lock for spec '{}' after removing stale lock: {e}",
                                                    spec_id
                                                ),
                                            });
                                        }
                                    }
                                }
                                Err(e) => {
                                    // Propagate the specific stale-removal error
                                    return Err(e);
                                }
                            }
                        }
                        Err(e) => return Err(e),
                    }
                }
                Err(e) => {
                    return Err(LockError::AcquisitionFailed {
                        reason: format!(
                            "Failed to create lock file for spec '{}' at '{}': {e}",
                            spec_id,
                            lock_path.display()
                        ),
                    });
                }
            }
        }

        // Reachable only when max_retries == 0 (edge case). All other paths return/continue
        // within the loop. This provides a safety net for the zero-retry edge case.
        Err(LockError::AcquisitionFailed {
            reason: format!(
                "Max retries ({}) exceeded for lock acquisition on spec '{}'",
                max_retries, spec_id
            ),
        })
    }

    /// Finalize lock acquisition by writing lock info and acquiring fd_lock
    fn finalize_lock(
        lock_path: PathBuf,
        lock_file: fs::File,
        lock_info: LockInfo,
    ) -> Result<Self, LockError> {
        let lock_json =
            serde_json::to_string_pretty(&lock_info).map_err(|e| LockError::AcquisitionFailed {
                reason: format!(
                    "Failed to serialize lock info for spec '{}': {e}",
                    lock_info.spec_id
                ),
            })?;

        // Acquire exclusive file descriptor lock and write in one step
        let mut rw_lock = Box::new(RwLock::new(lock_file));
        {
            let fd_lock = rw_lock
                .try_write()
                .map_err(|_e| LockError::ConcurrentExecution {
                    spec_id: lock_info.spec_id.clone(),
                    pid: 0, // Unknown PID since we couldn't read the lock
                    created_ago: "unknown".to_string(),
                })?;

            // Write to the locked file
            let mut file_ref = &*fd_lock;
            file_ref
                .write_all(lock_json.as_bytes())
                .map_err(|e| LockError::AcquisitionFailed {
                    reason: format!(
                        "Failed to write lock info for spec '{}': {e}",
                        lock_info.spec_id
                    ),
                })?;
            file_ref.flush().map_err(|e| LockError::AcquisitionFailed {
                reason: format!(
                    "Failed to flush lock file for spec '{}': {e}",
                    lock_info.spec_id
                ),
            })?;

            // Sync to disk for crash-resilience (small file, acceptable cost)
            file_ref
                .sync_all()
                .map_err(|e| LockError::AcquisitionFailed {
                    reason: format!(
                        "Failed to sync lock file for spec '{}': {e}",
                        lock_info.spec_id
                    ),
                })?;
        }

        Ok(Self {
            lock_path,
            _fd_lock: Some(rw_lock),
            lock_info,
        })
    }

    /// Attempt to remove a stale lock file atomically
    ///
    /// Uses rename-to-stale then delete pattern to minimize race window.
    /// Treats `NotFound` as success since another process may have already removed it.
    /// Includes PID in stale filename to prevent collision under high parallelism.
    fn try_remove_stale_lock(lock_path: &Path, spec_id: &str) -> Result<(), LockError> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis();
        let pid = process::id();
        let stale_path = lock_path.with_extension(format!("stale.{timestamp}.{pid}"));

        // Atomic rename to mark as stale
        match fs::rename(lock_path, &stale_path) {
            Ok(()) => {
                // Best-effort cleanup of stale file (ignore errors)
                let _ = fs::remove_file(&stale_path);
                Ok(())
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                // Another process already removed/renamed it - that's fine
                Ok(())
            }
            Err(e) => Err(LockError::AcquisitionFailed {
                reason: format!("Failed to rename stale lock for spec '{spec_id}': {e}"),
            }),
        }
    }

    /// Check if a lock exists for the given spec ID
    #[must_use]
    #[allow(dead_code)] // Lock introspection utility
    pub fn exists(spec_id: &str) -> bool {
        let lock_path = Self::get_lock_path(spec_id);
        lock_path.exists()
    }

    /// Get information about an existing lock (if any)
    pub fn get_lock_info(spec_id: &str) -> Result<Option<LockInfo>, LockError> {
        let lock_path = Self::get_lock_path(spec_id);

        if !lock_path.exists() {
            return Ok(None);
        }

        let lock_content =
            fs::read_to_string(&lock_path).map_err(|e| LockError::CorruptedLock {
                reason: format!("Failed to read lock file: {e}"),
            })?;

        let lock_info: LockInfo =
            serde_json::from_str(&lock_content).map_err(|e| LockError::CorruptedLock {
                reason: format!("Failed to parse lock file: {e}"),
            })?;

        Ok(Some(lock_info))
    }

    /// Release the lock (called automatically on drop)
    #[allow(dead_code)] // Lock management utility
    pub fn release(mut self) -> Result<(), LockError> {
        // Drop the file descriptor lock first
        self._fd_lock.take();

        // Remove the lock file
        if self.lock_path.exists() {
            fs::remove_file(&self.lock_path).map_err(|e| LockError::ReleaseFailed {
                reason: format!("Failed to remove lock file: {e}"),
            })?;
        }

        Ok(())
    }

    /// Get the spec ID for this lock
    #[must_use]
    #[allow(dead_code)] // Lock introspection utility
    pub fn spec_id(&self) -> &str {
        &self.lock_info.spec_id
    }

    /// Get the lock information
    #[must_use]
    #[allow(dead_code)] // Lock introspection utility
    pub const fn lock_info(&self) -> &LockInfo {
        &self.lock_info
    }

    /// Get the path to the lock file for a spec ID
    fn get_lock_path(spec_id: &str) -> PathBuf {
        crate::paths::spec_root(spec_id).as_std_path().join(".lock")
    }

    /// Check an existing lock and determine if it should be overridden
    ///
    /// Includes retry logic for empty/partial lockfile reads to handle the case where
    /// another process has just created the file but hasn't written content yet.
    fn check_existing_lock(
        lock_path: &Path,
        spec_id: &str,
        force: bool,
        ttl_seconds: u64,
    ) -> Result<(), LockError> {
        // Retry parameters for handling concurrent initialization
        const MAX_READ_RETRIES: u32 = 3;
        const READ_RETRY_DELAY_MS: u64 = 10;

        for attempt in 0..MAX_READ_RETRIES {
            let lock_content = match fs::read_to_string(lock_path) {
                Ok(content) => content,
                Err(e) if e.kind() == io::ErrorKind::NotFound => {
                    // Lock was removed between create_new(AlreadyExists) and read.
                    // Treat as "no lock"; caller will retry acquisition.
                    return Ok(());
                }
                Err(e) => {
                    // IO errors during read might be transient (file being written)
                    if attempt + 1 < MAX_READ_RETRIES {
                        std::thread::sleep(std::time::Duration::from_millis(READ_RETRY_DELAY_MS));
                        continue;
                    }
                    return Err(LockError::CorruptedLock {
                        reason: format!("Failed to read existing lock for spec '{}': {e}", spec_id),
                    });
                }
            };

            // Check for empty content (file exists but not yet written)
            if lock_content.is_empty() {
                if attempt + 1 < MAX_READ_RETRIES {
                    std::thread::sleep(std::time::Duration::from_millis(READ_RETRY_DELAY_MS));
                    continue;
                }
                return Err(LockError::CorruptedLock {
                    reason: format!(
                        "Lock file for spec '{}' is empty (may be initializing)",
                        spec_id
                    ),
                });
            }

            // Try to parse the JSON content
            match serde_json::from_str::<LockInfo>(&lock_content) {
                Ok(existing_lock) => {
                    // Successfully parsed - proceed with lock validation
                    return Self::validate_existing_lock(
                        &existing_lock,
                        spec_id,
                        force,
                        ttl_seconds,
                    );
                }
                Err(e) => {
                    // Check if this looks like a partial/incomplete JSON (EOF error)
                    let is_likely_incomplete = e.is_eof()
                        || lock_content.trim().is_empty()
                        || (lock_content.starts_with('{') && !lock_content.contains('}'));

                    // Only retry if it looks like the file might be mid-write
                    if is_likely_incomplete && attempt + 1 < MAX_READ_RETRIES {
                        std::thread::sleep(std::time::Duration::from_millis(READ_RETRY_DELAY_MS));
                        continue;
                    }

                    return Err(LockError::CorruptedLock {
                        reason: format!(
                            "Failed to parse existing lock for spec '{}': {e}",
                            spec_id
                        ),
                    });
                }
            }
        }
        // Note: This is unreachable since MAX_READ_RETRIES > 0 and all paths return.
        // Kept for safety if MAX_READ_RETRIES is ever changed to 0.
        unreachable!("check_existing_lock loop exhausted without returning")
    }

    /// Validate an existing lock and determine if it should be overridden
    fn validate_existing_lock(
        existing_lock: &LockInfo,
        spec_id: &str,
        force: bool,
        ttl_seconds: u64,
    ) -> Result<(), LockError> {
        // Calculate lock age (handle future timestamps gracefully - clock skew)
        let now_secs = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let lock_age = now_secs.saturating_sub(existing_lock.created_at);

        let is_stale = lock_age > ttl_seconds;

        // Check if the process is still running
        if Self::is_process_running(existing_lock.pid) {
            // Process is running - this is a fresh lock
            if !force {
                let created_ago = Self::format_duration_since(existing_lock.created_at);
                return Err(LockError::ConcurrentExecution {
                    spec_id: spec_id.to_string(),
                    pid: existing_lock.pid,
                    created_ago,
                });
            }
            // Force allows overriding even fresh locks
            return Ok(());
        }

        // Process is not running - check staleness
        if is_stale {
            if force {
                // Force flag allows overriding stale locks
                Ok(())
            } else {
                Err(LockError::StaleLock {
                    spec_id: spec_id.to_string(),
                    pid: existing_lock.pid,
                    age_secs: lock_age,
                })
            }
        } else {
            // Lock is recent but process is dead - fail without force
            if force {
                Ok(())
            } else {
                let created_ago = Self::format_duration_since(existing_lock.created_at);
                Err(LockError::ConcurrentExecution {
                    spec_id: spec_id.to_string(),
                    pid: existing_lock.pid,
                    created_ago,
                })
            }
        }
    }

    /// Check if a process with the given PID is still running
    fn is_process_running(pid: u32) -> bool {
        #[cfg(unix)]
        {
            // On Unix systems, use kill(pid, 0) to check if process exists
            // Returns 0 if process exists and we can signal it
            // Returns -1 with ESRCH if process doesn't exist
            // Returns -1 with EPERM if process exists but we lack permission
            let rc = unsafe { libc::kill(pid as i32, 0) };
            if rc == 0 {
                true
            } else {
                // If EPERM, the process exists but we can't signal it
                matches!(
                    io::Error::last_os_error().raw_os_error(),
                    Some(code) if code == libc::EPERM
                )
            }
        }

        #[cfg(windows)]
        {
            // On Windows, try to open the process handle and check if it's still running
            use winapi::um::handleapi::CloseHandle;
            use winapi::um::minwinbase::STILL_ACTIVE;
            use winapi::um::processthreadsapi::{GetExitCodeProcess, OpenProcess};
            use winapi::um::winnt::PROCESS_QUERY_LIMITED_INFORMATION;

            unsafe {
                // Use PROCESS_QUERY_LIMITED_INFORMATION which is sufficient for GetExitCodeProcess
                // and works with more processes than PROCESS_QUERY_INFORMATION
                let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
                if handle.is_null() {
                    return false;
                }

                // Check if the process is still running by getting its exit code
                let mut exit_code: u32 = 0;
                let result = GetExitCodeProcess(handle, &mut exit_code);
                CloseHandle(handle);

                // If GetExitCodeProcess fails, assume process is not running
                if result == 0 {
                    return false;
                }

                // STILL_ACTIVE (259) means the process is still running
                exit_code == STILL_ACTIVE
            }
        }

        #[cfg(not(any(unix, windows)))]
        {
            // Fallback: assume process is running (conservative approach)
            true
        }
    }

    /// Get the start time of the current process (best effort)
    fn get_process_start_time() -> Result<u64, LockError> {
        // This is a best-effort implementation
        // In practice, we use the current time as an approximation
        Ok(SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs())
    }

    /// Format a duration since a timestamp in a human-readable way
    fn format_duration_since(timestamp: u64) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let duration = now.saturating_sub(timestamp);

        if duration < 60 {
            format!("{duration}s")
        } else if duration < 3600 {
            format!("{}m", duration / 60)
        } else if duration < 86400 {
            format!("{}h", duration / 3600)
        } else {
            format!("{}d", duration / 86400)
        }
    }
}

impl std::fmt::Debug for FileLock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FileLock")
            .field("lock_path", &self.lock_path)
            .field("lock_info", &self.lock_info)
            .field("_fd_lock", &"<RwLock>")
            .finish()
    }
}

impl Drop for FileLock {
    /// Automatically release the lock when the `FileLock` is dropped
    fn drop(&mut self) {
        // Drop the file descriptor lock first
        self._fd_lock.take();

        // Remove the lock file (ignore errors in drop)
        if self.lock_path.exists() {
            let _ = fs::remove_file(&self.lock_path);
        }
    }
}

/// Utility functions for lock management
pub mod utils {
    use super::{
        DEFAULT_STALE_THRESHOLD_SECS, FileLock, LockError, Result, SystemTime, UNIX_EPOCH, fs,
    };

    /// Check if clean operation should be allowed (no active locks unless forced)
    pub fn can_clean(
        spec_id: &str,
        force: bool,
        ttl_seconds: Option<u64>,
    ) -> Result<(), LockError> {
        let ttl = ttl_seconds.unwrap_or(DEFAULT_STALE_THRESHOLD_SECS);
        if let Some(lock_info) = FileLock::get_lock_info(spec_id)? {
            if FileLock::is_process_running(lock_info.pid) {
                if force {
                    // Force flag allows cleaning even with active locks (--hard --force)
                    return Ok(());
                }
                return Err(LockError::ConcurrentExecution {
                    spec_id: spec_id.to_string(),
                    pid: lock_info.pid,
                    created_ago: FileLock::format_duration_since(lock_info.created_at),
                });
            }

            // Process is dead, check if we should allow cleaning
            if !force {
                let lock_age = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    - lock_info.created_at;

                if lock_age <= ttl {
                    return Err(LockError::StaleLock {
                        spec_id: spec_id.to_string(),
                        pid: lock_info.pid,
                        age_secs: lock_age,
                    });
                }
            }
        }

        Ok(())
    }

    /// Force remove a lock file (for emergency cleanup)
    #[allow(dead_code)] // Lock cleanup utility for CLI commands
    pub fn force_remove_lock(spec_id: &str) -> Result<(), LockError> {
        let lock_path = FileLock::get_lock_path(spec_id);

        if lock_path.exists() {
            fs::remove_file(&lock_path).map_err(|e| LockError::ReleaseFailed {
                reason: format!("Failed to force remove lock: {e}"),
            })?;
        }

        Ok(())
    }
}

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

    use std::fs;
    use tempfile::TempDir;

    fn setup_test_env() -> TempDir {
        crate::paths::with_isolated_home()
    }

    #[test]
    fn test_lock_acquisition_and_release() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-acquisition-123";

        // Should be able to acquire lock
        let lock = FileLock::acquire(spec_id, false, None).unwrap();
        assert_eq!(lock.spec_id(), spec_id);

        // The lock file should exist while the lock is held
        let lock_path = FileLock::get_lock_path(spec_id);
        assert!(
            lock_path.exists(),
            "Lock file should exist at: {lock_path:?}"
        );
        assert!(FileLock::exists(spec_id));

        // Should not be able to acquire another lock for same spec
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());

        // Release the lock
        lock.release().unwrap();
        assert!(!FileLock::exists(spec_id));

        // Should be able to acquire again after release
        let _lock2 = FileLock::acquire(spec_id, false, None).unwrap();
    }

    #[test]
    fn test_lock_info_serialization() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-serialization-456";
        let _lock = FileLock::acquire(spec_id, false, None).unwrap();

        // Should be able to read lock info
        let lock_info = FileLock::get_lock_info(spec_id).unwrap().unwrap();
        assert_eq!(lock_info.spec_id, spec_id);
        assert_eq!(lock_info.pid, process::id());
        assert!(!lock_info.xchecker_version.is_empty());
    }

    #[test]
    fn test_automatic_cleanup_on_drop() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-cleanup-789";

        {
            let _lock = FileLock::acquire(spec_id, false, None).unwrap();
            assert!(FileLock::exists(spec_id));
        } // lock goes out of scope here

        // Lock should be automatically cleaned up
        assert!(!FileLock::exists(spec_id));
    }

    #[test]
    fn test_force_override_stale_lock() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-stale-override";

        // Create a lock file manually with old timestamp
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        let old_lock_info = LockInfo {
            pid: 99999, // Non-existent PID
            start_time: 0,
            created_at: 0, // Very old timestamp
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&old_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Should fail without force
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), LockError::StaleLock { .. }));

        // Should succeed with force
        let lock = FileLock::acquire(spec_id, true, None).unwrap();
        assert_eq!(lock.spec_id(), spec_id);
    }

    #[test]
    fn test_clean_operation_checks() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-clean-checks";

        // Should be able to clean when no lock exists
        assert!(utils::can_clean(spec_id, false, None).is_ok());

        // Acquire a lock
        let _lock = FileLock::acquire(spec_id, false, None).unwrap();

        // Should not be able to clean with active lock
        let result = utils::can_clean(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            LockError::ConcurrentExecution { .. }
        ));

        // Should be able to clean with force (--hard --force overrides active locks)
        assert!(utils::can_clean(spec_id, true, None).is_ok());
    }

    #[test]
    fn test_lock_path_generation() {
        let _home = crate::paths::with_isolated_home();
        let spec_id = "my-test-spec";
        let expected_path = crate::paths::spec_root(spec_id).as_std_path().join(".lock");
        assert_eq!(FileLock::get_lock_path(spec_id), expected_path);
    }

    #[test]
    fn test_duration_formatting() {
        assert_eq!(
            FileLock::format_duration_since(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    - 30
            ),
            "30s"
        );
        assert_eq!(
            FileLock::format_duration_since(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    - 120
            ),
            "2m"
        );
        assert_eq!(
            FileLock::format_duration_since(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    - 7200
            ),
            "2h"
        );
    }

    #[test]
    fn test_xchecker_lock_creation() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        assert_eq!(lock.schema_version, "1");
        assert_eq!(lock.model_full_name, "haiku");
        assert_eq!(lock.claude_cli_version, "0.8.1");
    }

    #[test]
    fn test_xchecker_lock_no_drift() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        let context = RunContext {
            model_full_name: "haiku".to_string(),
            claude_cli_version: "0.8.1".to_string(),
            schema_version: "1".to_string(),
        };

        let drift = lock.detect_drift(&context);
        assert!(drift.is_none(), "Expected no drift when values match");
    }

    #[test]
    fn test_xchecker_lock_model_drift() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        let context = RunContext {
            model_full_name: "sonnet".to_string(),
            claude_cli_version: "0.8.1".to_string(),
            schema_version: "1".to_string(),
        };

        let drift = lock.detect_drift(&context).expect("Expected drift");
        assert!(drift.model_full_name.is_some());
        assert!(drift.claude_cli_version.is_none());
        assert!(drift.schema_version.is_none());
    }

    // ===== Edge Case Tests for Task 9.7 =====
    // (Tests already exist above, keeping only the serialization roundtrip test)

    #[test]
    fn test_lock_info_serialization_roundtrip() {
        let lock_info = LockInfo {
            pid: 12345,
            start_time: 1234567890,
            created_at: 1234567890,
            spec_id: "test-spec".to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        // Serialize and deserialize
        let json = serde_json::to_string(&lock_info).unwrap();
        let deserialized: LockInfo = serde_json::from_str(&json).unwrap();

        assert_eq!(lock_info.pid, deserialized.pid);
        assert_eq!(lock_info.start_time, deserialized.start_time);
        assert_eq!(lock_info.created_at, deserialized.created_at);
        assert_eq!(lock_info.spec_id, deserialized.spec_id);
        assert_eq!(lock_info.xchecker_version, deserialized.xchecker_version);
    }

    #[test]
    fn test_xchecker_lock_cli_version_drift() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        let context = RunContext {
            model_full_name: "haiku".to_string(),
            claude_cli_version: "0.9.0".to_string(),
            schema_version: "1".to_string(),
        };

        let drift = lock.detect_drift(&context).expect("Expected drift");
        assert!(drift.model_full_name.is_none());
        assert!(drift.claude_cli_version.is_some());
        assert!(drift.schema_version.is_none());

        let cli_drift = drift.claude_cli_version.unwrap();
        assert_eq!(cli_drift.locked, "0.8.1");
        assert_eq!(cli_drift.current, "0.9.0");
    }

    #[test]
    fn test_xchecker_lock_schema_version_drift() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        let context = RunContext {
            model_full_name: "haiku".to_string(),
            claude_cli_version: "0.8.1".to_string(),
            schema_version: "2".to_string(),
        };

        let drift = lock.detect_drift(&context).expect("Expected drift");
        assert!(drift.model_full_name.is_none());
        assert!(drift.claude_cli_version.is_none());
        assert!(drift.schema_version.is_some());

        let schema_drift = drift.schema_version.unwrap();
        assert_eq!(schema_drift.locked, "1");
        assert_eq!(schema_drift.current, "2");
    }

    #[test]
    fn test_xchecker_lock_multiple_drift() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        let context = RunContext {
            model_full_name: "sonnet".to_string(),
            claude_cli_version: "0.9.0".to_string(),
            schema_version: "2".to_string(),
        };

        let drift = lock.detect_drift(&context).expect("Expected drift");
        assert!(drift.model_full_name.is_some());
        assert!(drift.claude_cli_version.is_some());
        assert!(drift.schema_version.is_some());
    }

    #[test]
    fn test_xchecker_lock_save_and_load() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-lockfile";
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        // Save lockfile
        lock.save(spec_id).expect("Failed to save lockfile");

        // Load lockfile
        let loaded = XCheckerLock::load(spec_id)
            .expect("Failed to load lockfile")
            .expect("Lockfile should exist");

        assert_eq!(loaded.schema_version, lock.schema_version);
        assert_eq!(loaded.model_full_name, lock.model_full_name);
        assert_eq!(loaded.claude_cli_version, lock.claude_cli_version);
    }

    #[test]
    fn test_xchecker_lock_load_nonexistent() {
        let _temp_dir = setup_test_env();

        let spec_id = "nonexistent-spec";
        let loaded = XCheckerLock::load(spec_id).expect("Load should succeed");

        assert!(
            loaded.is_none(),
            "Should return None for nonexistent lockfile"
        );
    }

    #[test]
    fn test_xchecker_lock_corrupted_file() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-corrupted";
        let lock_path = XCheckerLock::get_lock_path(spec_id);

        // Create spec directory
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write corrupted JSON
        fs::write(&lock_path, "{ invalid json }").unwrap();

        // Should return error for corrupted file
        let result = XCheckerLock::load(spec_id);
        assert!(result.is_err(), "Should fail to load corrupted lockfile");
    }

    #[test]
    fn test_xchecker_lock_empty_file() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-empty";
        let lock_path = XCheckerLock::get_lock_path(spec_id);

        // Create spec directory
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write empty file
        fs::write(&lock_path, "").unwrap();

        // Should return error for empty file
        let result = XCheckerLock::load(spec_id);
        assert!(result.is_err(), "Should fail to load empty lockfile");
    }

    #[test]
    fn test_xchecker_lock_missing_fields() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-missing-fields";
        let lock_path = XCheckerLock::get_lock_path(spec_id);

        // Create spec directory
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write JSON with missing required fields
        fs::write(&lock_path, r#"{"schema_version": "1"}"#).unwrap();

        // Should return error for missing fields
        let result = XCheckerLock::load(spec_id);
        assert!(
            result.is_err(),
            "Should fail to load lockfile with missing fields"
        );
    }

    #[test]
    fn test_xchecker_lock_overwrite_existing() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-overwrite";

        // Create first lockfile
        let lock1 = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());
        lock1.save(spec_id).unwrap();

        // Create second lockfile with different values
        let lock2 = XCheckerLock::new("sonnet".to_string(), "0.9.0".to_string());
        lock2.save(spec_id).unwrap();

        // Load and verify it has the second lockfile's values
        let loaded = XCheckerLock::load(spec_id).unwrap().unwrap();
        assert_eq!(loaded.model_full_name, "sonnet");
        assert_eq!(loaded.claude_cli_version, "0.9.0");
    }

    #[test]
    fn test_xchecker_lock_drift_all_fields_match() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        let context = RunContext {
            model_full_name: "haiku".to_string(),
            claude_cli_version: "0.8.1".to_string(),
            schema_version: "1".to_string(),
        };

        let drift = lock.detect_drift(&context);
        assert!(
            drift.is_none(),
            "Should return None when all fields match exactly"
        );
    }

    #[test]
    fn test_xchecker_lock_drift_case_sensitive() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        // Test with different case
        let context = RunContext {
            model_full_name: "Claude-3-5-Sonnet-20241022".to_string(),
            claude_cli_version: "0.8.1".to_string(),
            schema_version: "1".to_string(),
        };

        let drift = lock.detect_drift(&context);
        assert!(drift.is_some(), "Drift detection should be case-sensitive");
        assert!(drift.unwrap().model_full_name.is_some());
    }

    #[test]
    fn test_xchecker_lock_drift_whitespace_sensitive() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        // Test with extra whitespace
        let context = RunContext {
            model_full_name: "haiku ".to_string(),
            claude_cli_version: "0.8.1".to_string(),
            schema_version: "1".to_string(),
        };

        let drift = lock.detect_drift(&context);
        assert!(
            drift.is_some(),
            "Drift detection should be whitespace-sensitive"
        );
        assert!(drift.unwrap().model_full_name.is_some());
    }

    #[test]
    fn test_xchecker_lock_save_creates_directory() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-new-dir";
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        // Directory should not exist yet
        let lock_path = XCheckerLock::get_lock_path(spec_id);
        assert!(!lock_path.exists());

        // Save should create directory
        lock.save(spec_id).unwrap();

        // Directory and file should now exist
        assert!(lock_path.exists());
        assert!(lock_path.parent().unwrap().exists());
    }

    #[test]
    fn test_xchecker_lock_json_format() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-json-format";
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        lock.save(spec_id).unwrap();

        // Read raw JSON and verify format
        let lock_path = XCheckerLock::get_lock_path(spec_id);
        let json_content = fs::read_to_string(&lock_path).unwrap();

        // Should be valid JSON
        let parsed: serde_json::Value = serde_json::from_str(&json_content).unwrap();

        // Verify required fields exist
        assert!(parsed.get("schema_version").is_some());
        assert!(parsed.get("created_at").is_some());
        assert!(parsed.get("model_full_name").is_some());
        assert!(parsed.get("claude_cli_version").is_some());

        // Verify values
        assert_eq!(parsed["schema_version"], "1");
        assert_eq!(parsed["model_full_name"], "haiku");
        assert_eq!(parsed["claude_cli_version"], "0.8.1");
    }

    #[test]
    fn test_xchecker_lock_timestamp_format() {
        let lock = XCheckerLock::new("haiku".to_string(), "0.8.1".to_string());

        // Verify created_at is a valid RFC3339 timestamp
        let timestamp_str = lock.created_at.to_rfc3339();
        assert!(!timestamp_str.is_empty());

        // Should be parseable back to DateTime
        let parsed = DateTime::parse_from_rfc3339(&timestamp_str);
        assert!(parsed.is_ok());
    }

    #[test]
    fn test_configurable_ttl_parameter() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-configurable-ttl";

        // Create a lock file with timestamp 2 minutes ago
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        let two_minutes_ago = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 120;

        let old_lock_info = LockInfo {
            pid: 99999, // Non-existent PID
            start_time: 0,
            created_at: two_minutes_ago,
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&old_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // With TTL of 60 seconds (1 minute), lock should be stale
        let result = FileLock::acquire(spec_id, false, Some(60));
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), LockError::StaleLock { .. }));

        // With TTL of 180 seconds (3 minutes), lock should not be stale yet
        // but process is dead, so it should still fail without force
        let result = FileLock::acquire(spec_id, false, Some(180));
        assert!(result.is_err());

        // With force, should succeed regardless of TTL
        let lock = FileLock::acquire(spec_id, true, Some(60)).unwrap();
        assert_eq!(lock.spec_id(), spec_id);
    }

    #[test]
    fn test_stale_lock_detection_by_age() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-stale-by-age";

        // Create a lock file with very old timestamp (2 hours ago)
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        let two_hours_ago = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 7200;

        let old_lock_info = LockInfo {
            pid: 99999, // Non-existent PID
            start_time: 0,
            created_at: two_hours_ago,
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&old_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Should detect as stale with default TTL (1 hour)
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), LockError::StaleLock { .. }));

        // Should succeed with force
        let lock = FileLock::acquire(spec_id, true, None).unwrap();
        assert_eq!(lock.spec_id(), spec_id);
    }

    #[test]
    fn test_stale_lock_detection_by_dead_process() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-stale-by-pid";

        // Create a lock file with recent timestamp but non-existent PID
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        let recent_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 60; // 1 minute ago

        let old_lock_info = LockInfo {
            pid: 99999, // Non-existent PID
            start_time: 0,
            created_at: recent_time,
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&old_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Should fail even though lock is recent, because process is dead
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());

        // Should succeed with force
        let lock = FileLock::acquire(spec_id, true, None).unwrap();
        assert_eq!(lock.spec_id(), spec_id);
    }

    #[test]
    fn test_concurrent_execution_detection() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-concurrent";

        // Acquire first lock
        let _lock1 = FileLock::acquire(spec_id, false, None).unwrap();

        // Try to acquire second lock - should fail with ConcurrentExecution
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            LockError::ConcurrentExecution { .. }
        ));

        // Even with force, should fail if process is still running
        let result = FileLock::acquire(spec_id, true, None);
        assert!(result.is_ok()); // Force allows overriding even fresh locks
    }

    #[test]
    fn test_lock_release_on_normal_exit() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-normal-exit";

        // Acquire lock
        let lock = FileLock::acquire(spec_id, false, None).unwrap();
        assert!(FileLock::exists(spec_id));

        // Explicitly release
        lock.release().unwrap();

        // Lock should be gone
        assert!(!FileLock::exists(spec_id));

        // Should be able to acquire again
        let _lock2 = FileLock::acquire(spec_id, false, None).unwrap();
    }

    #[test]
    fn test_lock_cleanup_on_panic() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-panic-cleanup";

        {
            let _lock = FileLock::acquire(spec_id, false, None).unwrap();
            assert!(FileLock::exists(spec_id));
            // Lock goes out of scope here, Drop should clean up
        }

        // Lock should be automatically cleaned up by Drop
        assert!(!FileLock::exists(spec_id));
    }

    #[test]
    fn test_force_flag_breaks_stale_lock() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-force-break";

        // Create a stale lock
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        let old_lock_info = LockInfo {
            pid: 99999,
            start_time: 0,
            created_at: 0,
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&old_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Should fail without force
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());

        // Should succeed with force
        let lock = FileLock::acquire(spec_id, true, None).unwrap();
        assert_eq!(lock.spec_id(), spec_id);

        // Lock info should be updated with current process
        let new_lock_info = FileLock::get_lock_info(spec_id).unwrap().unwrap();
        assert_eq!(new_lock_info.pid, process::id());
    }

    // ===== Edge Case Tests (Task 9.7) =====

    #[test]
    fn test_lock_with_invalid_pid() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-invalid-pid";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Create a lock with an invalid PID (0 is never a valid PID)
        let invalid_lock_info = LockInfo {
            pid: 0,
            start_time: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            created_at: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&invalid_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Should be able to acquire with force (PID 0 is never running)
        let result = FileLock::acquire(spec_id, true, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_lock_with_invalid_host() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-invalid-host";

        // Create a lock with current PID but we'll test that it still works
        let lock = FileLock::acquire(spec_id, false, None).unwrap();
        let lock_info = lock.lock_info();

        // Verify lock info is valid
        assert_eq!(lock_info.pid, process::id());
        assert_eq!(lock_info.spec_id, spec_id);
        assert!(!lock_info.xchecker_version.is_empty());
    }

    #[test]
    fn test_lock_with_corrupted_lock_file() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-corrupted-lock";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write corrupted JSON to lock file
        fs::write(&lock_path, "{ invalid json content }").unwrap();

        // Should fail with CorruptedLock error
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            LockError::CorruptedLock { .. }
        ));

        // Force flag doesn't bypass corrupted lock detection - it only bypasses stale lock detection
        // Corrupted locks are always an error that requires manual intervention
        let result_force = FileLock::acquire(spec_id, true, None);
        assert!(result_force.is_err());
        assert!(matches!(
            result_force.unwrap_err(),
            LockError::CorruptedLock { .. }
        ));
    }

    #[test]
    fn test_lock_with_partial_json() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-partial-json";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write partial JSON (missing closing brace)
        fs::write(&lock_path, r#"{"pid": 12345, "start_time": 0"#).unwrap();

        // Should fail with CorruptedLock error
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            LockError::CorruptedLock { .. }
        ));
    }

    #[test]
    fn test_lock_with_wrong_json_structure() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-wrong-structure";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write valid JSON but wrong structure (array instead of object)
        fs::write(&lock_path, r#"["not", "a", "lock", "object"]"#).unwrap();

        // Should fail with CorruptedLock error
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            LockError::CorruptedLock { .. }
        ));
    }

    #[test]
    fn test_lock_with_missing_required_fields() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-missing-fields";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write JSON with missing required fields
        fs::write(&lock_path, r#"{"pid": 12345}"#).unwrap();

        // Should fail with CorruptedLock error
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            LockError::CorruptedLock { .. }
        ));
    }

    #[test]
    fn test_lock_with_extra_fields() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-extra-fields";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Create lock info with all required fields plus extra
        let lock_info_json = format!(
            r#"{{
                "pid": 99999,
                "start_time": 0,
                "created_at": 0,
                "spec_id": "{spec_id}",
                "xchecker_version": "0.1.0",
                "extra_field": "should be ignored"
            }}"#
        );
        fs::write(&lock_path, lock_info_json).unwrap();

        // Should succeed with force (extra fields should be ignored)
        let result = FileLock::acquire(spec_id, true, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_lock_with_very_old_timestamp() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-very-old";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Create a lock with timestamp from year 1970
        let old_lock_info = LockInfo {
            pid: 99999,
            start_time: 0,
            created_at: 0, // Unix epoch
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&old_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Should be detected as stale
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), LockError::StaleLock { .. }));
    }

    #[test]
    fn test_lock_with_future_timestamp() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-future";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Create a lock with timestamp in the future (clock skew scenario)
        let future_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600; // 1 hour in the future

        let future_lock_info = LockInfo {
            pid: 99999, // Non-existent PID
            start_time: future_timestamp,
            created_at: future_timestamp,
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&future_lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Future timestamps should be handled gracefully (no panic)
        // Treated as age=0 (not stale), but PID check should still apply
        let result = FileLock::acquire(spec_id, false, None);

        // Should not panic - this is the key requirement
        // Result depends on whether PID 99999 exists (unlikely)
        // Either way, no overflow/panic should occur
        assert!(
            result.is_ok() || result.is_err(),
            "Should handle future timestamp without panic"
        );
    }

    #[test]
    fn test_lock_info_with_empty_spec_id() {
        let _temp_dir = setup_test_env();

        let spec_id = "";

        // Should handle empty spec_id gracefully
        let result = FileLock::acquire(spec_id, false, None);
        // May succeed or fail depending on path handling, but shouldn't panic
        let _ = result;
    }

    #[test]
    fn test_lock_info_with_special_characters_in_spec_id() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-with-special-@#$%";

        // Should handle special characters in spec_id
        let result = FileLock::acquire(spec_id, false, None);
        // May succeed or fail depending on filesystem, but shouldn't panic
        if let Ok(lock) = result {
            assert_eq!(lock.spec_id(), spec_id);
        }
    }

    #[test]
    fn test_get_lock_info_with_nonexistent_lock() {
        let _temp_dir = setup_test_env();

        let spec_id = "nonexistent-lock-spec";

        let result = FileLock::get_lock_info(spec_id).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_get_lock_info_with_corrupted_lock() {
        let _temp_dir = setup_test_env();

        let spec_id = "corrupted-lock-info-spec";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write corrupted content
        fs::write(&lock_path, "not json at all").unwrap();

        let result = FileLock::get_lock_info(spec_id);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            LockError::CorruptedLock { .. }
        ));
    }

    #[test]
    fn test_xchecker_lock_with_empty_values() {
        let lock = XCheckerLock::new(String::new(), String::new());

        assert_eq!(lock.schema_version, "1");
        assert_eq!(lock.model_full_name, "");
        assert_eq!(lock.claude_cli_version, "");
    }

    #[test]
    fn test_xchecker_lock_with_very_long_values() {
        let long_model = "a".repeat(1000);
        let long_version = "b".repeat(1000);

        let lock = XCheckerLock::new(long_model.clone(), long_version.clone());

        assert_eq!(lock.model_full_name, long_model);
        assert_eq!(lock.claude_cli_version, long_version);
    }

    #[test]
    fn test_xchecker_lock_with_unicode_values() {
        let unicode_model = "claude-测试-🚀";
        let unicode_version = "版本-1.0-✨";

        let lock = XCheckerLock::new(unicode_model.to_string(), unicode_version.to_string());

        assert_eq!(lock.model_full_name, unicode_model);
        assert_eq!(lock.claude_cli_version, unicode_version);
    }

    // ===== PR#141 Follow-up: Lock Hardening Regression Tests =====

    #[test]
    fn test_empty_lockfile_error_includes_spec_id() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-empty-lockfile-msg";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write empty file (simulates race condition during initialization)
        fs::write(&lock_path, "").unwrap();

        // Should fail with CorruptedLock error that includes spec_id
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());

        match result.unwrap_err() {
            LockError::CorruptedLock { reason } => {
                assert!(
                    reason.contains(spec_id),
                    "Error message should contain spec_id: {reason}"
                );
                assert!(
                    reason.contains("empty") || reason.contains("initializing"),
                    "Error message should mention empty/initializing: {reason}"
                );
            }
            other => panic!("Expected CorruptedLock, got: {other:?}"),
        }
    }

    #[test]
    fn test_partial_json_lockfile_error_includes_spec_id() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-partial-json-msg";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write partial JSON (simulates mid-write race condition)
        fs::write(&lock_path, r#"{"pid": 12345, "start_time":"#).unwrap();

        // Should fail with CorruptedLock error that includes spec_id
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());

        match result.unwrap_err() {
            LockError::CorruptedLock { reason } => {
                assert!(
                    reason.contains(spec_id),
                    "Error message should contain spec_id: {reason}"
                );
            }
            other => panic!("Expected CorruptedLock, got: {other:?}"),
        }
    }

    #[test]
    fn test_corrupted_json_error_includes_spec_id() {
        // This test verifies that corrupted lockfile error messages include spec_id
        // Note: We don't exercise the max_retries path here; instead we validate
        // the error formatting for a clearly corrupted (non-EOF) lockfile.

        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-error-format";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Write corrupted JSON that won't be retried (definite corruption, not EOF)
        fs::write(&lock_path, r#"{"invalid": "structure", "no_pid": true}"#).unwrap();

        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());

        match result.unwrap_err() {
            LockError::CorruptedLock { reason } => {
                assert!(
                    reason.contains(spec_id),
                    "Error message should contain spec_id: {reason}"
                );
            }
            other => panic!("Expected CorruptedLock, got: {other:?}"),
        }
    }

    #[test]
    fn test_concurrent_lock_error_includes_spec_id() {
        // This test verifies the ConcurrentExecution error includes spec_id

        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-create-error-format";

        // First acquire a lock
        let _lock = FileLock::acquire(spec_id, false, None).unwrap();

        // Try to acquire again - this will fail with ConcurrentExecution
        let result = FileLock::acquire(spec_id, false, None);
        assert!(result.is_err());

        // ConcurrentExecution error should include spec_id (already tested elsewhere,
        // but confirms error formatting is working)
        match result.unwrap_err() {
            LockError::ConcurrentExecution {
                spec_id: err_spec, ..
            } => {
                assert_eq!(err_spec, spec_id);
            }
            other => panic!("Expected ConcurrentExecution, got: {other:?}"),
        }
    }

    #[test]
    fn test_validate_existing_lock_handles_clock_skew() {
        let _temp_dir = setup_test_env();

        let spec_id = "test-spec-clock-skew-validation";
        let lock_path = FileLock::get_lock_path(spec_id);
        fs::create_dir_all(lock_path.parent().unwrap()).unwrap();

        // Create a lock with timestamp 1 hour in the future (clock skew)
        let future_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600;

        let lock_info = LockInfo {
            pid: 99999, // Non-existent PID
            start_time: future_timestamp,
            created_at: future_timestamp,
            spec_id: spec_id.to_string(),
            xchecker_version: "0.1.0".to_string(),
        };

        let lock_json = serde_json::to_string_pretty(&lock_info).unwrap();
        fs::write(&lock_path, lock_json).unwrap();

        // Should not panic due to clock skew - saturating_sub handles this
        // With force=true, should succeed
        let result = FileLock::acquire(spec_id, true, None);
        assert!(result.is_ok(), "Should handle clock skew gracefully");
    }
}