dracon-sync 0.112.13

Invisible git sync daemon for deterministic AI-assisted development
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
#![warn(missing_docs)]

//! Dracon Sync — git sync automation daemon.

mod bump;
mod cooldown;
mod daemon;
mod exclude;
mod git;
mod helpers;
mod log;
mod nix;
mod ownership;
mod policy;
mod print;
mod release;
mod report;
mod secrets;
mod standard_files;
mod sync;
mod test_helpers;
mod visibility;

/// Render a boolean as a compact on/off string for tables and flags rows.
fn onoff(b: bool) -> &'static str {
    if b {
        "on"
    } else {
        "off"
    }
}

use anyhow::Result;
use clap::{ArgAction, Parser, Subcommand};
use daemon::{list_stuck_repos, run_daemon, run_once, unstuck_repo};
use exclude::excluded_dir_names_set;
use git::{consolidate_to_main, detect_orphan_origin, fix_orphan_origin, has_both_main_and_master};
use policy::freeze_reason;
use policy::{resolve_policy_path, timestamp_secs, SyncPolicy};
use report::{
    push_large_blob_threshold_bytes, run_repair_concerns, run_repair_warns, run_repos_report,
    ConcernRepairFilter, RepoFilter,
};
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use sync::sync_repo;

#[derive(Parser, Debug)]
#[command(name = "dracon-sync")]
#[command(about = "Git sync automation — auto-commit, push, and mirror your repos")]
#[command(
    after_help = "ENVIRONMENT:\n  DRACON_SYNC_GIT_BIN    Override path to git binary (checked every call)\n  DRACON_SYNC_POLICY    Custom sync policy file path\n  DRACON_SYNC_STATE_DIR Custom state directory path"
)]
#[command(version)]
struct Cli {
    /// Increase output verbosity. Can be repeated up to 2 times (-v, -vv).
    #[arg(global = true, short, long, action = ArgAction::Count)]
    verbose: u8,
    #[command(subcommand)]
    cmd: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Show resolved policy path and sync scope.
    Status {
        /// Emit machine-readable JSON.
        #[arg(long)]
        json: bool,
    },
    /// One-off report across discovered repositories.
    Repos {
        /// Show only concern repos.
        #[arg(long)]
        only_concern: bool,
        /// Show only warn repos.
        #[arg(long, conflicts_with = "only_concern")]
        only_warn: bool,
        /// Emit machine-readable JSON.
        #[arg(long)]
        json: bool,
        /// Sort repos by field: updated, name, modified, ahead, behind.
        #[arg(long, default_value = "updated")]
        sort: String,
        /// Filter repos by name (substring match).
        #[arg(long)]
        filter: Option<String>,
        /// Show full repo paths instead of short names.
        #[arg(long)]
        full_path: bool,
    },
    /// Check daemon health (policy valid, daemon responsive, repos healthy).
    Health {
        /// Emit machine-readable JSON.
        #[arg(long)]
        json: bool,
    },
    /// Print Prometheus-style metrics.
    Metrics,
    /// Run one sync pass.
    Once,
    /// Run continuous sync loop.
    Daemon {
        /// Override the policy scan interval (seconds). Defaults to policy value.
        #[arg(long)]
        interval_secs: Option<u64>,
    },
    /// Sync one or more repositories now.
    SyncNow {
        /// The repository path(s) to sync immediately.
        repos: Vec<PathBuf>,
        /// Sync repos currently reported as WARN (dirty-only triage).
        #[arg(long, conflicts_with = "repos")]
        warns: bool,
        /// Preview what would be done without making any changes.
        #[arg(long)]
        dry_run: bool,
    },
    /// Pause sync (creates freeze marker).
    Pause,
    /// Resume sync (removes freeze marker).
    Resume,
    /// Manage sync configuration.
    Config {
        #[command(subcommand)]
        cmd: ConfigCommands,
    },
    /// Repair and manage repositories (concerns, warns, origins, stuck repos, dual-branch).
    Repair {
        #[command(subcommand)]
        cmd: RepairCommands,
    },
    /// Publish to package registries and check publish status.
    Publish {
        #[command(subcommand)]
        cmd: PublishCommands,
    },
    /// Scaffold standard files (LICENSE) into repositories.
    Scaffold {
        /// Repository path to scaffold. Defaults to all discovered repos.
        #[arg(long)]
        repo: Option<PathBuf>,
        /// Only scaffold these files (by name, e.g. LICENSE).
        #[arg(long)]
        files: Vec<String>,
        /// Overwrite existing files with template versions.
        #[arg(long)]
        overwrite: bool,
        /// Preview what would be done without making any changes.
        #[arg(long)]
        dry_run: bool,
    },
    /// Detect and report repository ownership (safety guard for
    /// auto-commit/auto-push).
    Ownership {
        /// Repository path. Defaults to all discovered repos.
        #[arg(long)]
        repo: Option<PathBuf>,
        /// Show the raw signals checked (git config, HEAD author, origin URL)
        /// in addition to the classified report.
        #[arg(long, conflicts_with = "json")]
        explain: bool,
        /// Emit machine-readable JSON.
        #[arg(long, conflicts_with = "explain")]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
enum RepairCommands {
    /// Repair concern repos (dry-run by default; use --apply to execute).
    Concerns {
        /// Execute git operations to repair concerns.
        #[arg(long)]
        apply: bool,
        /// Only repair this repository path.
        #[arg(long)]
        repo: Option<PathBuf>,
        /// Override push timeout seconds for this run.
        #[arg(long)]
        push_timeout_secs: Option<u64>,
        /// Retry count for push operations.
        #[arg(long, default_value_t = 3)]
        push_retries: u32,
        /// Allow rewrite of large blobs even when paths are outside excluded dirs.
        #[arg(long)]
        rewrite_large_any: bool,
        /// Only repair stuck push concerns.
        #[arg(long, conflicts_with = "only_stuck_pull")]
        only_stuck_push: bool,
        /// Only repair stuck pull concerns.
        #[arg(long, conflicts_with = "only_stuck_push")]
        only_stuck_pull: bool,
        /// Emit machine-readable JSON.
        #[arg(long)]
        json: bool,
    },
    /// Repair warn repos (dirty-only triage; dry-run by default).
    Warns {
        /// Execute git operations to repair warns.
        #[arg(long)]
        apply: bool,
        /// Only repair this repository path.
        #[arg(long)]
        repo: Option<PathBuf>,
        /// Emit machine-readable JSON.
        #[arg(long)]
        json: bool,
    },
    /// Detect and repair origin URLs pointing to orphan -N suffixed repos.
    Origins {
        /// Execute git operations to repair origins.
        #[arg(long)]
        apply: bool,
    },
    /// List repos that are permanently stuck on push.
    StuckList,
    /// Unstuck a repo that was marked as permanently stuck.
    StuckUnstuck {
        /// The repository path to unstuck.
        repo: PathBuf,
    },
    /// List repos that have both main and master branches.
    DualBranchList,
    /// Consolidate a repo with both main and master to main only.
    DualBranchRepair {
        /// The repository path to consolidate.
        repo: PathBuf,
    },
}

#[derive(Subcommand, Debug)]
enum PublishCommands {
    /// Publish a repository to configured package registries.
    Run {
        /// The repository path to publish.
        repo: PathBuf,
        /// Only publish to these target names (defaults to all configured).
        #[arg(long)]
        targets: Vec<String>,
        /// Skip the dry-run check and publish directly.
        #[arg(long)]
        skip_dry_run: bool,
    },
    /// Show publish status for a repository across configured registries.
    Status {
        /// The repository path to check.
        repo: PathBuf,
        /// Emit machine-readable JSON.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
enum ConfigCommands {
    /// Open sync policy in the system editor.
    Edit,
    /// Validate the sync policy for errors and warnings.
    Validate,
}

#[tokio::main]
async fn main() -> Result<()> {
    // If output is piped (e.g. `dracon-sync repos | head`), stdout can become a broken pipe.
    // Rust's default printing panics on write errors; convert that specific panic into a clean exit.
    let default_panic_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let msg = info.to_string();
        if msg.contains("Broken pipe") {
            std::process::exit(0);
        }
        default_panic_hook(info);
    }));

    let cli = Cli::parse();
    daemon::VERBOSITY.store(cli.verbose, Ordering::SeqCst);
    let policy_path = resolve_policy_path()?;

    match cli.cmd {
        Command::Status { json } => {
            let policy = SyncPolicy::load(&policy_path)?;
            let roots = policy.watch_root_paths();
            let excluded_dir_names = excluded_dir_names_set(&policy);
            let repos = git::discover_git_repos(
                &roots,
                &excluded_dir_names,
                &policy.exclude_repos,
                Some(&policy.system_repo),
            );
            let freeze = freeze_reason(&policy_path);
            if json {
                let payload = report::StatusJson {
                    policy: policy_path.display().to_string(),
                    roots: roots.iter().map(|p| p.display().to_string()).collect(),
                    repos_discovered: repos.len(),
                    pulse_interval_secs: policy.pulse_interval_secs,
                    inactivity_push_delay_secs: policy.inactivity_push_delay_secs,
                    freeze: freeze
                        .map(|r| format!("ON ({})", r))
                        .unwrap_or_else(|| "OFF".to_string()),
                    auto_commit: policy.auto_commit,
                    auto_pull: policy.auto_pull,
                    auto_push: policy.auto_push,
                    auto_bump_versions: policy.auto_bump_versions,
                    auto_repair_concerns: policy.auto_repair_concerns,
                    auto_repair_warns: policy.auto_repair_warns,
                    auto_rewrite_large_blobs: policy.auto_rewrite_large_blobs,
                    max_stage_file_bytes: policy.max_stage_file_bytes,
                    push_blob_threshold_bytes: push_large_blob_threshold_bytes(&policy),
                    exclude_dirs: policy.exclude_dir_names.clone(),
                    exclude_file_patterns: policy.exclude_file_patterns.clone(),
                    pull_op_timeout_secs: policy.pull_op_timeout_secs,
                    push_op_timeout_secs: policy.push_op_timeout_secs,
                    repo_sync_timeout_secs: policy.repo_sync_timeout_secs,
                    stage_op_timeout_secs: policy.stage_op_timeout_secs,
                    stage_cooldown_secs: policy.stage_cooldown_secs,
                    push_retries: policy.push_retries,
                    repair_cooldown_secs: policy.repair_cooldown_secs,
                    incident_ledger_max_lines: policy.incident_ledger_max_lines,
                    incident_ledger_max_age_days: policy.incident_ledger_max_age_days,
                    system_repo: policy.system_repo.clone(),
                    backup_policy: policy.backup_policy.clone(),
                    backup_dir: policy.backup_dir.clone(),
                    remotes: policy.remotes.len(),
                    remote_configs: policy
                        .remotes
                        .iter()
                        .map(|r| report::RemoteStatus {
                            name: r.name.clone(),
                            auth_type: format!("{:?}", r.auth_type).to_lowercase(),
                            auto_create: r.auto_create,
                            priority: r.priority,
                        })
                        .collect(),
                };
                println!("{}", serde_json::to_string_pretty(&payload)?);
            } else {
                use comfy_table::{
                    presets::UTF8_FULL_CONDENSED, Cell, Color, ContentArrangement, Table,
                };

                let mut table = Table::new();
                table.load_preset(UTF8_FULL_CONDENSED);
                table.set_content_arrangement(ContentArrangement::DynamicFullWidth);
                table.set_header(vec![Cell::new("KEY"), Cell::new("VALUE")]);

                // Policy path
                table.add_row(vec![
                    Cell::new("📜 Policy"),
                    Cell::new(policy_path.display().to_string()),
                ]);
                // Summary one-liner for quick scanning
                table.add_row(vec![
                    Cell::new("📋 Summary"),
                    Cell::new(format!(
                        "{} repos · {} watch root(s) · pulse {}",
                        repos.len(),
                        roots.len(),
                        crate::print::format_secs(policy.pulse_interval_secs)
                    )),
                ]);

                // Roots
                let roots_str: Vec<String> =
                    roots.iter().map(|p| p.display().to_string()).collect();
                table.add_row(vec![Cell::new("🔁 Roots"), Cell::new(roots_str.join(", "))]);

                // Repos
                table.add_row(vec![Cell::new("📦 Repos"), Cell::new(repos.len())]);

                // Pulse & Inactivity
                table.add_row(vec![
                    Cell::new("⏱️ Pulse"),
                    Cell::new(crate::print::format_secs(policy.pulse_interval_secs)),
                ]);
                table.add_row(vec![
                    Cell::new("⏳ Inactivity"),
                    Cell::new(crate::print::format_secs(policy.inactivity_push_delay_secs)),
                ]);

                // Freeze
                let freeze_str = freeze
                    .map(|r| format!("ON ({})", r))
                    .unwrap_or_else(|| "OFF".to_string());
                let freeze_color = if !print::should_color() {
                    Color::Reset
                } else if freeze_str == "OFF" {
                    Color::Green
                } else {
                    Color::Red
                };
                table.add_row(vec![
                    Cell::new("⏸️ Freeze"),
                    Cell::new(freeze_str).fg(freeze_color),
                ]);

                // Flags
                let flags = [
                    format!("commit={}", onoff(policy.auto_commit)),
                    format!("pull={}", onoff(policy.auto_pull)),
                    format!("push={}", onoff(policy.auto_push)),
                    format!("bump={}", onoff(policy.auto_bump_versions)),
                    format!("repair_concerns={}", onoff(policy.auto_repair_concerns)),
                    format!("repair_warns={}", onoff(policy.auto_repair_warns)),
                    format!(
                        "rewrite_large_blobs={}",
                        onoff(policy.auto_rewrite_large_blobs)
                    ),
                ]
                .join("  ");
                table.add_row(vec![Cell::new("⚙️ Flags"), Cell::new(flags)]);

                // Limits
                table.add_row(vec![
                    Cell::new("📏 Max stage file"),
                    Cell::new(format!(
                        "{} ({})",
                        crate::print::format_bytes(policy.max_stage_file_bytes),
                        policy.max_stage_file_bytes
                    )),
                ]);
                table.add_row(vec![
                    Cell::new("🧱 Push blob threshold"),
                    Cell::new(format!(
                        "{} ({})",
                        crate::print::format_bytes(push_large_blob_threshold_bytes(&policy)),
                        push_large_blob_threshold_bytes(&policy)
                    )),
                ]);

                // Exclude
                if !policy.exclude_dir_names.is_empty() {
                    table.add_row(vec![
                        Cell::new("🚫 Exclude dirs"),
                        Cell::new(policy.exclude_dir_names.join(", ")),
                    ]);
                }
                if !policy.exclude_file_patterns.is_empty() {
                    table.add_row(vec![
                        Cell::new("🚫 Exclude patterns"),
                        Cell::new(policy.exclude_file_patterns.join(", ")),
                    ]);
                }

                // Timeouts
                table.add_row(vec![
                    Cell::new("⏱️ Pull timeout"),
                    Cell::new(crate::print::format_secs(policy.pull_op_timeout_secs)),
                ]);
                table.add_row(vec![
                    Cell::new("⏱️ Push timeout"),
                    Cell::new(crate::print::format_secs(policy.push_op_timeout_secs)),
                ]);
                table.add_row(vec![
                    Cell::new("⏱️ Repo sync timeout"),
                    Cell::new(crate::print::format_secs(policy.repo_sync_timeout_secs)),
                ]);
                table.add_row(vec![
                    Cell::new("⏱️ Stage timeout"),
                    Cell::new(crate::print::format_secs(policy.stage_op_timeout_secs)),
                ]);
                table.add_row(vec![
                    Cell::new("⏸️  Stage cooldown"),
                    Cell::new(crate::print::format_secs(policy.stage_cooldown_secs)),
                ]);
                table.add_row(vec![
                    Cell::new("🔁 Push retries"),
                    Cell::new(policy.push_retries),
                ]);

                // Repair
                table.add_row(vec![
                    Cell::new("🧯 Repair cooldown"),
                    Cell::new(crate::print::format_secs(policy.repair_cooldown_secs)),
                ]);
                table.add_row(vec![
                    Cell::new("📒 Incident ledger"),
                    Cell::new(format!(
                        "{} lines · {}d retention",
                        policy.incident_ledger_max_lines, policy.incident_ledger_max_age_days
                    )),
                ]);

                // System repo
                if !policy.system_repo.is_empty() {
                    table.add_row(vec![
                        Cell::new("🏛️ System repo"),
                        Cell::new(&policy.system_repo),
                    ]);
                }

                // Backup
                if !policy.backup_policy.is_empty() || !policy.backup_dir.is_empty() {
                    table.add_row(vec![
                        Cell::new("🧰 Backup"),
                        Cell::new(format!(
                            "policy={} dir={}",
                            policy.backup_policy, policy.backup_dir
                        )),
                    ]);
                }

                // Remotes
                table.add_row(vec![
                    Cell::new("🌐 Remotes"),
                    Cell::new(policy.remotes.len()),
                ]);

                println!("{table}");
            }
        }
        Command::Config { cmd } => match cmd {
            ConfigCommands::Edit => {
                policy::open_policy_in_editor(&policy_path)?;
            }
            ConfigCommands::Validate => {
                let result = policy::validate_config(&policy_path);
                if result.is_valid() {
                    println!("✅ Policy is valid");
                } else {
                    println!("❌ Policy has errors:");
                    for e in &result.errors {
                        println!("  ERROR: {}", e);
                    }
                    if !result.warnings.is_empty() {
                        println!("\n⚠️  Warnings:");
                        for w in &result.warnings {
                            println!("  WARNING: {}", w);
                        }
                    }
                    std::process::exit(1);
                }
            }
        },
        Command::Pause => {
            if let Some(home) = dirs::home_dir() {
                let marker = home.join(".dracon").join("dracon-sync.freeze");
                std::fs::write(&marker, format!("paused at {}\n", timestamp_secs()))?;
                println!("⏸️  Sync paused (freeze marker: {})", marker.display());
            } else {
                anyhow::bail!("cannot determine home directory");
            }
        }
        Command::Resume => {
            if let Some(home) = dirs::home_dir() {
                let marker = home.join(".dracon").join("dracon-sync.freeze");
                if marker.exists() {
                    std::fs::remove_file(&marker)?;
                    println!("▶️  Sync resumed (freeze marker removed)");
                } else {
                    println!("ℹ️  No freeze marker found — sync was not paused");
                }
            } else {
                anyhow::bail!("cannot determine home directory");
            }
        }
        Command::Once => {
            run_once(&policy_path).await?;
        }
        Command::Daemon { interval_secs } => {
            run_daemon(policy_path, interval_secs).await?;
        }
        Command::SyncNow {
            repos,
            warns,
            dry_run,
        } => {
            if let Some(reason) = freeze_reason(&policy_path) {
                println!("⏸️ sync frozen ({})", reason);
                return Ok(());
            }
            if warns {
                run_repair_warns(&policy_path, !dry_run, None, false).await?;
                if dry_run {
                    println!(
                        "ℹ️ invoked via sync-now --dry-run; rerun `dracon-sync sync-now --warns` to execute"
                    );
                }
                return Ok(());
            }
            let policy = SyncPolicy::load(&policy_path)?;
            let excluded_dir_names = excluded_dir_names_set(&policy);
            for repo in repos {
                if daemon::is_repo_stuck(&repo) {
                    println!(
                        "🔒 {} is stuck on push. Run 'dracon-sync repair stuck-unstuck {}' first.",
                        repo.display(),
                        repo.display()
                    );
                    continue;
                }
                match sync_repo(
                    &repo,
                    &policy,
                    &excluded_dir_names,
                    0,
                    None,
                    dry_run,
                    Some(&policy_path),
                )
                .await
                {
                    Ok(crate::sync::SyncOutcome::Synced) => {
                        if dry_run {
                            println!("✅ dry-run complete for {}", repo.display());
                        } else {
                            println!("🔁 synced {}", repo.display());
                        }
                    }
                    Ok(crate::sync::SyncOutcome::NothingToDo) => {
                        if dry_run {
                            println!("✅ no sync changes needed for {}", repo.display());
                        } else {
                            println!("✅ no sync changes {}", repo.display());
                        }
                    }
                    Ok(crate::sync::SyncOutcome::Blocked) => {
                        println!(
                            "⏸️  sync blocked for {} (guard or manual intervention required)",
                            repo.display()
                        );
                    }
                    Err(e) => {
                        eprintln!("❌ error syncing {}: {}", repo.display(), e);
                    }
                }
            }
        }
        Command::Repos {
            only_concern,
            only_warn,
            json,
            sort,
            filter: filter_name,
            full_path,
        } => {
            let filter = if only_concern {
                RepoFilter::Concern
            } else if only_warn {
                RepoFilter::Warn
            } else {
                RepoFilter::All
            };
            run_repos_report(
                &policy_path,
                filter,
                json,
                &sort,
                filter_name.as_deref(),
                full_path,
            )
            .await?;
        }
        Command::Repair { cmd } => match cmd {
            RepairCommands::Concerns {
                apply,
                repo,
                push_timeout_secs,
                push_retries,
                rewrite_large_any,
                only_stuck_push,
                only_stuck_pull,
                json,
            } => {
                let filter = if only_stuck_push {
                    ConcernRepairFilter::StuckPush
                } else if only_stuck_pull {
                    ConcernRepairFilter::StuckPull
                } else {
                    ConcernRepairFilter::All
                };
                if !json {
                    println!("📜 Policy: {}", policy_path.display());
                    println!(
                        "🛠️ Mode: {}",
                        if apply {
                            "APPLY (mutating)"
                        } else {
                            "DRY-RUN (no changes)"
                        }
                    );
                    println!(
                        "⚙️ Push: timeout={}s retries={}",
                        push_timeout_secs.unwrap_or(0),
                        push_retries
                    );
                }
                run_repair_concerns(
                    &policy_path,
                    apply,
                    repo,
                    push_timeout_secs,
                    push_retries,
                    rewrite_large_any,
                    filter,
                    json,
                )
                .await?;
            }
            RepairCommands::Warns { apply, repo, json } => {
                if !json {
                    println!("📜 Policy: {}", policy_path.display());
                    println!(
                        "🧹 Warn mode: {}",
                        if apply {
                            "APPLY (mutating)"
                        } else {
                            "DRY-RUN (no changes)"
                        }
                    );
                }
                run_repair_warns(&policy_path, apply, repo, json).await?;
            }
            RepairCommands::Origins { apply } => {
                let policy = SyncPolicy::load(&policy_path)?;
                let roots = policy.watch_root_paths();
                let excluded_dir_names = excluded_dir_names_set(&policy);
                let repos = git::discover_git_repos(
                    &roots,
                    &excluded_dir_names,
                    &policy.exclude_repos,
                    Some(&policy.system_repo),
                );
                let mut found = 0;
                for repo in repos {
                    if let Some((current, canonical)) = detect_orphan_origin(&repo) {
                        println!("   {}: {} -> {}", repo.display(), current, canonical);
                        found += 1;
                        if apply {
                            if let Err(e) = fix_orphan_origin(&repo, &canonical) {
                                eprintln!("❌ failed to fix origin for {}: {}", repo.display(), e);
                            } else {
                                println!("✅ fixed origin for {}", repo.display());
                            }
                        }
                    }
                }
                if found == 0 {
                    println!("✅ no orphan origins found");
                } else if !apply {
                    println!("\n🔧 Run 'dracon-sync repair origins --apply' to fix them");
                }
            }
            RepairCommands::StuckList => {
                list_stuck_repos();
            }
            RepairCommands::StuckUnstuck { repo } => {
                unstuck_repo(&repo);
            }
            RepairCommands::DualBranchList => {
                let policy = SyncPolicy::load(&policy_path)?;
                let roots = policy.watch_root_paths();
                let excluded_dir_names = excluded_dir_names_set(&policy);
                let repos = git::discover_git_repos(
                    &roots,
                    &excluded_dir_names,
                    &policy.exclude_repos,
                    Some(&policy.system_repo),
                );
                let mut found = 0;
                for repo in repos {
                    if has_both_main_and_master(&repo) {
                        let branch =
                            git::current_branch(&repo).unwrap_or_else(|| "unknown".to_string());
                        println!("   {} (currently on {})", repo.display(), branch);
                        found += 1;
                    }
                }
                if found == 0 {
                    println!("✅ no repos with both main and master");
                } else {
                    println!("\n🔧 Run 'dracon-sync repair dual-branch-repair <path>' to consolidate to main");
                }
            }
            RepairCommands::DualBranchRepair { repo } => {
                if !has_both_main_and_master(&repo) {
                    println!("ℹ️ {} does not have both main and master", repo.display());
                    return Ok(());
                }
                println!("🔧 Consolidating {} to main...", repo.display());
                match consolidate_to_main(&repo).await {
                    Ok(()) => println!("✅ consolidated to main"),
                    Err(e) => {
                        eprintln!("❌ failed: {}", e);
                        return Err(e);
                    }
                }
            }
        },
        Command::Health { json } => {
            let policy = SyncPolicy::load(&policy_path)?;
            let validate_result = policy::validate_config(&policy_path);
            let roots = policy.watch_root_paths();
            let excluded_dir_names = excluded_dir_names_set(&policy);
            let repos = git::discover_git_repos(
                &roots,
                &excluded_dir_names,
                &policy.exclude_repos,
                Some(&policy.system_repo),
            );
            let freeze = freeze_reason(&policy_path);

            let frozen = freeze.is_some();
            let policy_ok = validate_result.is_valid();
            let daemon_ok = true;

            let status = if frozen || !policy_ok {
                "unhealthy"
            } else {
                "healthy"
            };

            if json {
                #[derive(serde::Serialize)]
                struct HealthJson<'a> {
                    status: &'a str,
                    frozen: bool,
                    freeze_reason: Option<&'a str>,
                    policy_valid: bool,
                    policy_errors: Vec<String>,
                    policy_warnings: Vec<String>,
                    daemon_running: bool,
                    roots: usize,
                    repos_discovered: usize,
                }
                let payload = HealthJson {
                    status,
                    frozen,
                    freeze_reason: freeze.as_deref(),
                    policy_valid: policy_ok,
                    policy_errors: validate_result.errors,
                    policy_warnings: validate_result.warnings,
                    daemon_running: daemon_ok,
                    roots: roots.len(),
                    repos_discovered: repos.len(),
                };
                println!("{}", serde_json::to_string_pretty(&payload)?);
            } else {
                use comfy_table::{
                    presets::UTF8_FULL_CONDENSED, Cell, Color, ContentArrangement, Table,
                };
                let color = print::should_color();
                let mk = |s: &str, c: Color| -> Cell {
                    if color {
                        Cell::new(s).fg(c)
                    } else {
                        Cell::new(s)
                    }
                };

                // ---- Summary line (one-liner) ----
                let summary_icon = if status == "healthy" { "" } else { "" };
                let daemon_str = if daemon_ok { "running" } else { "not running" };
                let freeze_str = freeze
                    .as_ref()
                    .map(|r| format!("⏸️ on ({})", r))
                    .unwrap_or_else(|| "off".to_string());
                let policy_str = if policy_ok { "valid" } else { "invalid" };
                println!(
                    "🏥 Health · {summary_icon} {status} · daemon {daemon_str} · freeze {freeze_str} · policy {policy_str}"
                );

                // ---- Main status table ----
                let mut table = Table::new();
                table
                    .load_preset(UTF8_FULL_CONDENSED)
                    .set_content_arrangement(ContentArrangement::Dynamic)
                    .set_header(vec![Cell::new(" "), Cell::new("KEY"), Cell::new("VALUE")]);

                let status_color = if status == "healthy" {
                    Color::Green
                } else {
                    Color::Red
                };
                table.add_row(vec![
                    mk(if status == "healthy" { "" } else { "" }, status_color),
                    Cell::new("Status"),
                    mk(status, status_color),
                ]);

                let daemon_color = if daemon_ok { Color::Green } else { Color::Red };
                table.add_row(vec![
                    mk(if daemon_ok { "" } else { "" }, daemon_color),
                    Cell::new("Daemon"),
                    if daemon_ok {
                        mk("running", Color::Green)
                    } else {
                        mk(
                            "not running · systemctl --user start dracon-sync.service",
                            Color::Red,
                        )
                    },
                ]);

                if let Some(reason) = &freeze {
                    table.add_row(vec![
                        mk("⏸️", Color::Yellow),
                        Cell::new("Freeze"),
                        mk(&format!("on ({})", reason), Color::Yellow),
                    ]);
                } else {
                    table.add_row(vec![Cell::new("  "), Cell::new("Freeze"), Cell::new("off")]);
                }

                let policy_color = if policy_ok { Color::Green } else { Color::Red };
                table.add_row(vec![
                    mk(if policy_ok { "" } else { "" }, policy_color),
                    Cell::new("Policy"),
                    mk(policy_str, policy_color),
                ]);

                table.add_row(vec![
                    Cell::new("📦"),
                    Cell::new("Repos"),
                    Cell::new(format!(
                        "{} discovered across {} roots",
                        repos.len(),
                        roots.len()
                    )),
                ]);

                println!("{table}");

                // ---- Errors block (if any) ----
                if !validate_result.errors.is_empty() {
                    println!();
                    println!("❌ Policy errors ({}):", validate_result.errors.len());
                    for e in &validate_result.errors {
                        println!("{e}");
                    }
                }

                // ---- Warnings block (grouped) ----
                if !validate_result.warnings.is_empty() {
                    println!();
                    println!("⚠️  Policy warnings ({}):", validate_result.warnings.len());
                    for w in &validate_result.warnings {
                        println!("   ⚠️  {w}");
                    }
                }

                // ---- Tip line ----
                if !daemon_ok || !policy_ok || !validate_result.errors.is_empty() {
                    println!();
                    println!("💡 Tip: run `dracon-sync config validate` for full diagnostics");
                }
            }
        }
        Command::Metrics => {
            let policy = SyncPolicy::load(&policy_path)?;
            let roots = policy.watch_root_paths();
            let excluded_dir_names = excluded_dir_names_set(&policy);
            let repos = git::discover_git_repos(
                &roots,
                &excluded_dir_names,
                &policy.exclude_repos,
                Some(&policy.system_repo),
            );
            let freeze = freeze_reason(&policy_path);
            let frozen = freeze.is_some();

            println!("# HELP dracon_sync_info Dracon sync daemon info");
            println!("# TYPE dracon_sync_info gauge");
            println!(
                "dracon_sync_info{{version=\"{}\"}} 1",
                env!("CARGO_PKG_VERSION")
            );

            println!(
                "# HELP dracon_sync_repos_discovered_total Number of git repositories discovered"
            );
            println!("# TYPE dracon_sync_repos_discovered_total gauge");
            println!("dracon_sync_repos_discovered_total {}", repos.len());

            println!("# HELP dracon_sync_watch_roots_total Number of configured watch roots");
            println!("# TYPE dracon_sync_watch_roots_total gauge");
            println!("dracon_sync_watch_roots_total {}", roots.len());

            println!("# HELP dracon_sync_remotes_total Number of configured remotes");
            println!("# TYPE dracon_sync_remotes_total gauge");
            println!("dracon_sync_remotes_total {}", policy.remotes.len());

            println!("# HELP dracon_sync_freeze_state Whether sync is currently frozen (1=frozen, 0=active)");
            println!("# TYPE dracon_sync_freeze_state gauge");
            println!("dracon_sync_freeze_state {}", if frozen { 1 } else { 0 });

            println!("# HELP dracon_sync_policy_auto_commit Whether auto-commit is enabled");
            println!("# TYPE dracon_sync_policy_auto_commit gauge");
            println!(
                "dracon_sync_policy_auto_commit {}",
                if policy.auto_commit { 1 } else { 0 }
            );

            println!("# HELP dracon_sync_policy_auto_push Whether auto-push is enabled");
            println!("# TYPE dracon_sync_policy_auto_push gauge");
            println!(
                "dracon_sync_policy_auto_push {}",
                if policy.auto_push { 1 } else { 0 }
            );

            println!("# HELP dracon_sync_policy_auto_pull Whether auto-pull is enabled");
            println!("# TYPE dracon_sync_policy_auto_pull gauge");
            println!(
                "dracon_sync_policy_auto_pull {}",
                if policy.auto_pull { 1 } else { 0 }
            );

            println!("# HELP dracon_sync_policy_auto_repair_concerns Whether auto-repair concerns is enabled");
            println!("# TYPE dracon_sync_policy_auto_repair_concerns gauge");
            println!(
                "dracon_sync_policy_auto_repair_concerns {}",
                if policy.auto_repair_concerns { 1 } else { 0 }
            );

            println!("# HELP dracon_sync_incident_ledger_max_lines Incident ledger max lines");
            println!("# TYPE dracon_sync_incident_ledger_max_lines gauge");
            println!(
                "dracon_sync_incident_ledger_max_lines {}",
                policy.incident_ledger_max_lines
            );

            let incident_path = report::incident_ledger_path(&policy_path);
            if incident_path.exists() {
                if let Ok(content) = std::fs::read_to_string(&incident_path) {
                    let lines = content.lines().filter(|l| !l.trim().is_empty()).count();
                    println!("# HELP dracon_sync_incident_ledger_lines_current Current number of lines in incident ledger");
                    println!("# TYPE dracon_sync_incident_ledger_lines_current gauge");
                    println!("dracon_sync_incident_ledger_lines_current {}", lines);
                }
            }

            if let Some(home) = dirs::home_dir() {
                let stuck_path = home.join(".local/state/dracon/dracon-sync-stuck-push-repos.json");
                if stuck_path.exists() {
                    if let Ok(content) = std::fs::read_to_string(&stuck_path) {
                        if let Ok(stuck) = serde_json::from_str::<Vec<serde_json::Value>>(&content)
                        {
                            println!("# HELP dracon_sync_stuck_repos_total Number of repos permanently stuck on push");
                            println!("# TYPE dracon_sync_stuck_repos_total gauge");
                            println!("dracon_sync_stuck_repos_total {}", stuck.len());
                        }
                    }
                }
            }

            println!("# HELP dracon_sync_push_retries Default push retry count");
            println!("# TYPE dracon_sync_push_retries gauge");
            println!("dracon_sync_push_retries {}", policy.push_retries);

            println!("# HELP dracon_sync_pulse_interval_secs Sync pulse interval in seconds");
            println!("# TYPE dracon_sync_pulse_interval_secs gauge");
            println!(
                "dracon_sync_pulse_interval_secs {}",
                policy.pulse_interval_secs
            );

            // Mass deletion guard removed — IndexLock fixes the clone race
        }
        Command::Publish { cmd } => match cmd {
            PublishCommands::Run {
                repo,
                targets,
                skip_dry_run: _,
            } => {
                let policy = SyncPolicy::load(&policy_path)?;
                if !policy.auto_publish {
                    anyhow::bail!(
                        "auto_publish is disabled in config. Enable it in your sync policy."
                    );
                }
                let repo_targets = if targets.is_empty() {
                    policy
                        .publish_targets
                        .iter()
                        .map(|t| t.name.clone())
                        .collect::<Vec<_>>()
                } else {
                    targets
                };
                let version = release::detect_project_version(&repo)
                    .map(|(v, _)| v)
                    .unwrap_or_else(|| "unknown".to_string());
                println!(
                    "Publishing {} (v{}) to: {}",
                    repo.display(),
                    version,
                    repo_targets.join(", ")
                );
                let steps = release::run_release_pipeline(
                    &repo,
                    "",
                    &version,
                    "patch",
                    &policy,
                    true,
                    false,
                    &repo_targets,
                    false,
                )
                .await;
                for step in &steps {
                    match step {
                        release::ReleaseStep::TagCreated(tag) => println!("  Tag: {tag}"),
                        release::ReleaseStep::GitHubReleaseCreated(tag) => {
                            println!("  Release: {tag}")
                        }
                        release::ReleaseStep::Published { registry, version } => {
                            println!("  Published: {registry} v{version}")
                        }
                        release::ReleaseStep::NixFlakePRCreated(url) => {
                            println!("  Nix flake PR: {url}")
                        }
                        release::ReleaseStep::Skipped(reason) => println!("  Skipped: {reason}"),
                        release::ReleaseStep::Failed { step: s, error } => {
                            eprintln!("  Failed: {s}{error}")
                        }
                    }
                }
            }
            PublishCommands::Status { repo, json } => {
                let policy = SyncPolicy::load(&policy_path)?;
                let version = release::detect_project_version(&repo)
                    .map(|(v, _)| v)
                    .unwrap_or_else(|| "unknown".to_string());
                let mut statuses = Vec::new();
                for target in &policy.publish_targets {
                    match release::extract_package_name(&repo, target.registry) {
                        Ok(pkg_name) => {
                            let exists = release::version_exists_on_registry(
                                target.registry,
                                &pkg_name,
                                &version,
                            )
                            .await;
                            statuses.push(serde_json::json!({
                                "target": target.name,
                                "registry": target.registry.as_str(),
                                "package": pkg_name,
                                "version": version,
                                "published": exists.unwrap_or(false),
                            }));
                        }
                        Err(e) => statuses.push(serde_json::json!({
                            "target": target.name,
                            "registry": target.registry.as_str(),
                            "version": version,
                            "error": e.to_string(),
                        })),
                    }
                }
                if json {
                    println!("{}", serde_json::to_string_pretty(&statuses)?);
                } else {
                    println!("Publish status for {} (v{}):", repo.display(), version);
                    for s in &statuses {
                        let target = s["target"].as_str().unwrap_or("?");
                        let published = s["published"].as_bool().unwrap_or(false);
                        let status_str = if published {
                            "published"
                        } else {
                            "not published"
                        };
                        println!("  {target}: {status_str}");
                    }
                }
            }
        },
        Command::Scaffold {
            repo,
            files,
            overwrite,
            dry_run,
        } => {
            cmd_scaffold(&policy_path, repo, files, overwrite, dry_run).await?;
        }
        Command::Ownership {
            repo,
            explain,
            json,
        } => {
            cmd_ownership(&policy_path, repo.as_deref(), explain, json)?;
        }
    }

    Ok(())
}

async fn cmd_scaffold(
    policy_path: &std::path::Path,
    repo: Option<PathBuf>,
    files: Vec<String>,
    overwrite: bool,
    dry_run: bool,
) -> Result<()> {
    use anyhow::Context;
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Cell, Color, ContentArrangement, Table};
    let policy = SyncPolicy::load(policy_path)?;

    if policy.standard_files.is_empty() {
        println!("No standard files configured in policy.");
        println!(
            "Add [[standard_files]] entries to {}",
            policy_path.display()
        );
        return Ok(());
    }

    let filtered_configs: Vec<_> = if files.is_empty() {
        policy.standard_files.clone()
    } else {
        policy
            .standard_files
            .iter()
            .filter(|c| files.contains(&c.target))
            .cloned()
            .collect()
    };

    if filtered_configs.is_empty() {
        println!("No matching standard files found.");
        return Ok(());
    }

    let repos = if let Some(repo_path) = repo {
        vec![repo_path]
    } else {
        let roots: Vec<PathBuf> = policy.watch_roots.iter().map(PathBuf::from).collect();
        let excluded: std::collections::BTreeSet<String> =
            policy.exclude_dir_names.iter().cloned().collect();
        git::discover_git_repos(&roots, &excluded, &policy.exclude_repos, None)
    };

    let policy_base = policy_path.parent().unwrap_or(policy_path);
    let mut results: Vec<(String, String, String)> = Vec::new();
    let mut total_copied = 0usize;

    for repo_path in &repos {
        let repo_override = policy::load_repo_override(repo_path);
        let repo_name = repo_path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| repo_path.display().to_string());

        for cfg in &filtered_configs {
            if repo_override.skip_standard_files.contains(&cfg.target) {
                continue;
            }

            let target_path = repo_path.join(&cfg.target);
            if target_path.exists() && !overwrite && !cfg.overwrite {
                continue;
            }

            let source_path = cfg.source_path(policy_base);
            if !source_path.exists() {
                results.push((
                    repo_name.clone(),
                    cfg.target.clone(),
                    "template missing".to_string(),
                ));
                continue;
            }

            if dry_run {
                results.push((
                    repo_name.clone(),
                    cfg.target.clone(),
                    "would copy".to_string(),
                ));
                total_copied += 1;
                continue;
            }

            if target_path.exists() && (overwrite || cfg.overwrite) {
                if target_path.is_dir() {
                    std::fs::remove_dir_all(&target_path)
                        .with_context(|| format!("failed to remove {}", cfg.target))?;
                } else {
                    std::fs::remove_file(&target_path)
                        .with_context(|| format!("failed to remove {}", cfg.target))?;
                }
            }

            if let Some(parent) = target_path.parent() {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("failed to create {}", parent.display()))?;
            }

            match std::fs::copy(&source_path, &target_path) {
                Ok(_) => {
                    results.push((repo_name.clone(), cfg.target.clone(), "copied".to_string()));
                    total_copied += 1;
                }
                Err(e) => {
                    results.push((repo_name.clone(), cfg.target.clone(), format!("error: {e}")));
                }
            }
        }
    }

    if results.is_empty() {
        println!("No standard files to scaffold (all repos already have them).");
        return Ok(());
    }

    let mut table = Table::new();
    table
        .load_preset(UTF8_FULL_CONDENSED)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_header(vec![
            Cell::new("REPO"),
            Cell::new("FILE"),
            Cell::new("STATUS"),
        ]);

    for (repo_name, file, status) in &results {
        let (status_str, color) = match status.as_str() {
            "copied" => ("\u{2705} copied", Color::Green),
            "would copy" => ("\u{1f4dd} would copy", Color::Yellow),
            "template missing" => ("\u{274c} template missing", Color::Red),
            s if s.starts_with("error:") => ("\u{274c} error", Color::Red),
            _ => (status.as_str(), Color::White),
        };
        table.add_row(vec![
            Cell::new(repo_name),
            Cell::new(file),
            Cell::new(status_str).fg(color),
        ]);
    }

    println!("{table}");
    let mode = if dry_run { "DRY-RUN" } else { "APPLIED" };
    println!(
        "{mode}: {total_copied} files scaffolded across {} repos",
        repos.len()
    );

    Ok(())
}

fn cmd_ownership(
    policy_path: &std::path::Path,
    repo: Option<&std::path::Path>,
    explain: bool,
    json: bool,
) -> Result<()> {
    use crate::ownership::{
        detect_ownership, read_signals, OwnershipInputs, OwnershipReport, TrustedSet,
    };
    use crate::policy::{load_repo_override, SyncPolicy};
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Cell, Color, ContentArrangement, Table};

    let policy = SyncPolicy::load(policy_path)?;
    let trusted = TrustedSet {
        emails: policy.trusted_emails.clone(),
        authors: policy.trusted_authors.clone(),
        remote_hosts: policy.trusted_remote_hosts.clone(),
    };
    let repos: Vec<PathBuf> = if let Some(p) = repo {
        vec![p.to_path_buf()]
    } else {
        let roots: Vec<PathBuf> = policy.watch_roots.iter().map(PathBuf::from).collect();
        let excluded: std::collections::BTreeSet<String> =
            policy.exclude_dir_names.iter().cloned().collect();
        git::discover_git_repos(&roots, &excluded, &policy.exclude_repos, None)
    };

    struct Row {
        repo: String,
        report: OwnershipReport,
        inputs: OwnershipInputs,
        override_owned: Option<bool>,
    }
    let mut rows: Vec<Row> = Vec::new();
    for repo_path in &repos {
        let inputs = read_signals(repo_path);
        let override_ = load_repo_override(repo_path);
        let override_owned = override_.owned;
        let report = detect_ownership(repo_path, &trusted, override_owned);
        rows.push(Row {
            repo: repo_path.display().to_string(),
            report,
            inputs,
            override_owned,
        });
    }

    if json {
        #[derive(serde::Serialize)]
        struct Out {
            policy: String,
            trusted_emails: Vec<String>,
            trusted_authors: Vec<String>,
            trusted_remote_hosts: Vec<String>,
            results: Vec<RepoJson>,
        }
        #[derive(serde::Serialize)]
        struct RepoJson {
            repo: String,
            report: OwnershipReport,
            user_email: Option<String>,
            head_author_email: Option<String>,
            head_author_name: Option<String>,
            origin_url: Option<String>,
            override_owned: Option<bool>,
        }
        let out = Out {
            policy: policy_path.display().to_string(),
            trusted_emails: policy.trusted_emails.clone(),
            trusted_authors: policy.trusted_authors.clone(),
            trusted_remote_hosts: policy.trusted_remote_hosts.clone(),
            results: rows
                .into_iter()
                .map(|r| RepoJson {
                    repo: r.repo,
                    report: r.report,
                    user_email: r.inputs.user_email,
                    head_author_email: r.inputs.head_author_email,
                    head_author_name: r.inputs.head_author_name,
                    origin_url: r.inputs.origin_url,
                    override_owned: r.override_owned,
                })
                .collect(),
        };
        println!("{}", serde_json::to_string_pretty(&out)?);
        return Ok(());
    }

    let mut table = Table::new();
    table.load_preset(UTF8_FULL_CONDENSED);
    table.set_content_arrangement(ContentArrangement::DynamicFullWidth);
    if explain {
        table.set_header(vec![
            Cell::new("📦 REPO"),
            Cell::new("🩺 OWNERSHIP"),
            Cell::new("📧 user.email"),
            Cell::new("👤 HEAD author"),
            Cell::new("🌐 origin"),
            Cell::new("🔧 override"),
        ]);
    } else {
        table.set_header(vec![Cell::new("📦 REPO"), Cell::new("🩺 OWNERSHIP")]);
    }
    for r in &rows {
        let (label, color) = match &r.report {
            OwnershipReport::Owned { reason } => (format!("✓ owned ({})", reason), Color::Green),
            OwnershipReport::Unowned { reason, .. } => {
                (format!("🚫 unowned: {}", reason), Color::Red)
            }
            OwnershipReport::Unknown { .. } => ("❓ unknown".to_string(), Color::Yellow),
        };
        let label_cell = Cell::new(label).fg(color);
        if explain {
            table.add_row(vec![
                Cell::new(&r.repo),
                label_cell,
                Cell::new(r.inputs.user_email.as_deref().unwrap_or("")),
                Cell::new(match (&r.inputs.head_author_name, &r.inputs.head_author_email) {
                    (Some(n), Some(e)) => format!("{} <{}>", n, e),
                    (Some(n), None) => n.clone(),
                    (None, Some(e)) => format!("<{}>", e),
                    (None, None) => "".to_string(),
                }),
                Cell::new(r.inputs.origin_url.as_deref().unwrap_or("")),
                Cell::new(
                    r.override_owned
                        .map(|b| if b { "owned=true" } else { "owned=false" })
                        .unwrap_or(""),
                ),
            ]);
        } else {
            table.add_row(vec![Cell::new(&r.repo), label_cell]);
        }
    }
    println!("{table}");
    Ok(())
}

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    fn temp_policy(repos: Vec<&str>) -> TempDir {
        let tmp = TempDir::new().unwrap();
        let content = format!(
            r#"
auto_github_private = false
auto_commit = true
auto_pull = true
auto_push = true
auto_bump_versions = false
watch_roots = {:?}
remotes = []
"#,
            repos
        );
        std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
        tmp
    }

    #[test]
    fn test_freeze_reason_none_when_no_marker() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".dracon")).unwrap();

        let policy_tmp = temp_policy(vec!["/dev/null"]);
        let policy_path = policy_tmp.path().join("policy.toml");

        let result = crate::policy::freeze_reason(&policy_path);
        assert!(result.is_none(), "no freeze marker should return None");
    }

    #[test]
    fn test_freeze_marker_paths() {
        let paths = crate::policy::freeze_marker_paths(std::path::Path::new("/fake.toml"));
        assert!(!paths.is_empty());
        assert!(paths
            .iter()
            .any(|p| p.to_string_lossy().contains(".dracon")));
        assert!(paths.iter().any(|p| p.to_string_lossy().contains("freeze")));
    }

    #[test]
    fn test_env_freeze_takes_precedence() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".dracon")).unwrap();

        let policy_tmp = temp_policy(vec!["/dev/null"]);
        let policy_path = policy_tmp.path().join("policy.toml");

        let _guard = crate::test_helpers::EnvRestorer::new("DRACON_SYNC_FREEZE", "1");
        let result = crate::policy::freeze_reason(&policy_path);

        assert!(
            result.is_some(),
            "env freeze should override missing marker"
        );
        assert!(result.unwrap().contains("env DRACON_SYNC_FREEZE"));
    }

    #[test]
    fn test_metrics_output_has_expected_format() {
        let lines = vec![
            "# HELP dracon_sync_info Dracon sync daemon info".to_string(),
            "# TYPE dracon_sync_info gauge".to_string(),
            format!(
                "dracon_sync_info{{version=\"{}\"}} 1",
                env!("CARGO_PKG_VERSION")
            ),
            "dracon_sync_repos_discovered_total 20".to_string(),
            "# HELP dracon_sync_freeze_state gauge".to_string(),
            "dracon_sync_freeze_state 0".to_string(),
        ];

        let mut found_version_line = false;
        for line in &lines {
            if line.starts_with('#') {
                assert!(
                    line.contains(" HELP ") || line.contains(" TYPE "),
                    "comment line should be HELP or TYPE: {}",
                    line
                );
            } else {
                assert!(
                    line.contains("dracon_sync"),
                    "metric line should contain metric name: {}",
                    line
                );
                if line.contains("version=") {
                    found_version_line = true;
                }
            }
        }
        assert!(found_version_line, "version metric line should be present");
    }

    #[test]
    fn test_metrics_contains_all_expected_metrics() {
        let expected_metrics = vec![
            "dracon_sync_info",
            "dracon_sync_repos_discovered_total",
            "dracon_sync_watch_roots_total",
            "dracon_sync_remotes_total",
            "dracon_sync_freeze_state",
            "dracon_sync_policy_auto_commit",
            "dracon_sync_policy_auto_push",
            "dracon_sync_policy_auto_pull",
            "dracon_sync_push_retries",
            "dracon_sync_pulse_interval_secs",
        ];

        for metric in &expected_metrics {
            assert!(
                metric.starts_with("dracon_sync_"),
                "metric name should start with dracon_sync_: {}",
                metric
            );
        }
    }
}

// daemon-push-test: 2026-06-21 12:18 — verify end-to-end propagation
// daemon-push-test-2: 2026-06-21 12:35 — verify daemon auto-push for nested repo