omni-dev 0.24.0

A powerful Git commit message analysis and amendment toolkit
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
//! `omni-dev ai claude history sync` — exports Claude Code conversation
//! history to a target directory as one `.jsonl` (and/or `.md`) per chat.
//!
//! See the issue and the module-level docs in [`super`] for the design rationale
//! (behavioural transcript vs faithful archive). This file implements only the
//! algorithm; rendering lives in [`super::markdown`].

use std::collections::BTreeSet;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use clap::Parser;
use serde::Serialize;

use super::common::{
    decode_slug, default_source_root, is_inside, parse_since, FileFormat, OutputFormat,
};
use super::markdown::{self, RenderOptions};

/// Exports Claude Code conversation history to a target directory.
#[derive(Parser, Debug)]
pub struct SyncCommand {
    /// Target directory for the export. Created if it does not exist.
    #[arg(long, value_name = "PATH")]
    pub target: PathBuf,

    /// Override source root. Defaults to `~/.claude/projects`.
    #[arg(long, value_name = "PATH")]
    pub source: Option<PathBuf>,

    /// Restrict sync to one project. Accepts the encoded directory name
    /// (e.g. `-Users-jky-tmp`) or a decoded cwd path (matched after decoding).
    // `allow_hyphen_values` lets the leading `-` in encoded slug names pass
    // through clap rather than being parsed as an unknown flag.
    #[arg(long, value_name = "NAME_OR_PATH", allow_hyphen_values = true)]
    pub project: Option<String>,

    /// Only sync sessions whose source mtime is at or after this point.
    /// Accepts a relative duration (`30s`, `5m`, `2h`, `7d`, `4w`) or an
    /// RFC 3339 timestamp.
    #[arg(long, value_name = "DURATION_OR_DATE")]
    pub since: Option<String>,

    /// Delete target files for sessions no longer present in the source.
    /// Only files matching `<slug>/<uuid>.<ext>` are eligible for deletion;
    /// `<ext>` is restricted to the formats listed in `--output-format` so
    /// artifacts the run was not asked to manage are preserved regardless.
    #[arg(long)]
    pub prune: bool,

    /// Preview changes without touching the target.
    #[arg(long)]
    pub dry_run: bool,

    /// Report format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    pub format: OutputFormat,

    /// On-disk file shape(s) to write. Accepts a comma-separated list, e.g.
    /// `--output-format jsonl,markdown` writes both side-by-side.
    #[arg(
        long,
        value_enum,
        value_name = "FORMAT[,FORMAT...]",
        value_delimiter = ',',
        default_value = "jsonl"
    )]
    pub output_format: Vec<FileFormat>,

    /// Hide system-side events (system reminders, attachments, permission-mode,
    /// summary, generic system events) from the rendered transcript. Affects
    /// markdown output only — jsonl is byte-identical regardless.
    #[arg(long)]
    pub exclude_system: bool,
}

impl SyncCommand {
    /// Executes the sync.
    pub fn execute(self) -> Result<()> {
        let formats = dedupe_formats(self.output_format.clone())?;
        let report = run(SyncOptions {
            target: &self.target,
            source: self.source.as_deref(),
            project: self.project.as_deref(),
            since: self.since.as_deref(),
            prune: self.prune,
            dry_run: self.dry_run,
            now: Utc::now(),
            output_formats: formats,
            exclude_system: self.exclude_system,
        })?;
        super::print_report(&report, self.dry_run, self.format)?;
        if !report.errors.is_empty() {
            anyhow::bail!(
                "{} session(s) failed to sync; see errors above",
                report.errors.len()
            );
        }
        Ok(())
    }
}

/// Dedupes the user-supplied list of output formats and rejects an empty set.
fn dedupe_formats(input: Vec<FileFormat>) -> Result<BTreeSet<FileFormat>> {
    let set: BTreeSet<FileFormat> = input.into_iter().collect();
    if set.is_empty() {
        anyhow::bail!("--output-format must list at least one format");
    }
    Ok(set)
}

/// Options for [`run`]. Public for tests in sibling modules.
pub struct SyncOptions<'a> {
    pub target: &'a Path,
    pub source: Option<&'a Path>,
    pub project: Option<&'a str>,
    pub since: Option<&'a str>,
    pub prune: bool,
    pub dry_run: bool,
    pub now: DateTime<Utc>,
    /// Set of file shapes to emit. Iteration order is canonical (jsonl first,
    /// then markdown) because [`FileFormat`] is `Ord`.
    pub output_formats: BTreeSet<FileFormat>,
    pub exclude_system: bool,
}

/// Outcome of a sync run.
#[derive(Debug, Default, Serialize)]
pub struct SyncReport {
    pub actions: Vec<SyncAction>,
    pub errors: Vec<SyncError>,
}

/// One unit of work the sync performed (or, in dry-run mode, would perform).
///
/// Each variant carries the [`FileFormat`] it pertains to so the report can
/// distinguish parallel jsonl and markdown actions for the same session.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SyncAction {
    Created {
        project: String,
        session: String,
        target: PathBuf,
        bytes: u64,
        format: FileFormat,
    },
    Updated {
        project: String,
        session: String,
        target: PathBuf,
        bytes: u64,
        format: FileFormat,
    },
    Skipped {
        project: String,
        session: String,
        target: PathBuf,
        reason: SkipReason,
        format: FileFormat,
    },
    Pruned {
        project: String,
        session: String,
        target: PathBuf,
        format: FileFormat,
    },
}

/// Why a session was skipped during planning.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SkipReason {
    Unchanged,
    FilteredBySince,
    FilteredByProject,
}

/// An error encountered while processing one session. Other sessions still run.
#[derive(Debug, Clone, Serialize)]
pub struct SyncError {
    pub project: String,
    pub session: String,
    pub reason: String,
}

/// Performs the sync. Library entry point — does no I/O on stdout itself.
pub fn run(opts: SyncOptions<'_>) -> Result<SyncReport> {
    let source_root_owned;
    let source_root = if let Some(p) = opts.source {
        p
    } else {
        source_root_owned = default_source_root()?;
        source_root_owned.as_path()
    };
    if !source_root.exists() {
        anyhow::bail!(
            "source directory does not exist: {} (set --source or create the directory)",
            source_root.display()
        );
    }
    if !source_root.is_dir() {
        anyhow::bail!("source path is not a directory: {}", source_root.display());
    }

    if is_inside(opts.target, source_root) {
        anyhow::bail!(
            "refusing to sync: target {} is inside source {}",
            opts.target.display(),
            source_root.display()
        );
    }

    if opts.output_formats.is_empty() {
        anyhow::bail!("output_formats must list at least one format");
    }

    if !opts.dry_run {
        fs::create_dir_all(opts.target)
            .with_context(|| format!("Failed to create target {}", opts.target.display()))?;
    }

    let cutoff = match opts.since {
        Some(spec) => Some(parse_since(spec, opts.now)?),
        None => None,
    };

    let mut report = SyncReport::default();

    let project_filter = opts.project;

    let project_dirs = list_project_dirs(source_root)?;
    for project_dir in project_dirs {
        let slug = match project_dir.file_name().and_then(|n| n.to_str()) {
            Some(s) => s.to_string(),
            None => continue,
        };
        if !project_matches(project_filter, &slug) {
            // Record skip per session-format so the user sees the filter took effect.
            for session in list_sessions(&project_dir)? {
                for &format in &opts.output_formats {
                    report.actions.push(SyncAction::Skipped {
                        project: slug.clone(),
                        session: session.uuid.clone(),
                        target: target_path_for(opts.target, &slug, &session.uuid, format),
                        reason: SkipReason::FilteredByProject,
                        format,
                    });
                }
            }
            continue;
        }

        for session in list_sessions(&project_dir)? {
            let target_dir = opts.target.join(&slug);

            if let Some(cutoff) = cutoff {
                let mtime: DateTime<Utc> = session.mtime.into();
                if mtime < cutoff {
                    for &format in &opts.output_formats {
                        report.actions.push(SyncAction::Skipped {
                            project: slug.clone(),
                            session: session.uuid.clone(),
                            target: target_path_for(opts.target, &slug, &session.uuid, format),
                            reason: SkipReason::FilteredBySince,
                            format,
                        });
                    }
                    continue;
                }
            }

            for &format in &opts.output_formats {
                let target_path =
                    target_dir.join(format!("{}.{}", session.uuid, format.extension()));
                let action = match plan_session(&session, &target_path, format) {
                    Ok(Plan::Skip) => Ok(SyncAction::Skipped {
                        project: slug.clone(),
                        session: session.uuid.clone(),
                        target: target_path.clone(),
                        reason: SkipReason::Unchanged,
                        format,
                    }),
                    Ok(Plan::Create) => write_session(
                        &session,
                        &target_dir,
                        &target_path,
                        format,
                        &slug,
                        opts.exclude_system,
                        opts.dry_run,
                    )
                    .map(|bytes| SyncAction::Created {
                        project: slug.clone(),
                        session: session.uuid.clone(),
                        target: target_path.clone(),
                        bytes,
                        format,
                    }),
                    Ok(Plan::Update) => write_session(
                        &session,
                        &target_dir,
                        &target_path,
                        format,
                        &slug,
                        opts.exclude_system,
                        opts.dry_run,
                    )
                    .map(|bytes| SyncAction::Updated {
                        project: slug.clone(),
                        session: session.uuid.clone(),
                        target: target_path.clone(),
                        bytes,
                        format,
                    }),
                    Err(e) => Err(e),
                };
                match action {
                    Ok(a) => report.actions.push(a),
                    Err(e) => report.errors.push(SyncError {
                        project: slug.clone(),
                        session: session.uuid.clone(),
                        reason: format!("{e:#}"),
                    }),
                }
            }
        }
    }

    if opts.prune {
        let format_by_ext: std::collections::HashMap<&'static str, FileFormat> = opts
            .output_formats
            .iter()
            .map(|&f| (f.extension(), f))
            .collect();
        prune_target(
            opts.target,
            source_root,
            opts.dry_run,
            &format_by_ext,
            &mut report,
        )?;
    }

    Ok(report)
}

/// Returns true if the slug should be processed (not filtered out). When
/// `false`, the caller emits `Skipped(FilteredByProject)` for the project's
/// sessions so the user sees the filter took effect.
fn project_matches(filter: Option<&str>, slug: &str) -> bool {
    let Some(filter) = filter else {
        return true;
    };
    filter == slug || decode_slug(slug) == filter
}

fn target_path_for(target: &Path, slug: &str, uuid: &str, format: FileFormat) -> PathBuf {
    target
        .join(slug)
        .join(format!("{uuid}.{}", format.extension()))
}

#[derive(Debug)]
struct Session {
    uuid: String,
    src_path: PathBuf,
    size: u64,
    mtime: SystemTime,
}

fn list_project_dirs(source_root: &Path) -> Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    let read = fs::read_dir(source_root)
        .with_context(|| format!("Failed to read source {}", source_root.display()))?;
    for entry in read {
        let entry =
            entry.with_context(|| format!("Failed to read entry in {}", source_root.display()))?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        out.push(path);
    }
    out.sort();
    Ok(out)
}

fn list_sessions(project_dir: &Path) -> Result<Vec<Session>> {
    let mut out = Vec::new();
    let read = fs::read_dir(project_dir)
        .with_context(|| format!("Failed to read project {}", project_dir.display()))?;
    for entry in read {
        let entry =
            entry.with_context(|| format!("Failed to read entry in {}", project_dir.display()))?;
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        if path.extension().and_then(|e| e.to_str()) != Some(FileFormat::Jsonl.extension()) {
            continue;
        }
        let Some(uuid) = path
            .file_stem()
            .and_then(|s| s.to_str())
            .map(str::to_string)
        else {
            continue;
        };
        let metadata = entry
            .metadata()
            .with_context(|| format!("Failed to stat {}", path.display()))?;
        let mtime = metadata
            .modified()
            .with_context(|| format!("Failed to read mtime of {}", path.display()))?;
        out.push(Session {
            uuid,
            src_path: path,
            size: metadata.len(),
            mtime,
        });
    }
    out.sort_by(|a, b| a.uuid.cmp(&b.uuid));
    Ok(out)
}

#[derive(Debug)]
enum Plan {
    Create,
    Update,
    Skip,
}

fn plan_session(session: &Session, target_path: &Path, format: FileFormat) -> Result<Plan> {
    match fs::metadata(target_path) {
        Ok(meta) => {
            let same_size = meta.len() == session.size;
            let same_mtime = meta.modified().ok().is_some_and(|t| t == session.mtime);
            // Markdown is a derived artefact whose on-disk length differs from
            // the source jsonl, so size cannot participate in the key. The
            // source jsonl is append-only, making mtime alone a sufficient
            // freshness key for the rendered output.
            let unchanged = match format {
                FileFormat::Jsonl => same_size && same_mtime,
                FileFormat::Markdown => same_mtime,
            };
            if unchanged {
                Ok(Plan::Skip)
            } else {
                Ok(Plan::Update)
            }
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Plan::Create),
        Err(e) => Err(e).with_context(|| format!("Failed to stat {}", target_path.display())),
    }
}

/// Writes the session in the requested format. Dispatches by format:
/// jsonl is a snapshot-EOF byte copy; markdown reads the snapshot bytes and
/// renders via [`markdown::render`].
fn write_session(
    session: &Session,
    target_dir: &Path,
    target_path: &Path,
    format: FileFormat,
    project_slug: &str,
    exclude_system: bool,
    dry_run: bool,
) -> Result<u64> {
    if dry_run {
        // No I/O in dry-run. The jsonl byte count is known up-front; markdown
        // would require rendering, which we deliberately skip.
        return Ok(match format {
            FileFormat::Jsonl => session.size,
            FileFormat::Markdown => 0,
        });
    }

    fs::create_dir_all(target_dir)
        .with_context(|| format!("Failed to create {}", target_dir.display()))?;

    let bytes = match format {
        FileFormat::Jsonl => copy_jsonl(session, target_dir, target_path)?,
        FileFormat::Markdown => render_markdown_to_file(
            session,
            target_dir,
            target_path,
            project_slug,
            exclude_system,
        )?,
    };

    set_mtime(target_path, session.mtime)
        .with_context(|| format!("Failed to set mtime on {}", target_path.display()))?;

    Ok(bytes)
}

/// Copies a session from `session.src_path` to `target_path` using a
/// snapshot-EOF read of `session.size` bytes — sessions still being appended
/// to upstream produce a valid prefix.
fn copy_jsonl(session: &Session, target_dir: &Path, target_path: &Path) -> Result<u64> {
    let mut src = BufReader::new(
        File::open(&session.src_path)
            .with_context(|| format!("Failed to open {}", session.src_path.display()))?,
    );

    // Stage to a sibling tempfile so a partially-copied target never overwrites
    // a previously-good one. The rename below is atomic on the same filesystem.
    let mut tmp = tempfile::NamedTempFile::new_in(target_dir)
        .with_context(|| format!("Failed to create temp in {}", target_dir.display()))?;
    let copied = {
        let mut writer = BufWriter::new(tmp.as_file_mut());
        let mut limited = (&mut src).take(session.size);
        let copied = io::copy(&mut limited, &mut writer)
            .with_context(|| format!("Failed to copy {}", session.src_path.display()))?;
        writer
            .flush()
            .with_context(|| format!("Failed to flush {}", target_path.display()))?;
        copied
    };

    let persisted = tmp
        .persist(target_path)
        .map_err(|e| e.error)
        .with_context(|| format!("Failed to publish {}", target_path.display()))?;
    drop(persisted);

    Ok(copied)
}

fn render_markdown_to_file(
    session: &Session,
    target_dir: &Path,
    target_path: &Path,
    project_slug: &str,
    exclude_system: bool,
) -> Result<u64> {
    let mut buf = Vec::with_capacity(session.size as usize);
    {
        let mut src = File::open(&session.src_path)
            .with_context(|| format!("Failed to open {}", session.src_path.display()))?;
        let mut limited = (&mut src).take(session.size);
        limited
            .read_to_end(&mut buf)
            .with_context(|| format!("Failed to read {}", session.src_path.display()))?;
    }

    let rendered = markdown::render(
        &buf,
        RenderOptions {
            project_slug,
            session_uuid: &session.uuid,
            exclude_system,
        },
    )
    .with_context(|| {
        format!(
            "Failed to render markdown for {}",
            session.src_path.display()
        )
    })?;

    let mut tmp = tempfile::NamedTempFile::new_in(target_dir)
        .with_context(|| format!("Failed to create temp in {}", target_dir.display()))?;
    tmp.as_file_mut()
        .write_all(rendered.as_bytes())
        .with_context(|| format!("Failed to write markdown to {}", target_path.display()))?;
    tmp.as_file_mut()
        .flush()
        .with_context(|| format!("Failed to flush {}", target_path.display()))?;

    let persisted = tmp
        .persist(target_path)
        .map_err(|e| e.error)
        .with_context(|| format!("Failed to publish {}", target_path.display()))?;
    drop(persisted);

    Ok(rendered.len() as u64)
}

fn set_mtime(path: &Path, mtime: SystemTime) -> io::Result<()> {
    let f = OpenOptions::new().write(true).open(path)?;
    f.set_modified(mtime)
}

fn prune_target(
    target_root: &Path,
    source_root: &Path,
    dry_run: bool,
    format_by_ext: &std::collections::HashMap<&'static str, FileFormat>,
    report: &mut SyncReport,
) -> Result<()> {
    let target_entries = match fs::read_dir(target_root) {
        Ok(it) => it,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(e) => {
            return Err(e)
                .with_context(|| format!("Failed to read target {}", target_root.display()));
        }
    };

    let mut slug_dirs: Vec<PathBuf> = Vec::new();
    for entry in target_entries {
        let entry =
            entry.with_context(|| format!("Failed to read entry in {}", target_root.display()))?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        slug_dirs.push(path);
    }
    slug_dirs.sort();

    for slug_dir in slug_dirs {
        let slug = match slug_dir.file_name().and_then(|n| n.to_str()) {
            Some(s) => s.to_string(),
            None => continue,
        };
        let source_slug_dir = source_root.join(&slug);

        let read = fs::read_dir(&slug_dir)
            .with_context(|| format!("Failed to read {}", slug_dir.display()))?;
        for entry in read {
            let entry =
                entry.with_context(|| format!("Failed to read entry in {}", slug_dir.display()))?;
            let path = entry.path();
            if !path.is_file() {
                continue;
            }
            let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
                continue;
            };
            let Some(&format) = format_by_ext.get(ext) else {
                continue;
            };
            let Some(uuid) = path
                .file_stem()
                .and_then(|s| s.to_str())
                .map(str::to_string)
            else {
                continue;
            };
            // Source companionship is keyed off the canonical jsonl file —
            // the markdown is a derivative, so its presence/absence in source
            // tracks the jsonl.
            let source_file =
                source_slug_dir.join(format!("{uuid}.{}", FileFormat::Jsonl.extension()));
            if source_file.exists() {
                continue;
            }
            if !dry_run {
                fs::remove_file(&path)
                    .with_context(|| format!("Failed to delete {}", path.display()))?;
            }
            report.actions.push(SyncAction::Pruned {
                project: slug.clone(),
                session: uuid,
                target: path,
                format,
            });
        }
    }

    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::fs::File as StdFile;
    use std::time::{Duration, SystemTime};

    use tempfile::TempDir;

    /// `TempDir::path()` returns a path with macOS's `/var/folders/...` form,
    /// which canonicalises to `/private/var/folders/...`. Tests that compare
    /// derived paths against `tmp.path()` will fail; canonicalising once at
    /// the start sidesteps the entire class of platform aliasing issues.
    fn tempdir() -> TempDir {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        std::fs::create_dir_all(&root).ok();
        TempDir::new_in(&root).unwrap()
    }

    fn jsonl_only() -> BTreeSet<FileFormat> {
        BTreeSet::from([FileFormat::Jsonl])
    }

    fn markdown_only() -> BTreeSet<FileFormat> {
        BTreeSet::from([FileFormat::Markdown])
    }

    fn both_formats() -> BTreeSet<FileFormat> {
        BTreeSet::from([FileFormat::Jsonl, FileFormat::Markdown])
    }

    fn default_opts<'a>(
        target: &'a Path,
        source: Option<&'a Path>,
        formats: BTreeSet<FileFormat>,
    ) -> SyncOptions<'a> {
        SyncOptions {
            target,
            source,
            project: None,
            since: None,
            prune: false,
            dry_run: false,
            now: chrono::Utc::now(),
            output_formats: formats,
            exclude_system: false,
        }
    }

    /// Source directory mock: writes one session jsonl per `(slug, uuid)`
    /// pair with the given content. Returns the source root.
    struct SourceBuilder {
        root: PathBuf,
    }

    impl SourceBuilder {
        fn new(root: PathBuf) -> Self {
            std::fs::create_dir_all(&root).unwrap();
            Self { root }
        }

        fn add(&self, slug: &str, uuid: &str, content: &str) -> PathBuf {
            let dir = self.root.join(slug);
            std::fs::create_dir_all(&dir).unwrap();
            let path = dir.join(format!("{uuid}.jsonl"));
            std::fs::write(&path, content).unwrap();
            path
        }

        fn append(&self, slug: &str, uuid: &str, more: &str) {
            let path = self.root.join(slug).join(format!("{uuid}.jsonl"));
            let mut f = OpenOptions::new().append(true).open(&path).unwrap();
            f.write_all(more.as_bytes()).unwrap();
            // Bump mtime explicitly so the test isn't sensitive to filesystem
            // mtime granularity (HFS+ in particular uses 1s resolution).
            let new_mtime = SystemTime::now() + Duration::from_secs(2);
            StdFile::open(&path)
                .unwrap()
                .set_modified(new_mtime)
                .unwrap();
        }
    }

    fn run_default(target: &Path, source: &Path) -> Result<SyncReport> {
        run(default_opts(target, Some(source), jsonl_only()))
    }

    fn count_created(r: &SyncReport) -> usize {
        r.actions
            .iter()
            .filter(|a| matches!(a, SyncAction::Created { .. }))
            .count()
    }

    fn count_updated(r: &SyncReport) -> usize {
        r.actions
            .iter()
            .filter(|a| matches!(a, SyncAction::Updated { .. }))
            .count()
    }

    fn count_skipped(r: &SyncReport) -> usize {
        r.actions
            .iter()
            .filter(|a| matches!(a, SyncAction::Skipped { .. }))
            .count()
    }

    fn count_pruned(r: &SyncReport) -> usize {
        r.actions
            .iter()
            .filter(|a| matches!(a, SyncAction::Pruned { .. }))
            .count()
    }

    fn count_filtered_by(r: &SyncReport, want: &SkipReason) -> usize {
        r.actions
            .iter()
            .filter(|a| matches!(a, SyncAction::Skipped { reason, .. } if reason == want))
            .count()
    }

    fn count_format(r: &SyncReport, fmt: FileFormat) -> usize {
        r.actions
            .iter()
            .filter(|a| match a {
                SyncAction::Created { format, .. }
                | SyncAction::Updated { format, .. }
                | SyncAction::Skipped { format, .. }
                | SyncAction::Pruned { format, .. } => *format == fmt,
            })
            .count()
    }

    #[test]
    fn fresh_sync_creates_files_with_matching_bytes() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("-Users-jky-foo", "uuid-1", "{\"x\":1}\n");
        sb.add("-Users-jky-foo", "uuid-2", "{\"x\":2}\n");
        sb.add("-Users-jky-bar", "uuid-3", "{\"x\":3}\n");

        let report = run_default(tgt.path(), src.path()).unwrap();
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);
        assert_eq!(count_created(&report), 3);

        for (slug, uuid, body) in [
            ("-Users-jky-foo", "uuid-1", "{\"x\":1}\n"),
            ("-Users-jky-foo", "uuid-2", "{\"x\":2}\n"),
            ("-Users-jky-bar", "uuid-3", "{\"x\":3}\n"),
        ] {
            let target_path = tgt.path().join(slug).join(format!("{uuid}.jsonl"));
            assert_eq!(std::fs::read_to_string(&target_path).unwrap(), body);
        }
    }

    #[test]
    fn second_run_is_noop() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "line\n");

        run_default(tgt.path(), src.path()).unwrap();
        let report = run_default(tgt.path(), src.path()).unwrap();
        assert!(matches!(
            report.actions[0],
            SyncAction::Skipped {
                reason: SkipReason::Unchanged,
                ..
            }
        ));
        assert_eq!(report.actions.len(), 1);
    }

    #[test]
    fn modified_source_triggers_update() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "line\n");
        sb.add("slug", "u2", "stable\n");

        run_default(tgt.path(), src.path()).unwrap();
        sb.append("slug", "u1", "more\n");

        let report = run_default(tgt.path(), src.path()).unwrap();
        assert_eq!(count_updated(&report), 1, "actions: {:?}", report.actions);
        assert_eq!(count_skipped(&report), 1);

        let body = std::fs::read_to_string(tgt.path().join("slug").join("u1.jsonl")).unwrap();
        assert_eq!(body, "line\nmore\n");
    }

    #[test]
    fn new_chat_added_between_runs() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "a\n");
        run_default(tgt.path(), src.path()).unwrap();

        sb.add("slug", "u2", "b\n");
        let report = run_default(tgt.path(), src.path()).unwrap();
        assert_eq!(count_created(&report), 1);
    }

    #[test]
    fn prune_deletes_only_matching_files_when_requested() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "a\n");
        sb.add("slug", "u2", "b\n");
        run_default(tgt.path(), src.path()).unwrap();

        // Drop a stray file that does not match `<slug>/<uuid>.jsonl` shape.
        let stray_top = tgt.path().join("README.md");
        std::fs::write(&stray_top, "keep me").unwrap();
        let stray_in_slug = tgt.path().join("slug").join("notes.txt");
        std::fs::write(&stray_in_slug, "keep me too").unwrap();

        // Remove u1 from source and run with --prune.
        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        let report = run(opts).unwrap();

        assert_eq!(count_pruned(&report), 1, "actions: {:?}", report.actions);
        assert!(!tgt.path().join("slug").join("u1.jsonl").exists());
        assert!(tgt.path().join("slug").join("u2.jsonl").exists());

        // Stray files survive prune.
        assert!(stray_top.exists());
        assert!(stray_in_slug.exists());
    }

    #[test]
    fn no_prune_leaves_orphans_alone() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "a\n");
        run_default(tgt.path(), src.path()).unwrap();

        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let report = run_default(tgt.path(), src.path()).unwrap();
        // No source file -> no action; orphan target file is untouched.
        assert!(report
            .actions
            .iter()
            .all(|a| !matches!(a, SyncAction::Pruned { .. })));
        assert!(tgt.path().join("slug").join("u1.jsonl").exists());
    }

    #[test]
    fn dry_run_does_not_touch_target() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "abc\n");

        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.dry_run = true;
        let report = run(opts).unwrap();
        assert!(report
            .actions
            .iter()
            .any(|a| matches!(a, SyncAction::Created { .. })));
        // Target slug subdir was never created.
        assert!(!tgt.path().join("slug").exists());
    }

    #[test]
    fn project_filter_matches_encoded_slug() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("-Users-jky-foo", "u1", "f\n");
        sb.add("-Users-jky-bar", "u2", "b\n");

        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.project = Some("-Users-jky-foo");
        let report = run(opts).unwrap();
        assert_eq!(count_created(&report), 1);
        assert_eq!(
            count_filtered_by(&report, &SkipReason::FilteredByProject),
            1
        );
    }

    #[test]
    fn project_filter_matches_decoded_path() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("-Users-jky-foo", "u1", "f\n");
        sb.add("-Users-jky-bar", "u2", "b\n");

        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.project = Some("/Users/jky/foo");
        let report = run(opts).unwrap();
        assert_eq!(count_created(&report), 1);
    }

    #[test]
    fn project_filter_no_match_skips_everything() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug-a", "u1", "a\n");
        sb.add("slug-b", "u2", "b\n");

        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.project = Some("nonexistent");
        let report = run(opts).unwrap();
        assert!(report.actions.iter().all(|a| matches!(
            a,
            SyncAction::Skipped {
                reason: SkipReason::FilteredByProject,
                ..
            }
        )));
    }

    #[test]
    fn since_filters_old_sessions() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        let old_path = sb.add("slug", "old", "old\n");
        sb.add("slug", "new", "new\n");

        // Backdate "old" session 30 days into the past.
        let old_mtime = SystemTime::now() - Duration::from_secs(30 * 24 * 60 * 60);
        StdFile::open(&old_path)
            .unwrap()
            .set_modified(old_mtime)
            .unwrap();

        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.since = Some("1d");
        let report = run(opts).unwrap();

        assert_eq!(count_created(&report), 1);
        assert_eq!(count_filtered_by(&report, &SkipReason::FilteredBySince), 1);
    }

    #[test]
    fn target_inside_source_is_refused() {
        let src = tempdir();
        let tgt_inside = src.path().join("inside");
        std::fs::create_dir_all(&tgt_inside).unwrap();
        let err = run(default_opts(&tgt_inside, Some(src.path()), jsonl_only())).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("inside"), "unexpected: {msg}");
    }

    #[test]
    fn missing_source_errors_clearly() {
        let tgt = tempdir();
        let nope = tgt.path().join("does-not-exist");
        let err = run(default_opts(tgt.path(), Some(&nope), jsonl_only())).unwrap_err();
        assert!(format!("{err:#}").contains("does not exist"));
    }

    #[test]
    fn source_path_must_be_directory() {
        let src = tempdir();
        let tgt = tempdir();
        let file = src.path().join("not-a-dir");
        std::fs::write(&file, "x").unwrap();
        let err = run(default_opts(tgt.path(), Some(&file), jsonl_only())).unwrap_err();
        assert!(format!("{err:#}").contains("not a directory"));
    }

    #[test]
    fn snapshot_eof_copies_only_initial_length() {
        // Simulate a chat that grows mid-sync: list_sessions captures the
        // initial size; copy_jsonl must not exceed it.
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        let path = sb.add("slug", "u1", "first-half\n");

        // Pre-compute size, then append more bytes BEFORE running sync.
        let snapshot_len = std::fs::metadata(&path).unwrap().len();
        {
            let mut f = OpenOptions::new().append(true).open(&path).unwrap();
            f.write_all(b"second-half-appended-after-snapshot\n")
                .unwrap();
        }
        // Fake out the planner: write a Session manually that pins the old size.
        let session = Session {
            uuid: "u1".to_string(),
            src_path: path.clone(),
            size: snapshot_len,
            mtime: std::fs::metadata(&path).unwrap().modified().unwrap(),
        };
        let target_dir = tgt.path().join("slug");
        std::fs::create_dir_all(&target_dir).unwrap();
        let target_path = target_dir.join("u1.jsonl");
        let copied = copy_jsonl(&session, &target_dir, &target_path).unwrap();
        assert_eq!(copied, snapshot_len);
        let body = std::fs::read_to_string(&target_path).unwrap();
        assert_eq!(body, "first-half\n");
    }

    #[test]
    fn mtime_is_preserved_on_target() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        let path = sb.add("slug", "u1", "data\n");
        // Set a very specific mtime so the comparison is unambiguous.
        let ts = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        StdFile::open(&path).unwrap().set_modified(ts).unwrap();

        run_default(tgt.path(), src.path()).unwrap();
        let target_path = tgt.path().join("slug").join("u1.jsonl");
        let target_mtime = std::fs::metadata(&target_path).unwrap().modified().unwrap();
        let target_secs = target_mtime
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert_eq!(target_secs, 1_700_000_000);
    }

    #[test]
    fn ignores_non_jsonl_and_subdirs_under_project() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        // Add a non-jsonl file and a sub-agent-style subdirectory; sync ignores both.
        let project_dir = src.path().join("slug");
        std::fs::write(project_dir.join("sessions-index.json"), "{}").unwrap();
        std::fs::create_dir_all(project_dir.join("u1").join("subagents")).unwrap();
        std::fs::write(
            project_dir
                .join("u1")
                .join("subagents")
                .join("agent-x.jsonl"),
            "noise\n",
        )
        .unwrap();

        let report = run_default(tgt.path(), src.path()).unwrap();
        assert_eq!(count_created(&report), 1, "actions: {:?}", report.actions);

        // Target contains only the one file, not the noise.
        let target_slug = tgt.path().join("slug");
        let entries: Vec<_> = std::fs::read_dir(&target_slug)
            .unwrap()
            .filter_map(Result::ok)
            .map(|e| e.file_name())
            .collect();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0], "u1.jsonl");
    }

    #[test]
    fn execute_via_clap_round_trip_works() {
        // Drives the full SyncCommand::execute path so the clap derive and
        // print_report code aren't dead.
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");

        let cmd = SyncCommand::try_parse_from([
            "history-sync",
            "--source",
            src.path().to_str().unwrap(),
            "--target",
            tgt.path().to_str().unwrap(),
            "--format",
            "yaml",
        ])
        .unwrap();
        cmd.execute().unwrap();
        assert!(tgt.path().join("slug").join("u1.jsonl").exists());
    }

    #[cfg(unix)]
    #[test]
    fn execute_returns_error_when_target_is_unwritable() {
        // Force copy_jsonl to fail by making the target slug directory
        // read-only. Sync proceeds for other sessions, then bail()s because
        // the report carries errors.
        use std::os::unix::fs::PermissionsExt;

        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");

        // Pre-create the slug subdir as read-only so the temp-file write fails.
        let slug_dir = tgt.path().join("slug");
        std::fs::create_dir_all(&slug_dir).unwrap();
        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o500)).unwrap();

        let cmd = SyncCommand::try_parse_from([
            "history-sync",
            "--source",
            src.path().to_str().unwrap(),
            "--target",
            tgt.path().to_str().unwrap(),
        ])
        .unwrap();
        let err = cmd.execute().unwrap_err();
        assert!(format!("{err:#}").contains("session(s) failed"));

        // Restore perms so TempDir can drop cleanly.
        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[test]
    fn target_root_is_canonicalised_for_inside_check_via_macos_alias() {
        // On macOS /tmp aliases /private/tmp — exercise the canonicalisation
        // walk-up. We use the actual tempdir whose parent canonicalises.
        let src = tempdir();
        let tgt_outside = tempdir();
        // Fresh sync should succeed when target is genuinely outside source.
        let report = run_default(tgt_outside.path(), src.path()).unwrap();
        assert!(report.errors.is_empty());
    }

    #[test]
    fn default_source_root_returns_a_path_under_home() {
        let p = super::super::common::default_source_root().unwrap();
        // Constructed from $HOME, so must be absolute and end in `.claude/projects`.
        assert!(p.is_absolute());
        assert!(p.ends_with(".claude/projects"));
    }

    #[test]
    fn dispatch_via_history_command_clap() {
        // Drive HistoryCommand::execute through clap (covers mod.rs dispatch).
        use super::super::HistoryCommand;
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        let cmd = HistoryCommand::try_parse_from([
            "history",
            "sync",
            "--source",
            src.path().to_str().unwrap(),
            "--target",
            tgt.path().to_str().unwrap(),
        ])
        .unwrap();
        cmd.execute().unwrap();
        assert!(tgt.path().join("slug").join("u1.jsonl").exists());
    }

    fn jsonl_format_by_ext() -> std::collections::HashMap<&'static str, FileFormat> {
        let mut m: std::collections::HashMap<&'static str, FileFormat> =
            std::collections::HashMap::new();
        m.insert(FileFormat::Jsonl.extension(), FileFormat::Jsonl);
        m
    }

    #[test]
    fn prune_handles_missing_target_dir_silently() {
        let src = tempdir();
        let tgt_root = tempdir();
        let nonexistent = tgt_root.path().join("not-yet-here");
        let mut report = SyncReport::default();
        let format_by_ext = jsonl_format_by_ext();
        prune_target(&nonexistent, src.path(), false, &format_by_ext, &mut report).unwrap();
        assert!(report.actions.is_empty());
    }

    #[test]
    fn prune_skips_non_jsonl_and_non_files_inside_target_slug() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "a\n");
        run_default(tgt.path(), src.path()).unwrap();

        let slug_dir = tgt.path().join("slug");
        std::fs::create_dir_all(slug_dir.join("subdir")).unwrap();
        std::fs::write(slug_dir.join("notes.txt"), "x").unwrap();

        // Remove u1 from source to make --prune trigger.
        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        let report = run(opts).unwrap();

        // Pruned exactly u1; subdir and notes.txt survive.
        assert_eq!(count_pruned(&report), 1);
        assert!(slug_dir.join("subdir").exists());
        assert!(slug_dir.join("notes.txt").exists());
    }

    #[test]
    fn prune_skips_non_directory_entries_at_target_root() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "a\n");
        run_default(tgt.path(), src.path()).unwrap();
        std::fs::write(tgt.path().join("README.md"), "stray").unwrap();

        let mut report = SyncReport::default();
        let format_by_ext = jsonl_format_by_ext();
        prune_target(tgt.path(), src.path(), false, &format_by_ext, &mut report).unwrap();
        assert!(report.actions.is_empty());
        assert!(tgt.path().join("README.md").exists());
    }

    #[test]
    fn dry_run_does_not_prune() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "a\n");
        run_default(tgt.path(), src.path()).unwrap();

        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        opts.dry_run = true;
        let report = run(opts).unwrap();
        assert!(report
            .actions
            .iter()
            .any(|a| matches!(a, SyncAction::Pruned { .. })));
        assert!(
            tgt.path().join("slug").join("u1.jsonl").exists(),
            "dry-run prune must not delete"
        );
    }

    #[test]
    fn source_root_non_directory_entries_are_skipped() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        std::fs::write(src.path().join("stray.txt"), "noise").unwrap();

        let report = run_default(tgt.path(), src.path()).unwrap();
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);
        assert_eq!(count_created(&report), 1);
    }

    #[cfg(unix)]
    #[test]
    fn update_path_records_error_when_target_dir_becomes_unwritable() {
        use std::os::unix::fs::PermissionsExt;

        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "first\n");
        run_default(tgt.path(), src.path()).unwrap();

        sb.append("slug", "u1", "second\n");

        let slug_dir = tgt.path().join("slug");
        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o500)).unwrap();

        let report = run_default(tgt.path(), src.path()).unwrap();
        assert_eq!(
            report.errors.len(),
            1,
            "actions: {:?}, errors: {:?}",
            report.actions,
            report.errors
        );

        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[test]
    fn project_flag_accepts_leading_hyphen_via_clap() {
        let src = tempdir();
        let tgt = tempdir();
        let cmd = SyncCommand::try_parse_from([
            "history-sync",
            "--source",
            src.path().to_str().unwrap(),
            "--target",
            tgt.path().to_str().unwrap(),
            "--project",
            "-Users-jky-tmp",
        ])
        .unwrap();
        assert_eq!(cmd.project.as_deref(), Some("-Users-jky-tmp"));
    }

    #[test]
    fn since_with_invalid_value_errors() {
        let src = tempdir();
        let tgt = tempdir();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.since = Some("nonsense");
        let err = run(opts).unwrap_err();
        assert!(format!("{err:#}").contains("--since"));
    }

    #[cfg(unix)]
    #[test]
    fn plan_session_propagates_stat_permission_error() {
        use std::os::unix::fs::PermissionsExt;

        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        run_default(tgt.path(), src.path()).unwrap();

        let slug_dir = tgt.path().join("slug");
        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o000)).unwrap();

        let report = run_default(tgt.path(), src.path());

        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o755)).unwrap();

        let report = report.unwrap();
        assert_eq!(
            report.errors.len(),
            1,
            "expected exactly one stat error, got actions={:?} errors={:?}",
            report.actions,
            report.errors
        );
        assert!(
            report.errors[0].reason.contains("Failed to stat"),
            "unexpected error: {}",
            report.errors[0].reason
        );
    }

    #[cfg(unix)]
    #[test]
    fn run_propagates_prune_error_via_question_mark() {
        // Force prune_target to fail from inside run() so the `?` after the
        // prune_target(...) call (line ~346) is exercised. dry_run lets us
        // skip the upfront create_dir_all on the target while still entering
        // the prune branch.
        use std::os::unix::fs::PermissionsExt;

        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        run_default(tgt.path(), src.path()).unwrap();

        std::fs::set_permissions(tgt.path(), std::fs::Permissions::from_mode(0o000)).unwrap();

        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        opts.dry_run = true;
        let result = run(opts);

        std::fs::set_permissions(tgt.path(), std::fs::Permissions::from_mode(0o755)).unwrap();

        let err = result.unwrap_err();
        assert!(format!("{err:#}").contains("Failed to read target"));
    }

    #[cfg(unix)]
    #[test]
    fn prune_propagates_read_dir_permission_error() {
        use std::os::unix::fs::PermissionsExt;

        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        run_default(tgt.path(), src.path()).unwrap();

        std::fs::set_permissions(tgt.path(), std::fs::Permissions::from_mode(0o000)).unwrap();

        let mut report = SyncReport::default();
        let format_by_ext = jsonl_format_by_ext();
        let result = prune_target(tgt.path(), src.path(), false, &format_by_ext, &mut report);

        std::fs::set_permissions(tgt.path(), std::fs::Permissions::from_mode(0o755)).unwrap();

        let err = result.unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("Failed to read target"), "unexpected: {msg}");
    }

    // -------------------------------------------------------------------
    // Markdown / multi-format coverage
    // -------------------------------------------------------------------

    #[test]
    fn markdown_only_emits_only_md_files() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );

        let report = run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);
        assert_eq!(count_created(&report), 1);
        assert!(tgt.path().join("slug").join("u1.md").exists());
        assert!(!tgt.path().join("slug").join("u1.jsonl").exists());

        let body = std::fs::read_to_string(tgt.path().join("slug").join("u1.md")).unwrap();
        assert!(body.starts_with("---\n"));
        assert!(body.contains("hi"));
    }

    #[test]
    fn both_formats_emit_both_files_side_by_side() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );

        let report = run(default_opts(tgt.path(), Some(src.path()), both_formats())).unwrap();
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);
        assert_eq!(count_created(&report), 2);
        assert_eq!(count_format(&report, FileFormat::Jsonl), 1);
        assert_eq!(count_format(&report, FileFormat::Markdown), 1);
        assert!(tgt.path().join("slug").join("u1.md").exists());
        assert!(tgt.path().join("slug").join("u1.jsonl").exists());
    }

    #[test]
    fn markdown_format_re_run_is_skipped() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );

        run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();
        let report = run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();
        assert_eq!(count_skipped(&report), 1);
        assert_eq!(count_created(&report) + count_updated(&report), 0);
    }

    #[test]
    fn markdown_regenerates_when_source_grows() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"first\"}}\n",
        );
        run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();

        sb.append(
            "slug",
            "u1",
            "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"second\"}]}}\n",
        );
        let report = run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();
        assert_eq!(count_updated(&report), 1, "actions: {:?}", report.actions);

        let body = std::fs::read_to_string(tgt.path().join("slug").join("u1.md")).unwrap();
        assert!(body.contains("first"));
        assert!(body.contains("second"));
    }

    #[test]
    fn prune_scopes_to_requested_format_jsonl_only() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );

        // Produce both files first.
        run(default_opts(tgt.path(), Some(src.path()), both_formats())).unwrap();
        assert!(tgt.path().join("slug").join("u1.jsonl").exists());
        assert!(tgt.path().join("slug").join("u1.md").exists());

        // Remove source, then prune with only jsonl format requested.
        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        let report = run(opts).unwrap();

        assert_eq!(count_pruned(&report), 1);
        assert!(!tgt.path().join("slug").join("u1.jsonl").exists());
        // Markdown survives — caller did not ask to manage it.
        assert!(tgt.path().join("slug").join("u1.md").exists());
    }

    #[test]
    fn prune_scopes_to_requested_format_markdown_only() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );

        run(default_opts(tgt.path(), Some(src.path()), both_formats())).unwrap();
        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();

        let mut opts = default_opts(tgt.path(), Some(src.path()), markdown_only());
        opts.prune = true;
        let report = run(opts).unwrap();

        assert_eq!(count_pruned(&report), 1);
        assert!(tgt.path().join("slug").join("u1.jsonl").exists());
        assert!(!tgt.path().join("slug").join("u1.md").exists());
    }

    #[test]
    fn prune_with_both_formats_removes_both() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );

        run(default_opts(tgt.path(), Some(src.path()), both_formats())).unwrap();
        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();

        let mut opts = default_opts(tgt.path(), Some(src.path()), both_formats());
        opts.prune = true;
        let report = run(opts).unwrap();

        assert_eq!(count_pruned(&report), 2);
        assert_eq!(count_format(&report, FileFormat::Jsonl), 1);
        assert_eq!(count_format(&report, FileFormat::Markdown), 1);
    }

    #[test]
    fn exclude_system_drops_attachment_from_markdown() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n\
             {\"type\":\"attachment\",\"attachment\":{\"type\":\"skill_listing\",\"skillCount\":1}}\n",
        );

        let mut opts = default_opts(tgt.path(), Some(src.path()), markdown_only());
        opts.exclude_system = true;
        run(opts).unwrap();
        let body = std::fs::read_to_string(tgt.path().join("slug").join("u1.md")).unwrap();
        assert!(body.contains("hi"));
        assert!(!body.contains("Attachment"));
    }

    #[test]
    fn markdown_partial_jsonl_prefix_renders_what_it_can() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        let path = sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"complete\"}}\n",
        );
        // Append a partial JSON line that the renderer must tolerate.
        let mut f = OpenOptions::new().append(true).open(&path).unwrap();
        f.write_all(b"{\"type\":\"user\",\"message\":{\"content\":\"par")
            .unwrap();

        run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();
        let body = std::fs::read_to_string(tgt.path().join("slug").join("u1.md")).unwrap();
        assert!(body.contains("complete"));
        assert!(!body.contains("\"par"));
    }

    #[test]
    fn markdown_action_carries_format_in_yaml_serialisation() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );
        let report = run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();
        let yaml = serde_yaml::to_string(&report).unwrap();
        assert!(yaml.contains("format: markdown"), "yaml: {yaml}");
    }

    #[test]
    fn dedupe_formats_collapses_duplicates() {
        let s = dedupe_formats(vec![FileFormat::Jsonl, FileFormat::Jsonl]).unwrap();
        assert_eq!(s.len(), 1);
    }

    #[test]
    fn dedupe_formats_rejects_empty_set() {
        assert!(dedupe_formats(vec![]).is_err());
    }

    #[test]
    fn run_rejects_empty_output_formats() {
        let src = tempdir();
        let tgt = tempdir();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.output_formats = BTreeSet::new();
        let err = run(opts).unwrap_err();
        assert!(format!("{err:#}").contains("output_formats"));
    }

    #[test]
    fn output_format_clap_accepts_comma_split() {
        let src = tempdir();
        let tgt = tempdir();
        let cmd = SyncCommand::try_parse_from([
            "history-sync",
            "--source",
            src.path().to_str().unwrap(),
            "--target",
            tgt.path().to_str().unwrap(),
            "--output-format",
            "jsonl,markdown",
        ])
        .unwrap();
        assert_eq!(cmd.output_format.len(), 2);
        assert!(cmd.output_format.contains(&FileFormat::Jsonl));
        assert!(cmd.output_format.contains(&FileFormat::Markdown));
    }

    #[test]
    fn output_format_clap_default_is_jsonl() {
        let src = tempdir();
        let tgt = tempdir();
        let cmd = SyncCommand::try_parse_from([
            "history-sync",
            "--source",
            src.path().to_str().unwrap(),
            "--target",
            tgt.path().to_str().unwrap(),
        ])
        .unwrap();
        assert_eq!(cmd.output_format, vec![FileFormat::Jsonl]);
    }

    #[test]
    fn exclude_system_clap_flag_parses() {
        let src = tempdir();
        let tgt = tempdir();
        let cmd = SyncCommand::try_parse_from([
            "history-sync",
            "--source",
            src.path().to_str().unwrap(),
            "--target",
            tgt.path().to_str().unwrap(),
            "--exclude-system",
        ])
        .unwrap();
        assert!(cmd.exclude_system);
    }

    // Linux-only: macOS / APFS rejects non-utf8 filenames at create time
    // ("Illegal byte sequence"), so the create_dir below would fail before
    // the prune walker is reached. Linux ext4/btrfs accepts them.
    #[cfg(target_os = "linux")]
    #[test]
    fn prune_skips_target_slug_dir_with_non_utf8_name() {
        // Cover the `file_name().to_str() => None` continue branch in
        // prune_target's slug-dir loop. Needs a Unix filesystem accepting
        // non-utf8 bytes as a directory name.
        use std::os::unix::ffi::OsStrExt;

        let src = tempdir();
        let tgt = tempdir();
        // Real session under a normal slug.
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        run_default(tgt.path(), src.path()).unwrap();

        // Drop a non-utf8 sibling slug dir into the target. Lone 0xff is
        // invalid utf-8 — file_name().to_str() returns None.
        let bad_name = std::ffi::OsStr::from_bytes(b"slug-\xff");
        let bad_dir = tgt.path().join(bad_name);
        std::fs::create_dir_all(&bad_dir).unwrap();

        // Remove u1 source so prune has work to do; bad_dir must not break the walker.
        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        let report = run(opts).unwrap();

        assert_eq!(count_pruned(&report), 1);
        assert!(bad_dir.exists(), "non-utf8 slug must be left alone");
    }

    // Linux-only: see sibling test for the rationale.
    #[cfg(target_os = "linux")]
    #[test]
    fn prune_skips_target_files_with_non_utf8_stem() {
        // Cover the `file_stem().to_str() => None` continue branch inside
        // prune_target's per-slug file loop.
        use std::os::unix::ffi::OsStrExt;

        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "x\n");
        run_default(tgt.path(), src.path()).unwrap();

        // Drop a `.jsonl` file with a non-utf8 stem inside the target slug dir.
        let bad_stem = std::ffi::OsStr::from_bytes(b"bad-\xff");
        let bad_file = tgt
            .path()
            .join("slug")
            .join(bad_stem)
            .with_extension("jsonl");
        std::fs::write(&bad_file, "x").unwrap();

        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        let report = run(opts).unwrap();

        // u1 still pruned; the non-utf8 stem file is left alone.
        assert_eq!(count_pruned(&report), 1);
        assert!(bad_file.exists(), "non-utf8 stem must not be deleted");
    }

    #[test]
    fn prune_skips_files_without_extension_and_unrecognised_extensions() {
        // Drop a no-extension file and a `.txt` file in the target slug; both
        // must survive --prune (covers the `Some(ext)` and `format_by_ext.get`
        // continue branches in prune_target).
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add("slug", "u1", "a\n");
        run_default(tgt.path(), src.path()).unwrap();

        let slug_dir = tgt.path().join("slug");
        std::fs::write(slug_dir.join("noext"), "x").unwrap();
        std::fs::write(slug_dir.join("notes.txt"), "x").unwrap();

        // Remove u1 source so the jsonl is eligible for prune; the no-ext and
        // .txt files must not be touched.
        std::fs::remove_file(src.path().join("slug").join("u1.jsonl")).unwrap();
        let mut opts = default_opts(tgt.path(), Some(src.path()), jsonl_only());
        opts.prune = true;
        let report = run(opts).unwrap();

        assert_eq!(count_pruned(&report), 1);
        assert!(slug_dir.join("noext").exists());
        assert!(slug_dir.join("notes.txt").exists());
    }

    #[cfg(unix)]
    #[test]
    fn markdown_write_records_error_when_target_dir_becomes_unwritable() {
        // First sync populates the target. Then make the slug dir read-only
        // and append to source so the next pass tries to Update — the markdown
        // tempfile creation fails inside render_markdown_to_file, exercising
        // the `?` propagation via write_session and into run()'s error arm.
        use std::os::unix::fs::PermissionsExt;

        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"first\"}}\n",
        );
        run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();

        sb.append(
            "slug",
            "u1",
            "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"second\"}]}}\n",
        );

        let slug_dir = tgt.path().join("slug");
        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o500)).unwrap();

        let report = run(default_opts(tgt.path(), Some(src.path()), markdown_only())).unwrap();

        std::fs::set_permissions(&slug_dir, std::fs::Permissions::from_mode(0o755)).unwrap();

        assert_eq!(report.errors.len(), 1, "errors: {:?}", report.errors);
        assert!(
            report.errors[0].reason.contains("Failed to create temp")
                || report.errors[0].reason.contains("Failed to write"),
            "unexpected: {}",
            report.errors[0].reason
        );
    }

    #[test]
    fn render_markdown_to_file_propagates_open_error() {
        // Force the underlying File::open to fail by passing a Session that
        // points at a missing source path. Covers the `?` propagation in
        // render_markdown_to_file.
        let tgt = tempdir();
        let target_dir = tgt.path().join("slug");
        std::fs::create_dir_all(&target_dir).unwrap();
        let session = Session {
            uuid: "u1".to_string(),
            src_path: tgt.path().join("does-not-exist.jsonl"),
            size: 100,
            mtime: SystemTime::now(),
        };
        let target_path = target_dir.join("u1.md");
        let err = render_markdown_to_file(&session, &target_dir, &target_path, "slug", false)
            .unwrap_err();
        assert!(format!("{err:#}").contains("Failed to open"));
    }

    #[test]
    fn dry_run_does_not_create_markdown_either() {
        let src = tempdir();
        let tgt = tempdir();
        let sb = SourceBuilder::new(src.path().to_path_buf());
        sb.add(
            "slug",
            "u1",
            "{\"type\":\"user\",\"message\":{\"content\":\"hi\"}}\n",
        );

        let mut opts = default_opts(tgt.path(), Some(src.path()), markdown_only());
        opts.dry_run = true;
        let report = run(opts).unwrap();
        assert!(report
            .actions
            .iter()
            .any(|a| matches!(a, SyncAction::Created { .. })));
        assert!(!tgt.path().join("slug").exists());
    }
}