heddle-cli 0.3.1

An AI-native version control system
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
// SPDX-License-Identifier: Apache-2.0
//! Pull, remote management, and serve commands.

#[cfg(feature = "client")]
use std::net::SocketAddr;
use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
#[cfg(feature = "client")]
use heddle_client::grpc_hosted::{HostedAuthMode, PullMaterialization};
use objects::{
    fs_atomic::write_file_atomic,
    object::{ChangeId, ThreadName, Tree},
    store::ObjectStore,
};
use refs::Head;
use repo::{Repository, RepositoryCapability};
use serde::Serialize;
use sley::{
    GitConfig, Repository as SleyRepository,
    plumbing::sley_config::{
        ConfigIncludeContext, ConfigOriginKind, ConfigScope, ConfigStack, ConfigStackEntry,
    },
};

use super::super::{
    action_line::print_next,
    advice::RecoveryAdvice,
    git_overlay_health::{
        RepositoryVerificationState, build_plain_git_verification_probe,
        build_repository_verification_state,
    },
    worktree_safety::ensure_worktree_clean,
};
#[cfg(feature = "client")]
use crate::client::HostedGrpcClient;
use crate::{
    bridge::{GitBridge, git_core::GitPullOutcome},
    cli::{Cli, RemoteCommands, should_output_json, style},
    client::LocalSync,
    config::UserConfig,
    remote::{Remote, RemoteConfig, RemoteError, RemoteTarget, resolve_remote_with_key},
};

#[derive(Serialize)]
struct RemoteListOutput {
    output_kind: &'static str,
    remotes: Vec<RemoteInfoOutput>,
}

#[derive(Serialize)]
struct RemoteInfoOutput {
    #[serde(skip_serializing_if = "Option::is_none")]
    output_kind: Option<&'static str>,
    name: String,
    url: String,
    source: String,
    is_default: bool,
}

#[derive(Serialize)]
struct RemoteMutationOutput {
    output_kind: &'static str,
    status: &'static str,
    action: &'static str,
    name: String,
    url: Option<String>,
    default: Option<String>,
    message: String,
    #[allow(dead_code)]
    #[serde(skip_serializing)]
    #[serde(rename = "verification")]
    trust: RepositoryVerificationState,
}

#[derive(Serialize)]
struct PullOutput {
    output_kind: &'static str,
    action: &'static str,
    status: &'static str,
    success: bool,
    pulled: bool,
    changed: bool,
    transport: &'static str,
    remote: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    branch: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    old_git_head: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    new_git_head: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    old_state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    new_state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    states_created: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    commits_seen: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    commits_seen_scope: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    materialized_checkout: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    changed_path_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    changed_paths: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    thread: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    objects: Option<usize>,
    #[allow(dead_code)]
    #[serde(skip_serializing)]
    #[serde(rename = "verification")]
    trust: RepositoryVerificationState,
}

struct GitOverlayPullOutputInput {
    remote: String,
    branch: Option<String>,
    old_git_head: Option<String>,
    new_git_head: Option<String>,
    old_state: Option<ChangeId>,
    new_state: Option<ChangeId>,
    changed_paths: Vec<String>,
    outcome: GitPullOutcome,
    trust: RepositoryVerificationState,
}

fn git_overlay_pull_output(input: GitOverlayPullOutputInput) -> PullOutput {
    PullOutput {
        output_kind: "pull",
        action: "pull",
        status: pull_status(input.outcome.changed),
        success: true,
        pulled: input.outcome.changed,
        changed: input.outcome.changed,
        transport: "git",
        remote: input.remote,
        branch: input.branch,
        old_git_head: input.old_git_head,
        new_git_head: input.new_git_head,
        old_state: input.old_state.map(|state| state.to_string()),
        new_state: input.new_state.map(|state| state.to_string()),
        states_created: Some(input.outcome.states_created),
        commits_seen: Some(input.outcome.commits_seen),
        commits_seen_scope: Some("branches_and_heddle_notes"),
        materialized_checkout: Some(input.outcome.materialized_checkout),
        changed_path_count: Some(input.changed_paths.len()),
        changed_paths: Some(input.changed_paths),
        thread: None,
        state: None,
        objects: None,
        trust: input.trust,
    }
}

fn heddle_pull_output(
    changed: bool,
    remote: String,
    thread: String,
    state: Option<String>,
    objects: Option<usize>,
    trust: RepositoryVerificationState,
) -> PullOutput {
    PullOutput {
        output_kind: "pull",
        action: "pull",
        status: pull_status(changed),
        success: true,
        pulled: changed,
        changed,
        transport: "heddle",
        remote,
        branch: None,
        old_git_head: None,
        new_git_head: None,
        old_state: None,
        new_state: None,
        states_created: None,
        commits_seen: None,
        commits_seen_scope: None,
        materialized_checkout: None,
        changed_path_count: None,
        changed_paths: None,
        thread: Some(thread),
        state,
        objects,
        trust,
    }
}

fn pull_status(changed: bool) -> &'static str {
    if changed { "updated" } else { "up_to_date" }
}

/// Execute pull command.
pub async fn cmd_pull(
    cli: &Cli,
    remote: Option<String>,
    thread: Option<String>,
    local_thread: Option<String>,
    lazy: bool,
) -> Result<()> {
    let repo = cli.open_repo()?;
    if remote.is_none() && resolved_default_remote_name(&repo)?.is_none() {
        return Err(anyhow::anyhow!(RecoveryAdvice::remote_not_configured(
            "pull"
        )));
    }
    if repo.capability() == RepositoryCapability::GitOverlay && !repo.hosted_enabled() {
        ensure_worktree_clean(&repo, "pull")?;
        let remote_name = resolve_default_remote_name(&repo, remote.as_deref())?;
        let branch = repo.git_overlay_current_branch()?;
        let old_git_head = git_checkout_head_oid(repo.root());
        let old_state = repo.head()?;
        let mut bridge = GitBridge::new(&repo);
        let outcome = bridge.pull(&remote_name)?;
        let new_git_head = git_checkout_head_oid(repo.root());
        let new_state = repo.head()?;
        let changed_paths =
            changed_paths_between_states(&repo, old_state.as_ref(), new_state.as_ref())?;
        let verification = build_repository_verification_state(&repo);
        if should_output_json(cli, Some(repo.config())) {
            let output = git_overlay_pull_output(GitOverlayPullOutputInput {
                remote: remote_name,
                branch,
                old_git_head,
                new_git_head,
                old_state,
                new_state,
                changed_paths,
                outcome,
                trust: verification,
            });
            crate::cli::render::write_json_stdout(&output)?;
        } else {
            if outcome.changed {
                println!(
                    "{} pulled from {}",
                    style::ok_marker(),
                    style::bold(&remote_name)
                );
            } else {
                println!(
                    "{} already up to date with {}; repository verification checked below",
                    style::ok_marker(),
                    style::bold(&remote_name)
                );
            }
            if let Some(branch) = &branch {
                if outcome.changed {
                    println!("Branch: {}", style::bold(branch));
                } else if let Some(head) = &new_git_head {
                    println!("Branch: {} at {}", style::bold(branch), short_oid(head));
                }
            }
            match (&old_git_head, &new_git_head) {
                (Some(old), Some(new)) if old != new => {
                    println!("Git: {} -> {}", short_oid(old), short_oid(new));
                }
                (Some(head), Some(_)) if outcome.changed => {
                    println!("Git: {}", short_oid(head));
                }
                _ => {}
            }
            println!(
                "Imported: {}",
                style::count(outcome.states_created, "new state")
            );
            println!(
                "Scanned: {} across branches + refs/notes/heddle",
                style::count(outcome.commits_seen, "Git commit object")
            );
            if outcome.materialized_checkout {
                println!("Worktree: materialized checkout");
            }
            if outcome.changed {
                println!("Changed paths: {}", changed_paths.len());
                for path in changed_paths.iter().take(8) {
                    println!("  - {path}");
                }
                if changed_paths.len() > 8 {
                    println!("  - ... {} more", changed_paths.len() - 8);
                }
            }
            if !verification.verified {
                println!("Workspace: {}", style::warn(&verification.status));
                if !verification.recommended_action.is_empty() {
                    print_next(&verification.recommended_action);
                }
            } else {
                println!("Workspace: verified");
            }
        }
        return Ok(());
    }

    super::preflight_native_remote_transport(&repo, remote.as_deref(), "pull")?;

    let user_config = UserConfig::load_default()?;
    #[cfg(not(feature = "client"))]
    let token = user_config.remote_token()?;
    #[cfg(feature = "client")]
    let (target, server_key) =
        resolve_remote_with_key(&repo, remote.as_deref()).map_err(anyhow::Error::msg)?;
    #[cfg(not(feature = "client"))]
    let (target, _server_key) =
        resolve_remote_with_key(&repo, remote.as_deref()).map_err(anyhow::Error::msg)?;

    let remote_thread = thread.unwrap_or_else(|| "main".to_string());
    let local_thread_name = local_thread.as_deref();
    let should_materialize = match repo.head_ref()? {
        Head::Attached { thread } => local_thread_name.is_none_or(|local| thread == local),
        Head::Detached { .. } => local_thread_name.is_none(),
    };
    if should_materialize {
        ensure_worktree_clean(&repo, "pull")?;
    }

    match target {
        RemoteTarget::Local(path) => {
            pull_local(&repo, &path, &remote_thread, local_thread_name, cli, lazy).await?;
        }
        RemoteTarget::Network { addr, repo_path } => {
            #[cfg(feature = "client")]
            pull_network(
                &repo,
                PullNetworkOptions {
                    addr,
                    repo_path: repo_path.as_deref(),
                    user_config: &user_config,
                    server_key,
                    remote_thread: &remote_thread,
                    local_thread: local_thread_name,
                    lazy,
                    cli,
                },
            )
            .await?;
            #[cfg(not(feature = "client"))]
            let _ = (addr, repo_path, token);
            #[cfg(not(feature = "client"))]
            anyhow::bail!(RecoveryAdvice::network_feature_unavailable("pull"));
        }
    }

    Ok(())
}

async fn pull_local(
    repo: &Repository,
    source_path: &std::path::Path,
    remote_thread: &str,
    local_thread: Option<&str>,
    cli: &Cli,
    lazy: bool,
) -> Result<()> {
    if lazy {
        return Err(anyhow::anyhow!(
            RecoveryAdvice::local_lazy_pull_unsupported(source_path)
        ));
    }

    if !should_output_json(cli, Some(repo.config())) {
        println!(
            "{} pulling from {}",
            style::working_marker(),
            style::dim(&format!("file://{}", source_path.display()))
        );
    }

    let source = LocalSync::open(source_path)?;

    let state_id = source
        .source()
        .refs()
        .get_thread(&ThreadName::new(remote_thread))?
        .context(format!("Thread {} not found in source", remote_thread))?;

    let objects_copied = source.fetch_state(repo, &state_id)?;

    let track_to_update = local_thread.unwrap_or(remote_thread);
    let track_tn = ThreadName::new(track_to_update);

    let pre_target = repo.refs().get_thread(&track_tn)?;
    let changed = pre_target.as_ref() != Some(&state_id) || objects_copied > 0;

    // Preserve attached-HEAD semantics only when the pull target is the
    // current checkout. Pulling a remote into a side thread must not move
    // the operator's active thread or overwrite its worktree.
    let head_ref = repo.head_ref()?;
    let should_materialize = match &head_ref {
        Head::Attached { thread } => thread == track_to_update,
        Head::Detached { .. } => local_thread.is_none(),
    };
    if should_materialize {
        // A dirty-refusal must NEVER leave a ref advanced without its
        // corresponding worktree materialization. Run the refuse-able
        // apply before publishing `track_tn`; `fast_forward_attached*`
        // publishes the attached current thread only after the worktree
        // apply succeeds, and the detached arm publishes `track_tn`
        // explicitly below after the same guard has passed.
        match (&head_ref, pre_target) {
            (Head::Attached { .. }, Some(_)) => {
                super::super::ff_record::record_ff_advance(repo, remote_thread, &state_id)?;
            }
            (Head::Attached { .. }, None) => {
                repo.fast_forward_attached_from_materialized_state(&state_id, None)?;
            }
            (Head::Detached { .. }, _) => {
                repo.goto(&state_id)?;
                repo.refs().set_thread(&track_tn, &state_id)?;
            }
        }
    } else {
        repo.refs().set_thread(&track_tn, &state_id)?;
    }

    if should_output_json(cli, Some(repo.config())) {
        let output = heddle_pull_output(
            changed,
            source_path.display().to_string(),
            track_to_update.to_string(),
            Some(state_id.to_string()),
            Some(objects_copied),
            build_repository_verification_state(repo),
        );
        crate::cli::render::write_json_stdout(&output)?;
    } else {
        println!(
            "{} pulled {} from {} ({})",
            style::ok_marker(),
            style::change_id(&state_id.short().to_string()),
            style::bold(remote_thread),
            style::count(objects_copied, "object")
        );
    }

    Ok(())
}

fn git_checkout_head_oid(root: &Path) -> Option<String> {
    let git = SleyRepository::discover(root).ok()?;
    git.head().ok()?.oid.map(|oid| oid.to_string())
}

fn short_oid(oid: &str) -> String {
    oid.chars().take(12).collect()
}

fn changed_paths_between_states(
    repo: &Repository,
    old_state: Option<&ChangeId>,
    new_state: Option<&ChangeId>,
) -> Result<Vec<String>> {
    if old_state == new_state {
        return Ok(Vec::new());
    }
    let Some(new_state) = new_state else {
        return Ok(Vec::new());
    };
    let new_state = repo
        .store()
        .get_state(new_state)?
        .context("new pulled state was not found in Heddle storage")?;
    let old_tree = match old_state {
        Some(old_state) => repo
            .store()
            .get_state(old_state)?
            .map(|state| state.tree)
            .unwrap_or_else(|| Tree::new().hash()),
        None => Tree::new().hash(),
    };
    let mut paths = repo
        .diff_trees(&old_tree, &new_state.tree)?
        .iter()
        .map(|change| change.path.clone())
        .collect::<Vec<_>>();
    paths.sort();
    paths.dedup();
    Ok(paths)
}

#[cfg(feature = "client")]
async fn pull_network(repo: &Repository, options: PullNetworkOptions<'_>) -> Result<()> {
    let repo_path = options
        .repo_path
        .context("network remotes must include a hosted repository path")?;
    let mut client = HostedGrpcClient::open_session(
        options.addr,
        options.user_config,
        options.server_key,
        HostedAuthMode::CredentialFallback,
    )
    .await?;

    if !should_output_json(options.cli, Some(repo.config())) {
        println!(
            "{} connected to {}",
            style::ok_marker(),
            style::dim(&options.addr.to_string())
        );
    }

    let result = client
        .pull_with_depth_and_materialization(
            repo,
            repo_path,
            options.remote_thread,
            options.local_thread,
            None,
            if options.lazy {
                PullMaterialization::Lazy
            } else {
                PullMaterialization::Full
            },
        )
        .await?;

    if result.success {
        let changed = result.final_state.is_some();
        if should_output_json(options.cli, Some(repo.config())) {
            let output = heddle_pull_output(
                changed,
                options.remote_thread.to_string(),
                options
                    .local_thread
                    .unwrap_or(options.remote_thread)
                    .to_string(),
                result.final_state.map(|state| state.to_string()),
                None,
                build_repository_verification_state(repo),
            );
            crate::cli::render::write_json_stdout(&output)?;
        } else {
            println!(
                "{} pulled from {}",
                style::ok_marker(),
                style::bold(options.remote_thread)
            );
            if let Some(final_state) = result.final_state {
                println!(
                    "{}",
                    style::field("state", &style::change_id(&final_state.to_string()))
                );
            }
        }
    } else {
        let err = result.error.unwrap_or_else(|| "Unknown error".to_string());
        return Err(anyhow::anyhow!(RecoveryAdvice::remote_pull_failed(
            options.remote_thread,
            options.local_thread,
            &err,
        )));
    }

    Ok(())
}

/// Execute remote command.
pub fn cmd_remote(cli: &Cli, command: RemoteCommands) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let start = cli.repo.as_ref().unwrap_or(&cwd);
    match &command {
        RemoteCommands::List => {
            if let Some(probe) = build_plain_git_verification_probe(start)? {
                let items = plain_git_remote_items(&probe.root);
                let default = default_remote_from_items(&items);
                let output = RemoteListOutput {
                    output_kind: "remote_list",
                    remotes: items
                        .into_iter()
                        .map(|(name, url)| {
                            let is_default = default.as_deref() == Some(name.as_str());
                            RemoteInfoOutput {
                                output_kind: None,
                                name,
                                url,
                                source: "git".to_string(),
                                is_default,
                            }
                        })
                        .collect(),
                };
                render_remote_list(&output, should_output_json(cli, None))?;
                return Ok(());
            }
        }
        RemoteCommands::Show { name } => {
            if let Some(probe) = build_plain_git_verification_probe(start)? {
                let items = plain_git_remote_items(&probe.root);
                let default = default_remote_from_items(&items);
                let url = items
                    .get(name)
                    .cloned()
                    .ok_or_else(|| RecoveryAdvice::remote_not_found(name))?;
                let output = RemoteInfoOutput {
                    output_kind: Some("remote_show"),
                    name: name.clone(),
                    url,
                    source: "git".to_string(),
                    is_default: default.as_deref() == Some(name.as_str()),
                };
                render_remote_info(&output, should_output_json(cli, None))?;
                return Ok(());
            }
        }
        RemoteCommands::Add { .. }
        | RemoteCommands::Remove { .. }
        | RemoteCommands::SetDefault { .. } => {}
    }

    let repo = Repository::open(start)?;

    match command {
        RemoteCommands::List => {
            let items = merged_remote_items(&repo)?;
            let default = resolved_default_remote_name(&repo)?;
            let output = RemoteListOutput {
                output_kind: "remote_list",
                remotes: items
                    .into_iter()
                    .map(|(name, (url, source))| {
                        let is_default = default.as_deref() == Some(name.as_str());
                        RemoteInfoOutput {
                            output_kind: None,
                            name,
                            url,
                            source,
                            is_default,
                        }
                    })
                    .collect(),
            };
            render_remote_list(&output, should_output_json(cli, Some(repo.config())))?;
            Ok(())
        }
        RemoteCommands::Add { name, url } => {
            super::preflight_native_remote_transport(&repo, Some(&url), "remote add")?;
            let git_overlay_default_before = (repo.capability()
                == RepositoryCapability::GitOverlay)
                .then(|| git_overlay_default_remote_name(&repo))
                .flatten();
            sync_git_overlay_remote_add(&repo, &name, &url)?;
            let mut cfg = RemoteConfig::open(&repo).map_err(anyhow::Error::msg)?;
            let default_was_empty = cfg.default_name().is_none();
            cfg.add(&name, Remote { url: url.clone() })
                .map_err(anyhow::Error::msg)?;
            if default_was_empty
                && git_overlay_default_before
                    .as_deref()
                    .is_some_and(|default| default != name)
            {
                cfg.clear_default().map_err(anyhow::Error::msg)?;
            }
            let default = resolved_default_remote_name(&repo)?;
            render_remote_mutation(
                RemoteMutationOutput {
                    output_kind: "remote_add",
                    status: "completed",
                    action: "remote_add",
                    name,
                    url: Some(url),
                    default,
                    message: "Added remote".to_string(),
                    trust: build_repository_verification_state(&repo),
                },
                should_output_json(cli, Some(repo.config())),
            )?;
            Ok(())
        }
        RemoteCommands::Remove { name } => {
            if !merged_remote_items(&repo)?.contains_key(&name) {
                return Err(RecoveryAdvice::remote_not_found(&name).into());
            }
            // Remove the git-overlay side FIRST so its uneditable-include
            // refusal (raised before any file is touched) leaves the Heddle
            // config unmutated. Persisting the Heddle removal ahead of this
            // fallible step stranded the repo in partial state: the Heddle
            // remote gone, the Git remote still present.
            sync_git_overlay_remote_remove(&repo, &name)?;
            let mut cfg = RemoteConfig::open(&repo).map_err(anyhow::Error::msg)?;
            match cfg.remove(&name) {
                Ok(()) | Err(RemoteError::NotFound(_)) => {}
                Err(err) => return Err(anyhow::Error::msg(err)),
            }
            render_remote_mutation(
                RemoteMutationOutput {
                    output_kind: "remote_remove",
                    status: "completed",
                    action: "remote_remove",
                    name,
                    url: None,
                    default: resolved_default_remote_name(&repo)?,
                    message: "Removed remote".to_string(),
                    trust: build_repository_verification_state(&repo),
                },
                should_output_json(cli, Some(repo.config())),
            )?;
            Ok(())
        }
        RemoteCommands::SetDefault { name } => {
            let items = merged_remote_items(&repo)?;
            let (url, _source) = items
                .get(&name)
                .cloned()
                .ok_or_else(|| RecoveryAdvice::remote_not_found(&name))?;
            let mut cfg = RemoteConfig::open(&repo).map_err(anyhow::Error::msg)?;
            // Git-overlay remotes added via `git remote add` only live in
            // `.git/config`. `merged_remote_items` surfaces them in
            // `remote list/show`, but `RemoteConfig::set_default` would
            // reject them as NotFound. Adopt the URL into
            // `.heddle/remotes.toml` first so `default_name()`-driven
            // readers (including `resolve_remote_with_key`) can resolve
            // it, then set the default explicitly.
            if cfg.get(&name).is_err() {
                cfg.add(&name, Remote { url }).map_err(anyhow::Error::msg)?;
            }
            cfg.set_default(&name).map_err(anyhow::Error::msg)?;
            render_remote_mutation(
                RemoteMutationOutput {
                    output_kind: "remote_set_default",
                    status: "completed",
                    action: "remote_set_default",
                    name: name.clone(),
                    url: None,
                    default: Some(name),
                    message: "Set default remote".to_string(),
                    trust: build_repository_verification_state(&repo),
                },
                should_output_json(cli, Some(repo.config())),
            )?;
            Ok(())
        }
        RemoteCommands::Show { name } => {
            let items = merged_remote_items(&repo)?;
            let default = resolved_default_remote_name(&repo)?;
            let (url, source) = items
                .get(&name)
                .cloned()
                .ok_or_else(|| RecoveryAdvice::remote_not_found(&name))?;
            let is_default = default.as_deref() == Some(name.as_str());
            let output = RemoteInfoOutput {
                output_kind: Some("remote_show"),
                name,
                url,
                source,
                is_default,
            };
            render_remote_info(&output, should_output_json(cli, Some(repo.config())))?;
            Ok(())
        }
    }
}

fn render_remote_mutation(output: RemoteMutationOutput, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string(&output)?);
    } else {
        println!(
            "{} {} {}",
            style::ok_marker(),
            output.message.to_lowercase(),
            style::bold(&output.name)
        );
        if !output.trust.recommended_action.is_empty() {
            print_next(&output.trust.recommended_action);
        }
    }
    Ok(())
}

fn render_remote_list(output: &RemoteListOutput, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string(output)?);
    } else if output.remotes.is_empty() {
        println!("{}", style::dim("No remotes configured"));
        println!("{}", style::field("next", "heddle remote add <name> <url>"));
    } else {
        println!("{}", style::section("Remotes"));
        for item in &output.remotes {
            println!(
                "  {} {} {}",
                style::bold(&item.name),
                style::dim(&item.url),
                style::dim(&format!(
                    "({}{})",
                    item.source,
                    if item.is_default { ", default" } else { "" }
                ))
            );
        }
    }
    Ok(())
}

fn render_remote_info(output: &RemoteInfoOutput, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string(output)?);
    } else {
        println!("{}", style::section("Remote"));
        println!("  {}", style::field("name", &style::bold(&output.name)));
        println!("  {}", style::field("url", &style::dim(&output.url)));
        println!("  {}", style::field("source", &style::dim(&output.source)));
        println!(
            "  {}",
            style::field("default", if output.is_default { "yes" } else { "no" })
        );
    }
    Ok(())
}

pub(crate) fn resolve_default_remote_name(
    repo: &Repository,
    requested: Option<&str>,
) -> Result<String> {
    if let Some(requested) = requested {
        return Ok(requested.to_string());
    }
    if let Some(default) = RemoteConfig::open(repo)
        .map_err(anyhow::Error::msg)?
        .default_name()
    {
        return Ok(default.to_string());
    }
    if repo.capability() == RepositoryCapability::GitOverlay
        && let Some(default) = git_overlay_default_remote_name(repo)
    {
        return Ok(default);
    }
    Ok("origin".to_string())
}

pub(crate) fn resolved_default_remote_name(repo: &Repository) -> Result<Option<String>> {
    let cfg = RemoteConfig::open(repo).map_err(anyhow::Error::msg)?;
    if let Some(default) = cfg.default_name() {
        return Ok(Some(default.to_string()));
    }
    if repo.capability() == RepositoryCapability::GitOverlay {
        return Ok(git_overlay_default_remote_name(repo));
    }
    Ok(None)
}

fn git_overlay_default_remote_name(repo: &Repository) -> Option<String> {
    let git_remotes = git_overlay_config_remotes(repo);
    if let Some(upstream_remote) = git_upstream_remote_name(repo) {
        return Some(upstream_remote);
    }
    if git_remotes.contains_key("origin") {
        return Some("origin".to_string());
    }
    if git_remotes.len() == 1 {
        return git_remotes.keys().next().cloned();
    }
    None
}

fn git_upstream_remote_name(repo: &Repository) -> Option<String> {
    let branch = repo.git_overlay_current_branch().ok().flatten()?;
    let git = SleyRepository::discover(repo.root()).ok()?;
    git.config_snapshot()
        .ok()?
        .get("branch", Some(&branch), "remote")
        .map(str::to_string)
        .filter(|remote| !remote.is_empty())
}

fn merged_remote_items(repo: &Repository) -> Result<BTreeMap<String, (String, String)>> {
    let cfg = RemoteConfig::open(repo).map_err(anyhow::Error::msg)?;
    let git_overlay_remotes = if repo.capability() == RepositoryCapability::GitOverlay {
        git_overlay_config_remotes(repo)
    } else {
        BTreeMap::new()
    };
    let mut items: BTreeMap<String, (String, String)> = cfg
        .list()
        .into_iter()
        .map(|(name, remote)| {
            let source = configured_remote_source(repo, &remote.url);
            (name, (remote.url, source.to_string()))
        })
        .collect();
    if repo.capability() == RepositoryCapability::GitOverlay {
        for (name, url) in git_overlay_remotes {
            items
                .entry(name)
                .or_insert_with(|| (url, "git-overlay".to_string()));
        }
    }
    Ok(items)
}

fn configured_remote_source(repo: &Repository, url: &str) -> &'static str {
    if repo.capability() == RepositoryCapability::GitOverlay
        && local_remote_path(url).is_some_and(|path| is_local_git_repository(&path))
    {
        "git-overlay"
    } else {
        "heddle"
    }
}

fn local_remote_path(url: &str) -> Option<std::path::PathBuf> {
    match RemoteTarget::parse(url).ok()? {
        RemoteTarget::Local(path) => Some(path),
        RemoteTarget::Network { .. } => None,
    }
}

fn is_local_git_repository(path: &Path) -> bool {
    if path.join(".git").exists() {
        return true;
    }
    path.join("HEAD").is_file() && path.join("objects").is_dir() && path.join("refs").is_dir()
}

fn plain_git_remote_items(root: &Path) -> BTreeMap<String, String> {
    let Some(ctx) = GitConfigContext::discover(root) else {
        return BTreeMap::new();
    };
    ctx.remotes(ctx.layered_paths())
}

fn default_remote_from_items(items: &BTreeMap<String, String>) -> Option<String> {
    if items.contains_key("origin") {
        Some("origin".to_string())
    } else if items.len() == 1 {
        items.keys().next().cloned()
    } else {
        None
    }
}

fn git_overlay_config_remotes(repo: &Repository) -> BTreeMap<String, String> {
    let Some(ctx) = GitConfigContext::discover(repo.root()) else {
        return BTreeMap::new();
    };
    let mut paths = ctx.layered_paths();
    paths.push(repo.heddle_dir().join("git").join("config"));
    ctx.remotes(paths)
}

/// The resolved Git directory layout for a repository, used to read remote
/// definitions from `.git/config` and its layered companions.
struct GitConfigContext {
    git_dir: PathBuf,
    common_dir: PathBuf,
    branch: Option<String>,
}

impl GitConfigContext {
    fn discover(root: &Path) -> Option<Self> {
        let git = SleyRepository::discover(root).ok()?;
        Some(Self {
            git_dir: git.git_dir().to_path_buf(),
            common_dir: git.common_dir().to_path_buf(),
            branch: git
                .head()
                .ok()
                .and_then(|head| head.symbolic_target.map(|name| name.to_string()))
                .and_then(|name| name.strip_prefix("refs/heads/").map(str::to_string)),
        })
    }

    /// The standard repository config files, ordered highest-precedence first:
    /// the per-worktree `config.worktree` (only when `extensions.worktreeConfig`
    /// is enabled), then the git-dir `config`, then the shared common-dir
    /// `config` for linked worktrees.
    fn layered_paths(&self) -> Vec<std::path::PathBuf> {
        let mut paths = Vec::new();
        if self.worktree_config_enabled() {
            paths.push(self.git_dir.join("config.worktree"));
        }
        paths.push(self.git_dir.join("config"));
        if self.common_dir != self.git_dir {
            paths.push(self.common_dir.join("config"));
        }
        paths
    }

    fn worktree_config_enabled(&self) -> bool {
        let mut paths = vec![self.git_dir.join("config")];
        if self.common_dir != self.git_dir {
            paths.push(self.common_dir.join("config"));
        }
        self.load(paths)
            .and_then(|config| config.get_bool("extensions", None, "worktreeConfig"))
            .unwrap_or(false)
    }

    /// The file a write to remote `name` must target so the next
    /// `remote list` read resolves the value we just wrote. The
    /// highest-precedence file that already defines the remote, resolved
    /// through `include.path`/`includeIf` indirection — not merely the
    /// top-level layer that *follows* the include, whose physical text has
    /// no `[remote]` section to edit. When no file defines the remote, the
    /// common config — git's default target for a brand-new remote.
    ///
    /// Errors when the defining file lies outside the repository's Git
    /// directory (reached via an include), so a reported-successful write is
    /// never a silent no-op against a file heddle won't edit.
    fn write_file_for(&self, name: &str) -> Result<std::path::PathBuf> {
        match self.defining_files_for(name).into_iter().next() {
            Some(path) => {
                if !self.owns_config_file(&path) {
                    anyhow::bail!(RecoveryAdvice::git_remote_in_included_config(name, &path));
                }
                Ok(path)
            }
            None => Ok(self.common_dir.join("config")),
        }
    }

    /// Every file that currently defines remote `name`, resolved through
    /// includes. A remove must clear all of them, otherwise a
    /// lower-precedence definition resurfaces — or a higher-precedence one
    /// keeps winning — on the next read, leaving the "successful" removal
    /// silently divergent. Errors when any defining file lies outside the
    /// repository's Git directory rather than no-op'ing against it.
    fn remove_files_for(&self, name: &str) -> Result<Vec<std::path::PathBuf>> {
        let files = self.defining_files_for(name);
        for path in &files {
            if !self.owns_config_file(path) {
                anyhow::bail!(RecoveryAdvice::git_remote_in_included_config(name, path));
            }
        }
        Ok(files)
    }

    /// The file(s) whose `[remote "<name>"]` section the reader resolves,
    /// following `include.path`/`includeIf`. Returned highest-precedence
    /// first, matching `remotes` read precedence (first-seen wins). The
    /// section metadata records the file each section physically lives in,
    /// so an include-defined remote resolves to the included file — the one
    /// a write must edit — not the including config.
    fn defining_files_for(&self, name: &str) -> Vec<std::path::PathBuf> {
        let mut files = Vec::new();
        let Some(stack) = self.config_stack() else {
            return files;
        };
        for entry in stack.entries.iter().rev() {
            if entry.section.eq_ignore_ascii_case("remote")
                && entry.subsection.as_deref() == Some(name)
                && let Some(path) = config_entry_origin_path(entry)
                && !files.contains(&path)
            {
                files.push(path);
            }
        }
        files
    }

    /// Whether heddle may rewrite `path`: only config files within the
    /// repository's own Git directory tree (git-dir / common-dir). A section
    /// pulled in from a file outside that tree via `include.path`/`includeIf`
    /// (e.g. a user-global config) is not ours to edit.
    fn owns_config_file(&self, path: &Path) -> bool {
        let target = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
        [&self.git_dir, &self.common_dir].into_iter().any(|root| {
            let root = root.canonicalize().unwrap_or_else(|_| root.clone());
            target.starts_with(&root)
        })
    }

    fn remotes(&self, paths: Vec<std::path::PathBuf>) -> BTreeMap<String, String> {
        let mut remotes = BTreeMap::new();
        for path in paths {
            let Some(config) = self.load_one(&path, true) else {
                continue;
            };
            for section in &config.sections {
                if !section.name.eq_ignore_ascii_case("remote") {
                    continue;
                }
                let Some(name) = section.subsection.as_deref() else {
                    continue;
                };
                let Some(url) = config_section_value(section, "url") else {
                    continue;
                };
                remotes
                    .entry(name.to_string())
                    .or_insert_with(|| url.to_string());
            }
        }
        remotes
    }

    fn load(&self, paths: Vec<PathBuf>) -> Option<GitConfig> {
        let mut merged = GitConfig::default();
        for path in paths.into_iter().rev() {
            let Some(config) = self.load_one(&path, true) else {
                continue;
            };
            merged.sections.extend(config.sections);
        }
        Some(merged)
    }

    fn config_stack(&self) -> Option<ConfigStack> {
        let context = ConfigIncludeContext {
            git_dir: Some(self.git_dir.clone()),
            current_branch: self.branch.clone(),
        };
        let mut stack = ConfigStack::new();
        for path in self.layered_paths().into_iter().rev() {
            let scope = if path
                .file_name()
                .is_some_and(|name| name == "config.worktree")
            {
                ConfigScope::Worktree
            } else {
                ConfigScope::Local
            };
            stack.push_file(&path, scope, true, &context).ok()?;
        }
        Some(stack)
    }

    fn load_one(&self, path: &Path, follow_includes: bool) -> Option<GitConfig> {
        let bytes = fs::read(path).ok()?;
        let config = GitConfig::parse(&bytes).ok()?;
        if !follow_includes {
            return Some(config);
        }
        let base = path.parent().unwrap_or_else(|| Path::new("."));
        config
            .resolve_includes(
                base,
                &ConfigIncludeContext {
                    git_dir: Some(self.git_dir.clone()),
                    current_branch: self.branch.clone(),
                },
            )
            .ok()
    }
}

fn config_entry_origin_path(entry: &ConfigStackEntry) -> Option<PathBuf> {
    (entry.origin.kind == ConfigOriginKind::File).then(|| PathBuf::from(&entry.origin.name))
}

fn config_section_value<'a>(
    section: &'a sley::plumbing::sley_config::ConfigSection,
    key: &str,
) -> Option<&'a str> {
    section
        .entries
        .iter()
        .rev()
        .find(|entry| entry.key.eq_ignore_ascii_case(key))
        .and_then(|entry| entry.value.as_deref())
}

fn sync_git_overlay_remote_add(repo: &Repository, name: &str, url: &str) -> Result<()> {
    if repo.capability() != RepositoryCapability::GitOverlay {
        return Ok(());
    }
    validate_git_overlay_remote_name(name)?;
    let ctx = GitConfigContext::discover(repo.root())
        .context("Git-overlay remote add requires a writable Git config")?;
    upsert_git_remote_config(&ctx.write_file_for(name)?, name, url)
}

fn sync_git_overlay_remote_remove(repo: &Repository, name: &str) -> Result<()> {
    if repo.capability() != RepositoryCapability::GitOverlay {
        return Ok(());
    }
    let Some(ctx) = GitConfigContext::discover(repo.root()) else {
        return Ok(());
    };
    for config_path in ctx.remove_files_for(name)? {
        remove_git_remote_config(&config_path, name)?;
    }
    Ok(())
}

fn validate_git_overlay_remote_name(name: &str) -> Result<()> {
    if name.trim().is_empty()
        || name.starts_with('-')
        || name.bytes().any(|byte| byte < 0x20 || byte == 0x7f)
        || name
            .chars()
            .any(|ch| matches!(ch, ' ' | '~' | '^' | ':' | '?' | '*' | '[' | '\\'))
        || name.contains("..")
        || name.contains("//")
        || name.starts_with('/')
        || name.ends_with('/')
        || name.starts_with('.')
        || name.ends_with(".lock")
    {
        anyhow::bail!(RecoveryAdvice::git_remote_name_invalid(name));
    }
    Ok(())
}

/// Add or replace the `[remote "<name>"]` section in a single physical config
/// file. Every existing definition of the remote in that file is dropped before
/// a fresh canonical section is appended, so an upsert replaces rather than
/// appends a duplicate that the first-seen section would win over on the next
/// read.
fn upsert_git_remote_config(config_path: &Path, name: &str, url: &str) -> Result<()> {
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let contents = fs::read_to_string(config_path).unwrap_or_default();
    let mut contents = remove_git_config_named_section(&contents, "remote", name);
    if !contents.ends_with('\n') && !contents.is_empty() {
        contents.push('\n');
    }
    let fetch = format!("+refs/heads/*:refs/remotes/{name}/*");
    contents.push_str(&format!(
        "[remote \"{}\"]\n\turl = {}\n\tfetch = {}\n",
        escape_git_config_section(name),
        quote_git_config_value(url),
        quote_git_config_value(&fetch)
    ));
    write_file_atomic(config_path, contents.as_bytes())?;
    Ok(())
}

/// Remove every `[remote "<name>"]` section from a single physical config file
/// that uses the normal quoted subsection form. No-ops when the file is absent
/// or defines no such remote.
fn remove_git_remote_config(config_path: &Path, name: &str) -> Result<()> {
    if !config_path.exists() {
        return Ok(());
    }
    let contents = fs::read_to_string(config_path)
        .with_context(|| format!("reading git config at {}", config_path.display()))?;
    let updated = remove_git_config_named_section(&contents, "remote", name);
    if updated == contents {
        return Ok(());
    }
    write_file_atomic(config_path, updated.as_bytes())?;
    Ok(())
}

fn remove_git_config_named_section(contents: &str, section: &str, subsection_name: &str) -> String {
    let mut output = Vec::new();
    let mut skipping = false;
    for line in contents.lines() {
        if let Some(name) = parse_git_config_subsection_name(line, section) {
            skipping = name == subsection_name;
        } else if is_git_config_section_header(line) {
            skipping = false;
        }
        if !skipping {
            output.push(line);
        }
    }
    let mut text = output.join("\n");
    if contents.ends_with('\n') && !text.is_empty() {
        text.push('\n');
    }
    text
}

fn parse_git_config_subsection_name(line: &str, section: &str) -> Option<String> {
    let trimmed = line.trim_start();
    let end = trimmed.find(']')?;
    let inner = trimmed.strip_prefix('[')?[..end - 1].trim();
    let (parsed_section, rest) = inner
        .split_once(char::is_whitespace)
        .map(|(section, rest)| (section, Some(rest.trim_start())))
        .unwrap_or((inner, None));
    if !parsed_section.eq_ignore_ascii_case(section) {
        if let Some((dotted_section, dotted_subsection)) = inner.split_once('.')
            && dotted_section.eq_ignore_ascii_case(section)
        {
            return Some(dotted_subsection.to_string());
        }
        return None;
    }
    let rest = rest?;
    let quoted = rest.strip_prefix('"')?.strip_suffix('"')?;
    unescape_git_config_string(quoted)
}

fn is_git_config_section_header(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.starts_with('[') && trimmed.contains(']')
}

fn escape_git_config_section(value: &str) -> String {
    escape_git_config_value(value)
}

fn escape_git_config_value(value: &str) -> String {
    let mut out = String::new();
    for ch in value.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            '\u{0008}' => out.push_str("\\b"),
            ch => out.push(ch),
        }
    }
    out
}

fn quote_git_config_value(value: &str) -> String {
    format!("\"{}\"", escape_git_config_value(value))
}

fn unescape_git_config_string(value: &str) -> Option<String> {
    let mut out = String::new();
    let mut chars = value.chars();
    while let Some(ch) = chars.next() {
        if ch != '\\' {
            out.push(ch);
            continue;
        }
        match chars.next()? {
            '\\' => out.push('\\'),
            '"' => out.push('"'),
            'n' => out.push('\n'),
            't' => out.push('\t'),
            'r' => out.push('\r'),
            'b' => out.push('\u{0008}'),
            escaped => out.push(escaped),
        }
    }
    Some(out)
}

#[cfg(feature = "client")]
struct PullNetworkOptions<'a> {
    addr: SocketAddr,
    repo_path: Option<&'a str>,
    user_config: &'a UserConfig,
    server_key: Option<String>,
    remote_thread: &'a str,
    local_thread: Option<&'a str>,
    lazy: bool,
    cli: &'a Cli,
}

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

    fn init_git(root: &Path) {
        SleyRepository::init(root).expect("init git repo");
    }

    #[test]
    fn parses_quoted_url_with_equals_and_strips_quotes() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        fs::write(
            tmp.path().join(".git").join("config"),
            "[remote \"origin\"]\n\turl = \"https://example.com/repo?ref=main&a=b\"\n",
        )
        .unwrap();

        let remotes = plain_git_remote_items(tmp.path());

        assert_eq!(
            remotes.get("origin").map(String::as_str),
            Some("https://example.com/repo?ref=main&a=b"),
        );
    }

    #[test]
    fn strips_inline_comments_from_url() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        fs::write(
            tmp.path().join(".git").join("config"),
            "[remote \"origin\"]\n\turl = https://example.com/repo ; trailing comment\n",
        )
        .unwrap();

        let remotes = plain_git_remote_items(tmp.path());

        assert_eq!(
            remotes.get("origin").map(String::as_str),
            Some("https://example.com/repo"),
        );
    }

    #[test]
    fn follows_include_directives() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("extra.config"),
            "[remote \"upstream\"]\n\turl = https://example.com/upstream\n",
        )
        .unwrap();
        fs::write(git_dir.join("config"), "[include]\n\tpath = extra.config\n").unwrap();

        let remotes = plain_git_remote_items(tmp.path());

        assert_eq!(
            remotes.get("upstream").map(String::as_str),
            Some("https://example.com/upstream"),
        );
    }

    #[test]
    fn worktree_config_overrides_local_when_extension_enabled() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("config"),
            "[extensions]\n\tworktreeConfig = true\n\
             [remote \"origin\"]\n\turl = https://example.com/local\n",
        )
        .unwrap();
        fs::write(
            git_dir.join("config.worktree"),
            "[remote \"origin\"]\n\turl = https://example.com/worktree\n",
        )
        .unwrap();

        let remotes = plain_git_remote_items(tmp.path());

        assert_eq!(
            remotes.get("origin").map(String::as_str),
            Some("https://example.com/worktree"),
        );
    }

    #[test]
    fn ignores_worktree_config_when_extension_disabled() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("config"),
            "[remote \"origin\"]\n\turl = https://example.com/local\n",
        )
        .unwrap();
        fs::write(
            git_dir.join("config.worktree"),
            "[remote \"origin\"]\n\turl = https://example.com/worktree\n",
        )
        .unwrap();

        let remotes = plain_git_remote_items(tmp.path());

        assert_eq!(
            remotes.get("origin").map(String::as_str),
            Some("https://example.com/local"),
        );
    }

    #[test]
    fn remove_clears_worktree_layer_when_extension_enabled() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("config"),
            "[extensions]\n\tworktreeConfig = true\n\
             [remote \"origin\"]\n\turl = https://example.com/common\n",
        )
        .unwrap();
        fs::write(
            git_dir.join("config.worktree"),
            "[remote \"origin\"]\n\turl = https://example.com/worktree\n",
        )
        .unwrap();

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        for path in ctx.remove_files_for("origin").unwrap() {
            remove_git_remote_config(&path, "origin").unwrap();
        }

        // The visible (per-worktree) remote must be gone after a remove;
        // a common-only removal would leave it winning on the next read.
        assert!(!plain_git_remote_items(tmp.path()).contains_key("origin"));
    }

    #[test]
    fn add_targets_worktree_layer_so_next_read_reflects_it() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("config"),
            "[extensions]\n\tworktreeConfig = true\n",
        )
        .unwrap();
        fs::write(
            git_dir.join("config.worktree"),
            "[remote \"origin\"]\n\turl = https://example.com/old\n",
        )
        .unwrap();

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        upsert_git_remote_config(
            &ctx.write_file_for("origin").unwrap(),
            "origin",
            "https://example.com/new",
        )
        .unwrap();

        // The upsert must hit the per-worktree layer (where the remote
        // lives and wins on read); writing to common would leave the
        // stale per-worktree url winning, a silent read/write divergence.
        assert_eq!(
            plain_git_remote_items(tmp.path())
                .get("origin")
                .map(String::as_str),
            Some("https://example.com/new"),
        );
    }

    #[test]
    fn remove_clears_remote_defined_via_include_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("extra.config"),
            "[remote \"upstream\"]\n\turl = https://example.com/upstream\n",
        )
        .unwrap();
        fs::write(git_dir.join("config"), "[include]\n\tpath = extra.config\n").unwrap();

        // The reader follows the include, so the remote is visible...
        assert!(plain_git_remote_items(tmp.path()).contains_key("upstream"));

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        for path in ctx.remove_files_for("upstream").unwrap() {
            remove_git_remote_config(&path, "upstream").unwrap();
        }

        // ...and a remove must clear the section from the *included* file
        // it actually lives in, not no-op against the including config.
        assert!(!plain_git_remote_items(tmp.path()).contains_key("upstream"));
    }

    #[test]
    fn write_to_included_remote_targets_the_defining_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("extra.config"),
            "[remote \"origin\"]\n\turl = https://example.com/old\n",
        )
        .unwrap();
        fs::write(git_dir.join("config"), "[include]\n\tpath = extra.config\n").unwrap();

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        let target = ctx.write_file_for("origin").unwrap();
        assert_eq!(target, git_dir.join("extra.config"));
        upsert_git_remote_config(&target, "origin", "https://example.com/new").unwrap();

        assert_eq!(
            plain_git_remote_items(tmp.path())
                .get("origin")
                .map(String::as_str),
            Some("https://example.com/new"),
        );
    }

    #[test]
    fn write_to_remote_in_external_include_errors_rather_than_no_ops() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        // An included config that lives *outside* the repository's Git tree.
        let external = tmp.path().join("external.config");
        fs::write(
            &external,
            "[remote \"origin\"]\n\turl = https://example.com/external\n",
        )
        .unwrap();
        fs::write(
            git_dir.join("config"),
            format!("[include]\n\tpath = {}\n", external.display()),
        )
        .unwrap();

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        assert!(ctx.write_file_for("origin").is_err());
        assert!(ctx.remove_files_for("origin").is_err());
    }

    #[test]
    fn add_new_remote_targets_common_layer() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("config"),
            "[extensions]\n\tworktreeConfig = true\n",
        )
        .unwrap();

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        // A brand-new remote (no layer defines it yet) follows git's
        // default: the common config.
        assert_eq!(
            ctx.write_file_for("origin").unwrap(),
            git_dir.join("config")
        );
        upsert_git_remote_config(
            &ctx.write_file_for("origin").unwrap(),
            "origin",
            "https://example.com/new",
        )
        .unwrap();
        assert_eq!(
            plain_git_remote_items(tmp.path())
                .get("origin")
                .map(String::as_str),
            Some("https://example.com/new"),
        );
    }

    #[test]
    fn remove_clears_comment_suffixed_remote_header() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        // A valid Git header Sley accepts but the hand-rolled writer didn't:
        // an inline comment trails the `[remote "origin"]` header.
        fs::write(
            git_dir.join("config"),
            "[remote \"origin\"] # primary mirror\n\turl = https://example.com/repo\n",
        )
        .unwrap();

        // The reader resolves it, so it shows up in `remote list`...
        assert!(plain_git_remote_items(tmp.path()).contains_key("origin"));

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        for path in ctx.remove_files_for("origin").unwrap() {
            remove_git_remote_config(&path, "origin").unwrap();
        }

        // ...so a remove must actually clear it, not silently no-op against a
        // header form the writer can't parse.
        assert!(!plain_git_remote_items(tmp.path()).contains_key("origin"));
    }

    #[test]
    fn remove_clears_dotted_remote_header() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        // The legacy dotted subsection form, equally valid to Sley.
        fs::write(
            git_dir.join("config"),
            "[remote.origin]\n\turl = https://example.com/repo\n",
        )
        .unwrap();

        assert!(plain_git_remote_items(tmp.path()).contains_key("origin"));

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        for path in ctx.remove_files_for("origin").unwrap() {
            remove_git_remote_config(&path, "origin").unwrap();
        }

        assert!(!plain_git_remote_items(tmp.path()).contains_key("origin"));
    }

    #[test]
    fn upsert_replaces_comment_suffixed_remote_header_without_duplicating() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("config"),
            "[remote \"origin\"] # primary mirror\n\turl = https://example.com/old\n",
        )
        .unwrap();

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        upsert_git_remote_config(
            &ctx.write_file_for("origin").unwrap(),
            "origin",
            "https://example.com/new",
        )
        .unwrap();

        // The upsert must update the existing section, not append a second
        // `[remote "origin"]` the first-seen (stale) section wins over on read.
        assert_eq!(
            plain_git_remote_items(tmp.path())
                .get("origin")
                .map(String::as_str),
            Some("https://example.com/new"),
        );
    }

    #[test]
    fn upsert_replaces_dotted_remote_header() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_git(tmp.path());
        let git_dir = tmp.path().join(".git");
        fs::write(
            git_dir.join("config"),
            "[remote.origin]\n\turl = https://example.com/old\n",
        )
        .unwrap();

        let ctx = GitConfigContext::discover(tmp.path()).unwrap();
        upsert_git_remote_config(
            &ctx.write_file_for("origin").unwrap(),
            "origin",
            "https://example.com/new",
        )
        .unwrap();

        assert_eq!(
            plain_git_remote_items(tmp.path())
                .get("origin")
                .map(String::as_str),
            Some("https://example.com/new"),
        );
    }
}