githubclaw 0.2.2

Near-autonomous AI agents that manage open-source projects end-to-end using GitHub as the single source of truth.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
//! GithubClaw CLI — init, start, stop, status, logs commands.
//!
//! Rust translation of the Python `cli.py`.

use clap::{Parser, Subcommand};
use std::collections::HashMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;

use crate::config::{find_repo_root, get_log_file, get_pid_file, global_config_dir, GlobalConfig};

// ---------------------------------------------------------------------------
// Embedded default templates (compile-time via include_str!)
// ---------------------------------------------------------------------------

const DEFAULT_ORCHESTRATOR_MD: &str = include_str!("../defaults/orchestrator.md");
const DEFAULT_GLOBAL_PROMPT_MD: &str = include_str!("../defaults/global_prompt.md");
const DEFAULT_VALUE_MD: &str = include_str!("../defaults/value.md");
const DEFAULT_MEMORY_MD: &str = include_str!("../defaults/memory.md");
const DEFAULT_SPAWN_CLAUDE_SH: &str = r#"#!/usr/bin/env bash
# GithubClaw spawn template for Claude Code.
set -euo pipefail
exec claude -p \
  --dangerously-skip-permissions \
  --allowedTools "${ALLOWED_TOOLS}" \
  --disallowedTools "${DISALLOWED_TOOLS}" \
  --max-turns "${MAX_TURNS:-200}" \
  --append-system-prompt-file "${PROMPT_FILE}" \
  "$TASK_PROMPT"
"#;
const DEFAULT_SPAWN_CODEX_SH: &str = r#"#!/usr/bin/env bash
# GithubClaw spawn template for Codex CLI.
set -euo pipefail
cat "${PROMPT_FILE}" | codex exec - \
  --dangerously-bypass-approvals-and-sandbox
"#;
const DEFAULT_GITIGNORE: &str = "secrets/\nqueue/\nlogs/\nmemory.md\n";
const DEFAULT_REPO_CONFIG_YAML: &str = "# GithubClaw per-repo configuration.\n# See https://github.com/GithubClaw/githubclaw for options.\n";

// Agent definitions embedded at compile time.
const DEFAULT_AGENT_ORCHESTRATOR: &str = include_str!("../defaults/agents/orchestrator.md");
const DEFAULT_AGENT_IMPLEMENTER: &str = include_str!("../defaults/agents/implementer.md");
const DEFAULT_AGENT_VERIFIER: &str = include_str!("../defaults/agents/verifier.md");
const DEFAULT_AGENT_REVIEWER: &str = include_str!("../defaults/agents/reviewer.md");
const DEFAULT_AGENT_VISION_GAP_ANALYST: &str =
    include_str!("../defaults/agents/vision_gap_analyst.md");
const DEFAULT_AGENT_BUG_REPRODUCER: &str = include_str!("../defaults/agents/bug_reproducer.md");

// ---------------------------------------------------------------------------
// Launchd / systemd constants
// ---------------------------------------------------------------------------

const LAUNCHD_LABEL: &str = "com.githubclaw.webhook-server";
const SYSTEMD_UNIT: &str = "githubclaw-webhook-server";

// ---------------------------------------------------------------------------
// CLI definition
// ---------------------------------------------------------------------------

#[derive(Parser)]
#[command(
    name = "githubclaw",
    version = env!("CARGO_PKG_VERSION"),
    about = "Near-autonomous AI agents for open-source project management."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Scaffold the .githubclaw/ directory in the current repository
    Init,
    /// Re-scan the current repository's open issues and PRs into the bootstrap queue
    Bootstrap,
    /// Start the webhook server as a background daemon
    Start,
    /// Stop the webhook server
    Stop {
        /// Immediate kill instead of graceful drain
        #[arg(long, short)]
        force: bool,
    },
    /// Show the status of the webhook server and registered repos
    Status,
    /// Show webhook server logs
    Logs {
        /// Follow log output (like tail -f)
        #[arg(long, short)]
        follow: bool,
    },
    /// Run the webhook server inline (used by launchd/systemd)
    Serve {
        /// Host to bind to
        #[arg(long, default_value = "0.0.0.0")]
        host: String,
        /// Port to bind to
        #[arg(long, default_value_t = 8000)]
        port: u16,
    },
    /// Dispatch a worker agent for a specific issue (called by Orchestrator)
    Dispatch {
        /// Agent type: implementer, verifier, reviewer, vision-gap-analyst, bug-reproducer
        agent_type: String,
        /// GitHub issue number
        #[arg(long)]
        issue: u64,
        /// Prompt/instructions for the agent
        #[arg(long)]
        prompt: String,
        /// Repository (owner/name). Defaults to current repo.
        #[arg(long)]
        repo: Option<String>,
        /// Logical event ID used for dispatch deduplication.
        #[arg(long)]
        event_id: Option<String>,
        /// Optional suffix to distinguish intentionally repeated identical dispatches.
        #[arg(long)]
        dedupe_key: Option<String>,
    },
    /// Start a release pipeline: dev -> release branch + PR
    Release {
        /// Repository (owner/name). Defaults to current repo.
        #[arg(long)]
        repo: Option<String>,
    },
    /// Launch the TUI dashboard
    Tui,
}

pub fn run() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Init => cmd_init(),
        Commands::Bootstrap => cmd_bootstrap(),
        Commands::Start => cmd_start(),
        Commands::Stop { force } => cmd_stop(force),
        Commands::Status => cmd_status(),
        Commands::Logs { follow } => cmd_logs(follow),
        Commands::Serve { host, port } => cmd_serve(&host, port),
        Commands::Dispatch {
            agent_type,
            issue,
            prompt,
            repo,
            event_id,
            dedupe_key,
        } => cmd_dispatch(
            &agent_type,
            issue,
            &prompt,
            repo.as_deref(),
            event_id.as_deref(),
            dedupe_key.as_deref(),
        ),
        Commands::Release { repo } => cmd_release(repo.as_deref()),
        Commands::Tui => cmd_tui(),
    }
}

// ===========================================================================
// cmd_init
// ===========================================================================

fn cmd_init() {
    let repo_root = match find_repo_root(None) {
        Some(r) => r,
        None => {
            eprintln!("Error: not inside a git repository.");
            std::process::exit(1);
        }
    };

    let claw_dir = repo_root.join(".githubclaw");

    if claw_dir.exists() {
        println!(
            "Directory {} already exists. Skipping existing files.",
            claw_dir.display()
        );
    }

    // Create directory structure
    let agents_dir = claw_dir.join("agents");
    let ai_dir = claw_dir.join("ai_instructions");
    let logs_dir = claw_dir.join("logs");
    let queue_dir = claw_dir.join("queue").join("dead");

    for d in [&agents_dir, &ai_dir, &logs_dir, &queue_dir] {
        fs::create_dir_all(d).unwrap_or_else(|e| {
            eprintln!("Error creating directory {}: {e}", d.display());
            std::process::exit(1);
        });
    }

    // Files to write (path -> content). Prompt/config files are user-owned and
    // are never overwritten. Runtime spawn scripts are refreshed so existing
    // repos pick up compatible launcher behavior after upgrades.
    let files: Vec<(PathBuf, &str)> = vec![
        (claw_dir.join("orchestrator.md"), DEFAULT_ORCHESTRATOR_MD),
        (claw_dir.join("global-prompt.md"), DEFAULT_GLOBAL_PROMPT_MD),
        (claw_dir.join("VALUE.md"), DEFAULT_VALUE_MD),
        (claw_dir.join("memory.md"), DEFAULT_MEMORY_MD),
        (claw_dir.join("spawn_claude.sh"), DEFAULT_SPAWN_CLAUDE_SH),
        (claw_dir.join("spawn_codex.sh"), DEFAULT_SPAWN_CODEX_SH),
        (claw_dir.join(".gitignore"), DEFAULT_GITIGNORE),
        (claw_dir.join("config.yaml"), DEFAULT_REPO_CONFIG_YAML),
        // Agent definition files (6 V2 agents)
        (
            agents_dir.join("orchestrator.md"),
            DEFAULT_AGENT_ORCHESTRATOR,
        ),
        (agents_dir.join("implementer.md"), DEFAULT_AGENT_IMPLEMENTER),
        (agents_dir.join("verifier.md"), DEFAULT_AGENT_VERIFIER),
        (agents_dir.join("reviewer.md"), DEFAULT_AGENT_REVIEWER),
        (
            agents_dir.join("vision_gap_analyst.md"),
            DEFAULT_AGENT_VISION_GAP_ANALYST,
        ),
        (
            agents_dir.join("bug_reproducer.md"),
            DEFAULT_AGENT_BUG_REPRODUCER,
        ),
    ];

    let mut created: usize = 0;
    let mut skipped: usize = 0;
    let mut refreshed: usize = 0;

    for (filepath, content) in &files {
        let existed = filepath.exists();
        let is_spawn_script = filepath
            .file_name()
            .and_then(|n| n.to_str())
            .map(|n| n == "spawn_claude.sh" || n == "spawn_codex.sh")
            .unwrap_or(false);

        if existed && !is_spawn_script {
            skipped += 1;
            continue;
        }
        if let Some(parent) = filepath.parent() {
            let _ = fs::create_dir_all(parent);
        }
        if let Err(e) = fs::write(filepath, content) {
            eprintln!("Error writing {}: {e}", filepath.display());
        } else {
            if existed && is_spawn_script {
                refreshed += 1;
            } else {
                created += 1;
            }
        }
    }

    // Make spawn scripts executable (chmod 755)
    for script_name in &["spawn_claude.sh", "spawn_codex.sh"] {
        let script = claw_dir.join(script_name);
        if script.exists() {
            let _ = fs::set_permissions(&script, fs::Permissions::from_mode(0o755));
        }
    }

    println!("Initialized .githubclaw/ in {}", repo_root.display());
    println!(
        "  Created {created} files, refreshed {refreshed} runtime scripts, skipped {skipped} existing files."
    );
    println!();

    // (a) Auto-register the repo
    register_repo(&repo_root);

    // (b) One-time webhook secret setup
    setup_webhook_secret();

    // (c) Backend detection
    detect_backends();

    // (d) Pre-flight check for gh CLI
    preflight_gh();

    // (e) Guidance on what to git add
    println!();
    println!("To track agent configs in git:");
    println!(
        "  git add .githubclaw/agents/ .githubclaw/VALUE.md \
         .githubclaw/global-prompt.md .githubclaw/orchestrator.md"
    );

    // (f) Next steps
    println!();
    println!("Next steps:");
    println!("  1. Edit .githubclaw/VALUE.md with your project mission");
    println!("  2. Create a GitHub App and set webhook URL + secret");
    println!("  3. Set up a tunnel (cloudflare tunnel, ngrok, etc.)");
    println!("  4. githubclaw start");
}

fn cmd_bootstrap() {
    use crate::process_manager::ProcessManager;
    use crate::scheduler::ScheduledEventManager;
    use crate::server::{bootstrap_repo, load_registry, ServerState};
    use std::collections::HashSet;
    use tokio::sync::{Mutex, RwLock};

    let repo_root = match find_repo_root(None) {
        Some(r) => r,
        None => {
            eprintln!("Error: not inside a git repository.");
            std::process::exit(1);
        }
    };

    let output = match Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(&repo_root)
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            eprintln!("Error running git remote get-url origin: {e}");
            std::process::exit(1);
        }
    };
    if !output.status.success() {
        eprintln!("Error: no 'origin' remote found.");
        std::process::exit(1);
    }

    let remote_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let owner_repo = match parse_github_remote(&remote_url) {
        Some(or) => or,
        None => {
            eprintln!("Error: could not parse GitHub owner/repo from: {remote_url}");
            std::process::exit(1);
        }
    };

    let global_dir = global_config_dir();
    let registry = load_registry(&global_dir.join("registry.json"));
    let entry = match registry.get(&owner_repo).cloned() {
        Some(entry) => entry,
        None => {
            eprintln!("Error: repo {owner_repo} is not registered. Run `githubclaw init` first.");
            std::process::exit(1);
        }
    };

    let rt = tokio::runtime::Runtime::new().unwrap_or_else(|e| {
        eprintln!("Failed to create tokio runtime: {e}");
        std::process::exit(1);
    });

    rt.block_on(async move {
        let scheduler_path = global_dir.join("scheduled_events.json");
        let state = Arc::new(ServerState {
            webhook_secret: String::new(),
            registry: RwLock::new(registry),
            started_repos: RwLock::new(HashSet::new()),
            queues: Mutex::new(HashMap::new()),
            githubclaw_home: global_dir.clone(),
            process_manager: Arc::new(ProcessManager::new(1)),
            scheduler: Mutex::new(ScheduledEventManager::new(&scheduler_path)),
            rate_limiter: Arc::new(crate::rate_limiter::RateLimiter::default()),
            shutdown: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            issue_router: crate::issue_router::IssueRouter::new(global_dir.join("sessions")),
            session_store: crate::session_store::SessionStore::new(),
        });

        match bootstrap_repo(&state, &owner_repo, &entry, true).await {
            Ok(()) => println!("Bootstrapped open issues/PRs for {owner_repo}."),
            Err(e) => {
                eprintln!("Bootstrap failed for {owner_repo}: {e}");
                std::process::exit(1);
            }
        }
    });
}

// ===========================================================================
// cmd_start
// ===========================================================================

fn cmd_start() {
    if let Some(pid) = read_pid() {
        eprintln!("Webhook server already running (PID {pid}).");
        std::process::exit(1);
    }

    // Ensure global directories exist
    let global_dir = global_config_dir();
    let _ = fs::create_dir_all(global_dir.join("logs"));
    let _ = fs::create_dir_all(global_dir.join("secrets"));

    let config = GlobalConfig::load(None).unwrap_or_else(|e| {
        eprintln!("Error loading config: {e}");
        std::process::exit(1);
    });

    // Save default global config if it doesn't exist
    if !global_dir.join("config.yaml").exists() {
        let _ = config.save(None);
    }

    let log_path = get_log_file();
    if let Some(parent) = log_path.parent() {
        let _ = fs::create_dir_all(parent);
    }

    let system = std::env::consts::OS;

    match system {
        "macos" => {
            let plist_path = write_launchd_plist(LAUNCHD_LABEL, config.port, &log_path);
            let uid = unsafe { libc::getuid() };

            // Unload stale definition first
            let _ = Command::new("launchctl")
                .args([
                    "bootout",
                    &format!("gui/{uid}"),
                    &plist_path.to_string_lossy(),
                ])
                .output();

            let result = Command::new("launchctl")
                .args([
                    "bootstrap",
                    &format!("gui/{uid}"),
                    &plist_path.to_string_lossy(),
                ])
                .output();

            match result {
                Ok(output) if !output.status.success() => {
                    eprintln!(
                        "Failed to start via launchd: {}",
                        String::from_utf8_lossy(&output.stderr).trim()
                    );
                    std::process::exit(1);
                }
                Err(e) => {
                    eprintln!("Failed to run launchctl: {e}");
                    std::process::exit(1);
                }
                _ => {}
            }

            // Find PID from launchctl print
            if let Ok(info) = Command::new("launchctl")
                .args(["print", &format!("gui/{uid}/{LAUNCHD_LABEL}")])
                .output()
            {
                let stdout = String::from_utf8_lossy(&info.stdout);
                for line in stdout.lines() {
                    let trimmed = line.trim();
                    if trimmed.starts_with("pid =") {
                        if let Some(val) = trimmed.split('=').nth(1) {
                            if let Ok(pid) = val.trim().parse::<u32>() {
                                let _ = fs::write(get_pid_file(), pid.to_string());
                            }
                        }
                    }
                }
            }

            println!(
                "Webhook server started via launchd on port {}.",
                config.port
            );
            println!("  Logs: {}", log_path.display());
            println!("  Plist: {}", plist_path.display());
        }
        "linux" => {
            let unit_path = write_systemd_unit(SYSTEMD_UNIT, config.port, &log_path);

            let _ = Command::new("systemctl")
                .args(["--user", "daemon-reload"])
                .output();

            let result = Command::new("systemctl")
                .args(["--user", "start", SYSTEMD_UNIT])
                .output();

            match result {
                Ok(output) if !output.status.success() => {
                    eprintln!(
                        "Failed to start via systemd: {}",
                        String::from_utf8_lossy(&output.stderr).trim()
                    );
                    std::process::exit(1);
                }
                Err(e) => {
                    eprintln!("Failed to run systemctl: {e}");
                    std::process::exit(1);
                }
                _ => {}
            }

            // Get PID from systemd
            if let Ok(pid_output) = Command::new("systemctl")
                .args([
                    "--user",
                    "show",
                    SYSTEMD_UNIT,
                    "--property=MainPID",
                    "--value",
                ])
                .output()
            {
                let s = String::from_utf8_lossy(&pid_output.stdout);
                if let Ok(pid) = s.trim().parse::<u32>() {
                    if pid > 0 {
                        let _ = fs::write(get_pid_file(), pid.to_string());
                    }
                }
            }

            println!(
                "Webhook server started via systemd on port {}.",
                config.port
            );
            println!("  Logs: {}", log_path.display());
            println!("  Unit: {}", unit_path.display());
        }
        _ => {
            eprintln!("Unsupported platform: {system}. Only macOS and Linux are supported.");
            std::process::exit(1);
        }
    }

    // Health check
    health_check(config.port, &log_path);
}

// ===========================================================================
// cmd_stop
// ===========================================================================

fn cmd_stop(force: bool) {
    let system = std::env::consts::OS;

    if force {
        stop_force(system);
    } else {
        stop_graceful(system);
    }
}

fn stop_graceful(system: &str) {
    let pid = read_pid();

    match system {
        "macos" => {
            let plist_path = home_dir()
                .join("Library")
                .join("LaunchAgents")
                .join(format!("{LAUNCHD_LABEL}.plist"));
            if plist_path.exists() {
                // Send SIGTERM for graceful drain
                if let Some(pid) = pid {
                    unsafe {
                        libc::kill(pid as i32, libc::SIGTERM);
                    }
                }
                let uid = unsafe { libc::getuid() };
                let result = Command::new("launchctl")
                    .args([
                        "bootout",
                        &format!("gui/{uid}"),
                        &plist_path.to_string_lossy(),
                    ])
                    .output();

                let _ = fs::remove_file(get_pid_file());

                match result {
                    Ok(output)
                        if output.status.success()
                            || String::from_utf8_lossy(&output.stderr)
                                .contains("No such process") =>
                    {
                        println!("Webhook server stopped (graceful drain).");
                    }
                    Ok(output) => {
                        println!(
                            "launchctl bootout warning: {}",
                            String::from_utf8_lossy(&output.stderr).trim()
                        );
                    }
                    Err(e) => {
                        eprintln!("Failed to run launchctl: {e}");
                    }
                }
                return;
            }
        }
        "linux" => {
            let result = Command::new("systemctl")
                .args(["--user", "stop", SYSTEMD_UNIT])
                .output();

            let _ = fs::remove_file(get_pid_file());

            match result {
                Ok(output) if output.status.success() => {
                    println!("Webhook server stopped (graceful drain).");
                }
                Ok(output) => {
                    println!(
                        "systemctl stop warning: {}",
                        String::from_utf8_lossy(&output.stderr).trim()
                    );
                }
                Err(e) => {
                    eprintln!("Failed to run systemctl: {e}");
                }
            }
            return;
        }
        _ => {}
    }

    // Fallback: direct PID-based stop
    match pid {
        Some(pid) => {
            unsafe {
                libc::kill(pid as i32, libc::SIGTERM);
            }
            let _ = fs::remove_file(get_pid_file());
            println!("Webhook server stopped (graceful drain).");
        }
        None => {
            eprintln!("Webhook server is not running.");
            std::process::exit(1);
        }
    }
}

fn stop_force(system: &str) {
    let pid = read_pid();

    match system {
        "macos" => {
            if let Some(pid) = pid {
                unsafe {
                    libc::kill(pid as i32, libc::SIGKILL);
                }
            }
            let plist_path = home_dir()
                .join("Library")
                .join("LaunchAgents")
                .join(format!("{LAUNCHD_LABEL}.plist"));
            if plist_path.exists() {
                let uid = unsafe { libc::getuid() };
                let _ = Command::new("launchctl")
                    .args([
                        "bootout",
                        &format!("gui/{uid}"),
                        &plist_path.to_string_lossy(),
                    ])
                    .output();
            }
            let _ = fs::remove_file(get_pid_file());
            println!("Webhook server killed (force).");
        }
        "linux" => {
            let result = Command::new("systemctl")
                .args(["--user", "kill", "--signal=KILL", SYSTEMD_UNIT])
                .output();

            let _ = Command::new("systemctl")
                .args(["--user", "stop", SYSTEMD_UNIT])
                .output();

            let _ = fs::remove_file(get_pid_file());

            match result {
                Ok(output) if output.status.success() => {
                    println!("Webhook server killed (force).");
                }
                Ok(output) => {
                    println!(
                        "systemctl kill warning: {}",
                        String::from_utf8_lossy(&output.stderr).trim()
                    );
                }
                Err(e) => {
                    eprintln!("Failed to run systemctl: {e}");
                }
            }
        }
        _ => {
            // Fallback: direct PID-based kill
            match pid {
                Some(pid) => {
                    unsafe {
                        libc::kill(pid as i32, libc::SIGKILL);
                    }
                    let _ = fs::remove_file(get_pid_file());
                    println!("Webhook server killed (force).");
                }
                None => {
                    eprintln!("Webhook server is not running.");
                    std::process::exit(1);
                }
            }
        }
    }
}

// ===========================================================================
// cmd_status
// ===========================================================================

fn cmd_status() {
    // Check if server is running
    match read_pid() {
        Some(pid) => {
            println!("Webhook server is running (PID {pid}).");
            if let Ok(config) = GlobalConfig::load(None) {
                println!("  Port: {}", config.port);
            }
        }
        None => {
            println!("Webhook server is not running.");
        }
    }

    // Show registered repos
    let registry_path = global_config_dir().join("registry.json");
    if !registry_path.exists() {
        println!();
        println!("No repos registered (registry.json not found).");
        return;
    }

    let registry_contents = match fs::read_to_string(&registry_path) {
        Ok(c) => c,
        Err(_) => {
            println!();
            println!("Registry file is corrupted.");
            return;
        }
    };

    let registry: serde_json::Value = match serde_json::from_str(&registry_contents) {
        Ok(v) => v,
        Err(_) => {
            println!();
            println!("Registry file is corrupted.");
            return;
        }
    };

    let repos = match registry.get("repos").and_then(|r| r.as_object()) {
        Some(r) if !r.is_empty() => r,
        _ => {
            println!();
            println!("No repos registered.");
            return;
        }
    };

    println!();
    println!("Registered repos ({}):", repos.len());
    for (repo_name, info) in repos {
        let local_path = info
            .get("local_path")
            .and_then(|v| v.as_str())
            .unwrap_or("unknown");
        println!("  {repo_name}");
        println!("    Path: {local_path}");

        // Show queue size if queue dir exists
        let queue_dir = Path::new(local_path).join(".githubclaw").join("queue");
        if queue_dir.exists() {
            let queue_count = fs::read_dir(&queue_dir)
                .map(|entries| {
                    entries
                        .filter_map(|e| e.ok())
                        .filter(|e| {
                            e.path().is_file()
                                && e.path().extension().is_some_and(|ext| ext == "json")
                        })
                        .count()
                })
                .unwrap_or(0);
            println!("    Queue: {queue_count} item(s)");
        }
    }
}

// ===========================================================================
// cmd_logs
// ===========================================================================

fn cmd_logs(follow: bool) {
    let log_path = get_log_file();
    if !log_path.exists() {
        println!("No logs found.");
        return;
    }

    if follow {
        // Replace process with tail -f
        use std::os::unix::process::CommandExt;
        let err = Command::new("tail")
            .args(["-f", &log_path.to_string_lossy()])
            .exec();
        eprintln!("Failed to exec tail: {err}");
        std::process::exit(1);
    } else {
        // Print last 50 lines
        match fs::read_to_string(&log_path) {
            Ok(contents) => {
                let lines: Vec<&str> = contents.lines().collect();
                let start = if lines.len() > 50 {
                    lines.len() - 50
                } else {
                    0
                };
                for line in &lines[start..] {
                    println!("{line}");
                }
            }
            Err(e) => {
                eprintln!("Error reading log file: {e}");
                std::process::exit(1);
            }
        }
    }
}

// ===========================================================================
// cmd_serve — runs the axum server inline (called by launchd/systemd)
// ===========================================================================

fn cmd_serve(host: &str, port: u16) {
    use crate::process_manager::ProcessManager;
    use crate::scheduler::ScheduledEventManager;
    use crate::server::{
        bootstrap_repo, create_router, load_registry, load_webhook_secret, ServerState,
    };
    use std::collections::HashSet;
    use tokio::sync::{Mutex, RwLock};

    // Build the tokio runtime for the async server
    let rt = tokio::runtime::Runtime::new().unwrap_or_else(|e| {
        eprintln!("Failed to create tokio runtime: {e}");
        std::process::exit(1);
    });

    rt.block_on(async {
        // Initialize tracing
        tracing_subscriber::fmt()
            .with_env_filter(
                tracing_subscriber::EnvFilter::try_from_default_env()
                    .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
            )
            .init();

        let global_dir = global_config_dir();

        // Load config
        let config = GlobalConfig::load(None).unwrap_or_else(|e| {
            eprintln!("Error loading config: {e}");
            std::process::exit(1);
        });

        // Load webhook secret
        let secret_path = global_dir.join("secrets").join("webhook_secret");
        let webhook_secret = load_webhook_secret(&secret_path).unwrap_or_else(|e| {
            eprintln!("Error loading webhook secret: {e}");
            std::process::exit(1);
        });

        // Load registry
        let registry_path = global_dir.join("registry.json");
        let registry = load_registry(&registry_path);

        if registry.is_empty() {
            tracing::warn!("No repos registered. Run `githubclaw init` in a repo first.");
        }

        // Load scheduler
        let scheduler_path = global_dir.join("scheduled_events.json");
        let mut scheduler = ScheduledEventManager::new(&scheduler_path);
        if let Err(e) = scheduler.load() {
            tracing::warn!("Failed to load scheduled events: {}", e);
        }

        // Create server state
        let state = Arc::new(ServerState {
            webhook_secret: webhook_secret.clone(),
            registry: RwLock::new(registry.clone()),
            started_repos: RwLock::new(HashSet::new()),
            queues: Mutex::new(HashMap::new()),
            githubclaw_home: global_dir.clone(),
            process_manager: Arc::new(ProcessManager::with_limits(
                config.max_concurrent_orchestrators,
                config.max_concurrent_workers,
            )),
            scheduler: Mutex::new(scheduler),
            rate_limiter: Arc::new(crate::rate_limiter::RateLimiter::default()),
            shutdown: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            issue_router: crate::issue_router::IssueRouter::new(global_dir.join("sessions")),
            session_store: crate::session_store::SessionStore::new(),
        });

        // Bootstrap repos: scan existing open issues/PRs for each repo
        for (repo_name, entry) in &registry {
            if let Err(e) = bootstrap_repo(&state, repo_name, entry, false).await {
                tracing::warn!("Bootstrap failed for {}: {}", repo_name, e);
            }
        }

        // Start the process monitor in background
        let _monitor_handle = state.process_manager.start_monitor();

        // Start the scheduler firing loop in background
        {
            let sched_state = Arc::clone(&state);
            tokio::spawn(async move {
                let mut interval = tokio::time::interval(std::time::Duration::from_secs(
                    crate::constants::SCHEDULER_CHECK_INTERVAL_SECONDS,
                ));
                loop {
                    interval.tick().await;
                    if sched_state
                        .shutdown
                        .load(std::sync::atomic::Ordering::Relaxed)
                    {
                        break;
                    }
                    let mut scheduler = sched_state.scheduler.lock().await;
                    let sched_state_inner = Arc::clone(&sched_state);
                    scheduler
                        .fire_due_events_with_callback(|repo, payload| {
                            let st = Arc::clone(&sched_state_inner);
                            async move {
                                let mut queues = st.queues.lock().await;
                                let registry = st.registry.read().await;
                                let queue = crate::server::get_or_create_queue(
                                    &mut queues,
                                    &registry,
                                    &st.githubclaw_home,
                                    &repo,
                                )
                                .map_err(|e| e.to_string())?;
                                queue
                                    .enqueue(
                                        serde_json::json!({
                                            "type": "scheduled_fired",
                                            "scheduled_payload": payload,
                                        }),
                                        "scheduled_fired",
                                    )
                                    .map_err(|e| e.to_string())?;
                                Ok(())
                            }
                        })
                        .await;
                }
            });
        }

        // Set up shutdown flag handler
        {
            let shutdown_flag = state.shutdown.clone();
            tokio::spawn(async move {
                tokio::signal::ctrl_c().await.ok();
                shutdown_flag.store(true, std::sync::atomic::Ordering::Relaxed);
            });
        }

        // Start per-repo event drain loops + rate limiter recovery probe
        crate::server::start_event_processing(Arc::clone(&state)).await;

        // Build router
        let app = create_router(Arc::clone(&state));

        // Bind and serve
        let bind_addr = format!("{host}:{port}");
        tracing::info!("GithubClaw webhook server listening on {}", bind_addr);

        let listener = tokio::net::TcpListener::bind(&bind_addr)
            .await
            .unwrap_or_else(|e| {
                eprintln!("Failed to bind to {}: {}", bind_addr, e);
                std::process::exit(1);
            });

        // Graceful shutdown on SIGTERM/SIGINT
        let shutdown_signal = async {
            let mut sigterm =
                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                    .expect("failed to install SIGTERM handler");
            let sigint = tokio::signal::ctrl_c();
            tokio::select! {
                _ = sigterm.recv() => {
                    tracing::info!("Received SIGTERM, shutting down...");
                }
                _ = sigint => {
                    tracing::info!("Received SIGINT, shutting down...");
                }
            }
        };

        axum::serve(listener, app)
            .with_graceful_shutdown(shutdown_signal)
            .await
            .unwrap_or_else(|e| {
                eprintln!("Server error: {e}");
                std::process::exit(1);
            });

        tracing::info!("Server shut down.");
    });
}

// ===========================================================================
// Helper functions
// ===========================================================================

fn home_dir() -> PathBuf {
    std::env::var("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("/tmp"))
}

/// Parse `owner/repo` from a GitHub remote URL.
///
/// Supports:
///   - `git@github.com:owner/repo.git`
///   - `https://github.com/owner/repo.git`
///   - `https://github.com/owner/repo`
fn parse_github_remote(url: &str) -> Option<String> {
    let re_ssh = regex::Regex::new(r"^git@github\.com:([^/]+)/([^/]+?)(?:\.git)?$").ok()?;
    if let Some(caps) = re_ssh.captures(url) {
        return Some(format!("{}/{}", &caps[1], &caps[2]));
    }

    let re_https = regex::Regex::new(r"^https://github\.com/([^/]+)/([^/]+?)(?:\.git)?$").ok()?;
    if let Some(caps) = re_https.captures(url) {
        return Some(format!("{}/{}", &caps[1], &caps[2]));
    }

    None
}

/// Auto-register the repo in `~/.githubclaw/registry.json`.
fn register_repo(repo_root: &Path) {
    let output = match Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(repo_root)
        .output()
    {
        Ok(o) => o,
        Err(_) => {
            println!("  Warning: could not run git; skipping registry.");
            return;
        }
    };

    if !output.status.success() {
        println!("  Warning: no 'origin' remote found; skipping registry.");
        return;
    }

    let remote_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let owner_repo = match parse_github_remote(&remote_url) {
        Some(or) => or,
        None => {
            println!("  Warning: could not parse GitHub owner/repo from: {remote_url}");
            return;
        }
    };

    let repo_name = owner_repo.split('/').next_back().unwrap_or(&owner_repo);
    let global_dir = global_config_dir();
    let _ = fs::create_dir_all(&global_dir);
    let registry_path = global_dir.join("registry.json");

    let mut registry: serde_json::Value = if registry_path.exists() {
        fs::read_to_string(&registry_path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_else(|| serde_json::json!({"repos": {}}))
    } else {
        serde_json::json!({"repos": {}})
    };

    if registry.get("repos").is_none() {
        registry["repos"] = serde_json::json!({});
    }

    let resolved = fs::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf());

    registry["repos"][&owner_repo] = serde_json::json!({
        "local_path": resolved.to_string_lossy(),
        "socket_path": format!("/tmp/githubclaw-{repo_name}.sock"),
    });

    let json_str = serde_json::to_string_pretty(&registry).unwrap_or_default();
    let _ = fs::write(&registry_path, format!("{json_str}\n"));

    println!("  Registered {owner_repo} in ~/.githubclaw/registry.json");
}

/// One-time webhook secret setup.
fn setup_webhook_secret() {
    let secrets_dir = global_config_dir().join("secrets");
    let _ = fs::create_dir_all(&secrets_dir);
    let secret_path = secrets_dir.join("webhook_secret");

    if secret_path.exists() {
        println!("  Webhook secret already configured.");
        return;
    }

    // Generate 32 random bytes as hex (64 hex chars)
    use std::io::Read;
    let mut buf = [0u8; 32];
    if let Ok(mut f) = fs::File::open("/dev/urandom") {
        if f.read_exact(&mut buf).is_ok() {
            let secret = hex::encode(buf);
            if fs::write(&secret_path, &secret).is_ok() {
                let _ = fs::set_permissions(&secret_path, fs::Permissions::from_mode(0o600));
                println!("  Generated webhook secret at ~/.githubclaw/secrets/webhook_secret");
                println!("  Use this secret when creating your GitHub App webhook.");
                return;
            }
        }
    }
    eprintln!("  Warning: could not generate webhook secret.");
}

/// Check which agent backends are available.
fn detect_backends() {
    let claude_found = which("claude");
    let codex_found = which("codex");

    let mut available = Vec::new();
    if claude_found {
        available.push("claude");
    }
    if codex_found {
        available.push("codex");
    }

    if available.is_empty() {
        println!(
            "  Warning: Neither claude nor codex CLI found. \
             Install one before running agents."
        );
    } else {
        println!("  Available backends: {}", available.join(", "));
    }
}

/// Pre-flight check for gh CLI.
fn preflight_gh() {
    if !which("gh") {
        println!("  Warning: gh CLI not found. Install it: https://cli.github.com");
        return;
    }

    let result = Command::new("gh").args(["auth", "status"]).output();
    match result {
        Ok(output) if output.status.success() => {
            println!("  gh CLI authenticated.");
        }
        _ => {
            println!("  Warning: gh CLI not authenticated. Run: gh auth login");
        }
    }
}

/// Check if a binary is on PATH.
fn which(binary: &str) -> bool {
    Command::new("which")
        .arg(binary)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Read PID from the PID file, returning None if not present or if the process
/// is not alive.
fn read_pid() -> Option<u32> {
    let pid_file = get_pid_file();
    if !pid_file.exists() {
        return None;
    }

    let contents = fs::read_to_string(&pid_file).ok()?;
    let pid: u32 = contents.trim().parse().ok()?;

    // Check if process is alive (signal 0)
    let alive = unsafe { libc::kill(pid as i32, 0) == 0 };
    if alive {
        Some(pid)
    } else {
        let _ = fs::remove_file(&pid_file);
        None
    }
}

/// Write a macOS launchd plist and return its path.
fn write_launchd_plist(label: &str, port: u16, log_path: &Path) -> PathBuf {
    let plist_dir = home_dir().join("Library").join("LaunchAgents");
    let _ = fs::create_dir_all(&plist_dir);
    let plist_path = plist_dir.join(format!("{label}.plist"));

    let exe_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("githubclaw"));
    let path_env = std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into());

    let plist_content = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{label}</string>
    <key>ProgramArguments</key>
    <array>
        <string>{exe}</string>
        <string>serve</string>
        <string>--host</string>
        <string>0.0.0.0</string>
        <string>--port</string>
        <string>{port}</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>{log}</string>
    <key>StandardErrorPath</key>
    <string>{log}</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>{path}</string>
    </dict>
</dict>
</plist>
"#,
        exe = exe_path.display(),
        log = log_path.display(),
        path = path_env,
    );

    let _ = fs::write(&plist_path, plist_content);
    plist_path
}

/// Write a Linux systemd user unit file and return its path.
fn write_systemd_unit(unit_name: &str, port: u16, log_path: &Path) -> PathBuf {
    let unit_dir = home_dir().join(".config").join("systemd").join("user");
    let _ = fs::create_dir_all(&unit_dir);
    let unit_path = unit_dir.join(format!("{unit_name}.service"));

    let exe_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("githubclaw"));
    let path_env = std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into());

    let unit_content = format!(
        r#"[Unit]
Description=GithubClaw Webhook Server
After=network.target

[Service]
Type=simple
ExecStart={exe} serve --host 0.0.0.0 --port {port}
Restart=on-failure
RestartSec=5
StandardOutput=append:{log}
StandardError=append:{log}
Environment=PATH={path}

[Install]
WantedBy=default.target
"#,
        exe = exe_path.display(),
        log = log_path.display(),
        path = path_env,
    );

    let _ = fs::write(&unit_path, unit_content);
    unit_path
}

/// Simple health check after startup — retry up to 3 times.
fn health_check(port: u16, log_path: &Path) {
    std::thread::sleep(std::time::Duration::from_secs(2));

    for attempt in 0..3 {
        let result = Command::new("curl")
            .args([
                "-sf",
                "--max-time",
                "5",
                &format!("http://127.0.0.1:{port}/health"),
            ])
            .output();

        if let Ok(output) = result {
            if output.status.success() {
                println!("  Server is healthy.");
                return;
            }
        }

        if attempt < 2 {
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    println!(
        "  Warning: Server may not have started correctly. Check logs: {}",
        log_path.display()
    );
}

// ===========================================================================
// Helpers
// ===========================================================================

/// Detect the GitHub owner/repo from the current git remote.
fn detect_github_remote(repo_root: &Path) -> Option<String> {
    let output = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(repo_root)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    parse_github_remote(&url)
}

fn runtime_timestamp() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs().to_string())
        .unwrap_or_else(|_| "0".to_string())
}

// ===========================================================================
// cmd_dispatch — Dispatch a worker agent for a specific issue
// ===========================================================================

fn cmd_dispatch(
    agent_type: &str,
    issue: u64,
    prompt: &str,
    repo: Option<&str>,
    event_id_arg: Option<&str>,
    dedupe_key_arg: Option<&str>,
) {
    use crate::constants::AGENT_TYPES;
    use crate::dispatch_receipts::DispatchReceiptStore;

    // Validate agent type
    if !AGENT_TYPES.contains(&agent_type) {
        eprintln!(
            "Error: unknown agent type '{}'. Valid types: {}",
            agent_type,
            AGENT_TYPES.join(", ")
        );
        std::process::exit(1);
    }

    // Resolve repo
    let repo_name = match repo {
        Some(r) => r.to_string(),
        None => {
            let repo_root = find_repo_root(None).unwrap_or_else(|| {
                eprintln!("Error: not inside a git repository. Use --repo flag.");
                std::process::exit(1);
            });
            detect_github_remote(&repo_root).unwrap_or_else(|| {
                eprintln!("Error: cannot detect GitHub remote. Use --repo flag.");
                std::process::exit(1);
            })
        }
    };

    let repo_root = find_repo_root(None).unwrap_or_else(|| {
        eprintln!("Error: not inside a git repository.");
        std::process::exit(1);
    });

    let receipt_store = DispatchReceiptStore::new(&repo_root);
    let dispatch_event_id = event_id_arg.map(ToString::to_string).or_else(|| {
        std::env::var("GITHUBCLAW_EVENT_ID")
            .ok()
            .filter(|value| !value.trim().is_empty())
    });
    let dispatch_dedupe_suffix = dedupe_key_arg.map(ToString::to_string).or_else(|| {
        std::env::var("GITHUBCLAW_DISPATCH_DEDUPE_KEY")
            .ok()
            .filter(|value| !value.trim().is_empty())
    });
    let dispatch_receipt_key = dispatch_event_id.as_ref().map(|event_id| {
        DispatchReceiptStore::key_for(
            event_id,
            agent_type,
            issue,
            prompt,
            dispatch_dedupe_suffix.as_deref(),
        )
    });

    if let Some(ref receipt_key) = dispatch_receipt_key {
        if receipt_store.has_receipt(receipt_key) {
            println!(
                "Skipping duplicate {} dispatch for {}#{} (receipt {}).",
                agent_type, repo_name, issue, receipt_key
            );
            let started_at = runtime_timestamp();
            let session_store = crate::session_store::SessionStore::new();
            let mut runtime_snapshot = session_store
                .load_runtime_snapshot(&repo_name, issue)
                .unwrap_or(None)
                .unwrap_or_else(|| {
                    crate::runtime_state::IssueRuntimeSnapshot::new(&repo_name, issue)
                });
            runtime_snapshot.note_agent_finished(
                agent_type,
                &started_at,
                true,
                format!(
                    "Skipped duplicate dispatch for {}#{} (event {})",
                    repo_name,
                    issue,
                    dispatch_event_id.as_deref().unwrap_or_default()
                ),
            );
            let _ = session_store.save_runtime_snapshot(&repo_name, &runtime_snapshot);
            return;
        }
    }

    println!(
        "Dispatching {} agent for {}#{} ...",
        agent_type, repo_name, issue
    );

    let started_at = runtime_timestamp();
    let session_store = crate::session_store::SessionStore::new();
    let mut runtime_snapshot = session_store
        .load_runtime_snapshot(&repo_name, issue)
        .unwrap_or(None)
        .unwrap_or_else(|| crate::runtime_state::IssueRuntimeSnapshot::new(&repo_name, issue));
    runtime_snapshot.note_agent_started(
        agent_type,
        &started_at,
        format!("Dispatch started for {}#{}", repo_name, issue),
    );
    let _ = session_store.save_runtime_snapshot(&repo_name, &runtime_snapshot);

    // Build environment with root issue tracking
    let mut extra_env = HashMap::new();
    if issue > 0 {
        extra_env.insert("GITHUBCLAW_ROOT_ISSUE".into(), issue.to_string());
    }
    extra_env.insert("GITHUBCLAW_REPO".into(), repo_name.clone());

    // Load agent definition: write to temp file, then parse
    let agent_def_content = load_agent_definition(agent_type, &repo_root);
    let tmp_dir = std::env::temp_dir().join("githubclaw-dispatch");
    fs::create_dir_all(&tmp_dir).unwrap_or_default();
    let agent_file = tmp_dir.join(format!("{}.md", agent_type));
    fs::write(&agent_file, &agent_def_content).unwrap_or_else(|e| {
        eprintln!("Error writing temp agent file: {}", e);
        std::process::exit(1);
    });
    let agent_def = match crate::agents::parser::parse_agent_file(&agent_file) {
        Ok(def) => def,
        Err(e) => {
            eprintln!("Error parsing agent definition for '{}': {}", agent_type, e);
            std::process::exit(1);
        }
    };

    // Assemble prompt
    let mut prompt_assembler = crate::agents::prompt_assembler::PromptAssembler::new(&repo_root);
    let prompt_file = match prompt_assembler.assemble(&agent_def, prompt) {
        Ok(path) => path,
        Err(e) => {
            eprintln!("Error assembling prompt: {}", e);
            std::process::exit(1);
        }
    };

    // Build and display the command (actual spawn is handled by the webhook server)
    let spawner = crate::agents::spawner::AgentSpawner::new(
        &repo_root,
        crate::constants::DEFAULT_AGENT_MAX_TURNS,
    );
    let env = spawner.build_env(&agent_def, &prompt_file, prompt, Some(&extra_env));
    let cmd = match spawner.build_command(&agent_def, &prompt_file, prompt) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Error building command: {}", e);
            std::process::exit(1);
        }
    };

    // Execute the agent subprocess
    let program = &cmd[0];
    let args = &cmd[1..];
    let status = Command::new(program)
        .args(args)
        .envs(&env)
        .current_dir(&repo_root)
        .status();

    match status {
        Ok(s) => {
            let code = s.code().unwrap_or(-1);
            let mut runtime_snapshot = session_store
                .load_runtime_snapshot(&repo_name, issue)
                .unwrap_or(None)
                .unwrap_or_else(|| {
                    crate::runtime_state::IssueRuntimeSnapshot::new(&repo_name, issue)
                });
            let detail = if code == 0 {
                format!("Dispatch completed for {}#{}", repo_name, issue)
            } else {
                format!(
                    "Dispatch exited with code {} for {}#{}",
                    code, repo_name, issue
                )
            };
            runtime_snapshot.note_agent_finished(agent_type, &started_at, code == 0, detail);
            let _ = session_store.save_runtime_snapshot(&repo_name, &runtime_snapshot);
            if code == 0 {
                if let Some(event_id) = dispatch_event_id.as_deref() {
                    if let Err(err) = receipt_store.record_success(
                        event_id,
                        agent_type,
                        issue,
                        prompt,
                        dispatch_dedupe_suffix.as_deref(),
                    ) {
                        eprintln!(
                            "Warning: failed to persist dispatch receipt for '{}': {}",
                            agent_type, err
                        );
                    }
                }
                println!("Agent '{}' completed successfully.", agent_type);
            } else {
                eprintln!("Agent '{}' exited with code {}.", agent_type, code);
                std::process::exit(code);
            }
        }
        Err(e) => {
            let mut runtime_snapshot = session_store
                .load_runtime_snapshot(&repo_name, issue)
                .unwrap_or(None)
                .unwrap_or_else(|| {
                    crate::runtime_state::IssueRuntimeSnapshot::new(&repo_name, issue)
                });
            runtime_snapshot.note_agent_finished(
                agent_type,
                &started_at,
                false,
                format!(
                    "Dispatch failed to spawn for {}#{}: {}",
                    repo_name, issue, e
                ),
            );
            let _ = session_store.save_runtime_snapshot(&repo_name, &runtime_snapshot);
            eprintln!("Error spawning agent '{}': {}", agent_type, e);
            std::process::exit(1);
        }
    }
}

/// Load an agent definition, preferring repo-local over embedded defaults.
fn load_agent_definition(agent_type: &str, repo_root: &Path) -> String {
    // Check repo-local agents directory first
    let local_path = repo_root
        .join(".githubclaw")
        .join("agents")
        .join(format!("{}.md", agent_type));
    if local_path.exists() {
        return fs::read_to_string(&local_path).unwrap_or_default();
    }

    // Fall back to embedded defaults
    match agent_type {
        "orchestrator" => DEFAULT_AGENT_ORCHESTRATOR.to_string(),
        "implementer" => DEFAULT_AGENT_IMPLEMENTER.to_string(),
        "verifier" => DEFAULT_AGENT_VERIFIER.to_string(),
        "reviewer" => DEFAULT_AGENT_REVIEWER.to_string(),
        "vision-gap-analyst" => DEFAULT_AGENT_VISION_GAP_ANALYST.to_string(),
        "bug-reproducer" => DEFAULT_AGENT_BUG_REPRODUCER.to_string(),
        _ => {
            eprintln!(
                "Error: no embedded definition for agent type '{}'",
                agent_type
            );
            std::process::exit(1);
        }
    }
}

// ===========================================================================
// cmd_release — Start release pipeline
// ===========================================================================

fn cmd_release(repo: Option<&str>) {
    let repo_root = find_repo_root(None).unwrap_or_else(|| {
        eprintln!("Error: not inside a git repository.");
        std::process::exit(1);
    });

    let repo_name = match repo {
        Some(r) => r.to_string(),
        None => detect_github_remote(&repo_root).unwrap_or_else(|| {
            eprintln!("Error: cannot detect GitHub remote. Use --repo flag.");
            std::process::exit(1);
        }),
    };

    println!("Starting release pipeline for {} ...", repo_name);

    // Create release branch from dev
    let output = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(&repo_root)
        .output();

    let current_branch = match output {
        Ok(o) => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        Err(e) => {
            eprintln!("Error getting current branch: {}", e);
            std::process::exit(1);
        }
    };

    if current_branch != "dev" {
        eprintln!(
            "Error: release must be started from 'dev' branch (currently on '{}')",
            current_branch
        );
        std::process::exit(1);
    }

    // Generate release branch name with timestamp
    let timestamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
    let release_branch = format!("release/{}", timestamp);

    // Create release branch
    let status = Command::new("git")
        .args(["checkout", "-b", &release_branch])
        .current_dir(&repo_root)
        .status();

    if let Err(e) = status {
        eprintln!("Error creating release branch: {}", e);
        std::process::exit(1);
    }

    // Push release branch
    let status = Command::new("git")
        .args(["push", "-u", "origin", &release_branch])
        .current_dir(&repo_root)
        .status();

    if let Err(e) = status {
        eprintln!("Error pushing release branch: {}", e);
        std::process::exit(1);
    }

    // Create release PR via gh CLI directly (no orchestrator dispatch needed
    // for the initial PR — orchestrator can be dispatched separately if needed)
    println!("Creating release PR...");
    let pr_body = format!(
        "## Release from `{}`\n\n\
         Automated release PR. Review changes and complete dogfooding checklist before merging.\n\n\
         ---\n_Generated by `githubclaw release`_",
        release_branch
    );
    let status = Command::new("gh")
        .args([
            "pr",
            "create",
            "--base",
            "main",
            "--head",
            &release_branch,
            "--title",
            &format!("Release {}", release_branch.replace("release/", "")),
            "--body",
            &pr_body,
        ])
        .current_dir(&repo_root)
        .status();

    match status {
        Ok(s) if s.success() => {
            println!("Release PR created successfully.");
            println!("Complete the dogfooding checklist, then merge via GitHub web UI.");
        }
        Ok(s) => {
            eprintln!("gh pr create exited with code {:?}", s.code());
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("Failed to create release PR: {}", e);
            std::process::exit(1);
        }
    }
}

// ===========================================================================
// cmd_tui — Launch TUI dashboard
// ===========================================================================

fn cmd_tui() {
    crate::tui::startup::run_tui_startup_checks();
    let repo_root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
    crate::tui::ui::run(&repo_root).unwrap_or_else(|err| {
        eprintln!("Error: failed to run TUI: {}", err);
        std::process::exit(1);
    });
}

// ===========================================================================
// Tests
// ===========================================================================

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

    #[test]
    fn test_parse_github_remote_ssh() {
        let result = parse_github_remote("git@github.com:octocat/Hello-World.git");
        assert_eq!(result, Some("octocat/Hello-World".to_string()));
    }

    #[test]
    fn test_parse_github_remote_https() {
        let result = parse_github_remote("https://github.com/octocat/Hello-World.git");
        assert_eq!(result, Some("octocat/Hello-World".to_string()));
    }

    #[test]
    fn test_parse_github_remote_https_no_git_suffix() {
        let result = parse_github_remote("https://github.com/octocat/Hello-World");
        assert_eq!(result, Some("octocat/Hello-World".to_string()));
    }

    #[test]
    fn test_parse_github_remote_invalid() {
        assert_eq!(parse_github_remote("not-a-url"), None);
        assert_eq!(parse_github_remote("https://gitlab.com/owner/repo"), None);
        assert_eq!(parse_github_remote(""), None);
    }

    #[test]
    fn test_dispatch_command_accepts_dedupe_flags() {
        let cli = Cli::try_parse_from([
            "githubclaw",
            "dispatch",
            "implementer",
            "--issue",
            "42",
            "--prompt",
            "Fix bug",
            "--event-id",
            "evt-123",
            "--dedupe-key",
            "second-pass",
        ])
        .unwrap();

        match cli.command {
            Commands::Dispatch {
                agent_type,
                issue,
                prompt,
                event_id,
                dedupe_key,
                ..
            } => {
                assert_eq!(agent_type, "implementer");
                assert_eq!(issue, 42);
                assert_eq!(prompt, "Fix bug");
                assert_eq!(event_id.as_deref(), Some("evt-123"));
                assert_eq!(dedupe_key.as_deref(), Some("second-pass"));
            }
            _ => panic!("expected dispatch command"),
        }
    }
}