kdo 0.2.0-alpha.1

Context-native workspace manager for AI coding agents. Cuts token consumption on polyglot monorepos.
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
//! kdo CLI — context-native workspace manager for AI agents.

mod bench;
mod run;
mod setup;

use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{generate, Shell};
use indicatif::{ProgressBar, ProgressStyle};
use kdo_context::ContextGenerator;
use kdo_core::WorkspaceConfig;
use kdo_graph::WorkspaceGraph;
use miette::IntoDiagnostic;
use owo_colors::OwoColorize;
use std::io::{self, Write};
use std::path::Path;
use tabled::{Table, Tabled};
use tracing::info;

#[derive(Parser)]
#[command(name = "kdo", version, about = "Workspace manager for the agent era")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize a kdo workspace. Scaffolds template if empty, adopts existing repo otherwise.
    Init,

    /// Create a new project in the workspace with interactive scaffolding.
    New {
        /// Project name.
        name: String,
    },

    /// Run a named task across workspace projects.
    Run {
        /// Task name (e.g., build, test, lint, dev).
        task: String,

        /// Only run in this project (name or substring match).
        #[arg(long)]
        filter: Option<String>,

        /// Run independent projects in parallel.
        #[arg(long)]
        parallel: bool,

        /// Print the resolved pipeline without executing.
        #[arg(long)]
        dry_run: bool,

        /// Extra args appended to the resolved command (use after `--`).
        #[arg(last = true)]
        args: Vec<String>,
    },

    /// Run an arbitrary command in each project directory.
    Exec {
        /// Command to execute (quoted).
        command: String,

        /// Only run in this project (name or substring match).
        #[arg(long)]
        filter: Option<String>,

        /// Run in all projects in parallel.
        #[arg(long)]
        parallel: bool,
    },

    /// List all projects in the workspace.
    List {
        /// Output format.
        #[arg(long, default_value = "table")]
        format: OutputFormat,
    },

    /// Show the dependency graph.
    Graph {
        /// Output format.
        #[arg(long, default_value = "text")]
        format: GraphFormat,
    },

    /// Generate a context bundle for a project within a token budget.
    Context {
        /// Project name.
        project: String,

        /// Token budget.
        #[arg(long, default_value = "4096")]
        budget: usize,

        /// Output format.
        #[arg(long, default_value = "table")]
        format: OutputFormat,
    },

    /// List projects affected by changes since a git ref.
    Affected {
        /// Git base ref.
        #[arg(long, default_value = "main")]
        base: String,

        /// Output format.
        #[arg(long, default_value = "table")]
        format: OutputFormat,
    },

    /// Validate workspace health.
    Doctor,

    /// Generate shell completions.
    Completions {
        /// Shell to generate completions for.
        shell: Shell,
    },

    /// Start the MCP server.
    Serve {
        /// Transport type.
        #[arg(long, default_value = "stdio")]
        transport: String,

        /// Agent profile: `claude`, `openclaw`, or `generic`. Tunes context budget,
        /// loop-detection window, and tool description length for the target agent.
        #[arg(long, default_value = "generic")]
        agent: String,
    },

    /// Find projects structurally similar to the given one.
    Similar {
        /// Project name.
        project: String,

        /// Number of results to return.
        #[arg(long, default_value = "5")]
        limit: usize,

        /// Output format.
        #[arg(long, default_value = "table")]
        format: OutputFormat,
    },

    /// Look up a symbol's definition across the workspace.
    Source {
        /// Symbol name (function, struct, class, type).
        symbol: String,

        /// Only search this project.
        #[arg(long)]
        filter: Option<String>,
    },

    /// Benchmark token consumption: baseline (filesystem walk) vs kdo (MCP).
    Bench {
        /// Only run tasks whose name contains this substring.
        #[arg(long)]
        task: Option<String>,

        /// Repeat each measurement this many times and report the median.
        #[arg(long, default_value = "1")]
        iterations: usize,

        /// Instead of proxy measurement, parse a real agent session log
        /// (Claude Code JSONL) and report observed token usage.
        #[arg(long, value_name = "PATH")]
        from_log: Option<std::path::PathBuf>,
    },

    /// Wire kdo into a coding agent's config (Claude Code or OpenClaw).
    Setup {
        /// Agent to set up: `claude` or `openclaw`.
        agent: String,

        /// Write to user-level config instead of workspace-level.
        #[arg(long)]
        global: bool,

        /// Print every file + command that would change, without touching disk.
        #[arg(long)]
        dry_run: bool,
    },

    /// Upgrade kdo to the latest release (or a specific version).
    Upgrade {
        /// Install a specific version (e.g. `0.1.0-alpha.3`). Default: latest release.
        #[arg(long)]
        version: Option<String>,

        /// Show what would happen without changing the binary.
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Clone, ValueEnum)]
enum OutputFormat {
    Table,
    Json,
}

#[derive(Clone, ValueEnum)]
enum GraphFormat {
    Text,
    Json,
    Dot,
}

#[derive(Tabled)]
struct ProjectRow {
    #[tabled(rename = "Name")]
    name: String,
    #[tabled(rename = "Language")]
    language: String,
    #[tabled(rename = "Summary")]
    summary: String,
    #[tabled(rename = "Deps")]
    dep_count: usize,
}

#[derive(Tabled)]
struct AffectedRow {
    #[tabled(rename = "Project")]
    name: String,
}

fn main() -> miette::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
        )
        .with_writer(io::stderr)
        .init();

    let cli = Cli::parse();

    match cli.command {
        Commands::Init => cmd_init()?,
        Commands::New { name } => cmd_new(&name)?,
        Commands::Run {
            task,
            filter,
            parallel,
            dry_run,
            args,
        } => cmd_run(&task, filter.as_deref(), parallel, dry_run, &args)?,
        Commands::Exec {
            command,
            filter,
            parallel,
        } => cmd_exec(&command, filter.as_deref(), parallel)?,
        Commands::List { format } => cmd_list(format)?,
        Commands::Graph { format } => cmd_graph(format)?,
        Commands::Context {
            project,
            budget,
            format,
        } => cmd_context(&project, budget, format)?,
        Commands::Affected { base, format } => cmd_affected(&base, format)?,
        Commands::Doctor => cmd_doctor()?,
        Commands::Completions { shell } => cmd_completions(shell)?,
        Commands::Serve { transport, agent } => cmd_serve(&transport, &agent)?,
        Commands::Similar {
            project,
            limit,
            format,
        } => cmd_similar(&project, limit, format)?,
        Commands::Source { symbol, filter } => cmd_source(&symbol, filter.as_deref())?,
        Commands::Bench {
            task,
            iterations,
            from_log,
        } => bench::cmd_bench(task.as_deref(), iterations, from_log.as_deref())?,
        Commands::Setup {
            agent,
            global,
            dry_run,
        } => setup::cmd_setup(&agent, global, dry_run)?,
        Commands::Upgrade { version, dry_run } => cmd_upgrade(version.as_deref(), dry_run)?,
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// .kdo/ and kdo.toml management
// ---------------------------------------------------------------------------

const KDO_TOML: &str = "kdo.toml";
const KDO_DIR: &str = ".kdo";
const KDO_CONTEXT_DIR: &str = ".kdo/context";
const KDO_CACHE_DIR: &str = ".kdo/cache";
const KDO_GRAPH_CACHE: &str = ".kdo/graph.json";
const KDOIGNORE_FILE: &str = ".kdoignore";

/// Create the `.kdo/` cache directory structure.
fn create_kdo_dir(root: &Path) -> miette::Result<()> {
    std::fs::create_dir_all(root.join(KDO_CONTEXT_DIR)).into_diagnostic()?;
    std::fs::create_dir_all(root.join(KDO_CACHE_DIR)).into_diagnostic()?;
    Ok(())
}

/// Write `kdo.toml` at workspace root.
///
/// Generates a richly-commented template whose tasks match the languages detected
/// in the workspace. The resulting file both runs out of the box and teaches the
/// reader the full schema (env, aliases, depends_on, per-project overrides).
fn write_kdo_toml(
    root: &Path,
    workspace_name: &str,
    projects: &[String],
    languages: &std::collections::HashSet<kdo_core::Language>,
) -> miette::Result<()> {
    let path = root.join(KDO_TOML);
    if path.exists() {
        info!(path = %path.display(), "kdo.toml already exists, leaving it alone");
        return Ok(());
    }

    let (build_cmd, test_cmd, lint_cmd, fmt_cmd, dev_cmd) = detect_default_tasks(languages);

    let projects_line = if projects.is_empty() {
        "# (no projects yet — run `kdo new <name>` to scaffold one)".to_string()
    } else {
        format!("# Projects: {}", projects.join(", "))
    };

    let content = format!(
        r#"# kdo workspace configuration
# https://github.com/vivekpal1/kdo
#
{projects_line}

[workspace]
name = "{workspace_name}"
# Restrict project discovery to specific globs (optional — default scans everything):
# projects = ["apps/*", "packages/*", "crates/*"]
# exclude  = ["legacy/**", "archive/**"]

# Short aliases: `kdo run b` → `kdo run build`.
[aliases]
b = "build"
t = "test"
l = "lint"

# Workspace-wide environment (merged into every task invocation).
# Loaded before `[env]`; keys here win over env_files.
# [env]
# RUST_BACKTRACE = "1"
# env_files = [".env", ".env.local"]

# ─────────────────────────── TASKS ───────────────────────────
# Tasks can be declared two ways:
#
#   1. Bare command:
#        build = "cargo build"
#
#   2. Full spec with pipeline semantics:
#        [tasks.build]
#        command     = "cargo build"
#        depends_on  = ["^build"]          # "^task" = run `task` in every
#                                          #          upstream dep project first
#                                          # "task"  = same project, earlier step
#                                          # "//task"= workspace-wide task first
#        inputs      = ["src/**", "Cargo.toml"]
#        outputs     = ["target/debug/"]
#        cache       = true                # reserved for future cache backend
#        persistent  = false               # long-running (dev server) — don't block
#        env         = {{ RUST_LOG = "info" }}

[tasks]
build = "{build}"
test  = "{test}"
lint  = "{lint}"
fmt   = "{fmt}"
dev   = "{dev}"

# Example pipeline (uncomment to use):
# [tasks.ci]
# depends_on = ["lint", "test", "build"]

# ────────────────────── PER-PROJECT OVERRIDES ─────────────────
# Override tasks or env for a specific project:
# [projects.my-service]
# env = {{ DATABASE_URL = "postgres://localhost/myservice_dev" }}
#
# [projects.my-service.tasks]
# build = "cargo build --release --features prod"
"#,
        build = build_cmd,
        test = test_cmd,
        lint = lint_cmd,
        fmt = fmt_cmd,
        dev = dev_cmd,
    );

    std::fs::write(&path, content).into_diagnostic()?;
    info!(path = %path.display(), "wrote kdo.toml");
    Ok(())
}

/// Pick sensible default commands based on languages present in the workspace.
fn detect_default_tasks(
    languages: &std::collections::HashSet<kdo_core::Language>,
) -> (
    &'static str,
    &'static str,
    &'static str,
    &'static str,
    &'static str,
) {
    use kdo_core::Language;
    let has = |l: &Language| languages.contains(l);

    if has(&Language::Rust) || has(&Language::Anchor) {
        (
            "cargo build",
            "cargo test",
            "cargo clippy --all-targets -- -D warnings",
            "cargo fmt --all",
            "cargo run",
        )
    } else if has(&Language::TypeScript) || has(&Language::JavaScript) {
        (
            "npm run build",
            "npm test",
            "npm run lint",
            "npm run format",
            "npm run dev",
        )
    } else if has(&Language::Python) {
        (
            "python -m build",
            "python -m pytest",
            "ruff check .",
            "ruff format .",
            "python -m app",
        )
    } else if has(&Language::Go) {
        (
            "go build ./...",
            "go test ./...",
            "golangci-lint run",
            "gofmt -w .",
            "go run .",
        )
    } else {
        (
            "echo 'configure build in kdo.toml'",
            "echo 'configure test in kdo.toml'",
            "echo 'configure lint in kdo.toml'",
            "echo 'configure fmt in kdo.toml'",
            "echo 'configure dev in kdo.toml'",
        )
    }
}

/// Write a `.kdoignore` file with sensible defaults.
fn write_kdoignore(root: &Path) -> miette::Result<()> {
    let ignore_path = root.join(KDOIGNORE_FILE);
    if ignore_path.exists() {
        return Ok(());
    }
    let content = "\
node_modules/
target/
dist/
build/
__pycache__/
.git/
.kdo/
*.lock
";
    std::fs::write(&ignore_path, content).into_diagnostic()?;
    info!(path = %ignore_path.display(), "created .kdoignore");
    Ok(())
}

/// Ensure `.gitignore` has kdo entries and language-specific patterns.
fn ensure_gitignore(
    root: &Path,
    languages: &std::collections::HashSet<kdo_core::Language>,
) -> miette::Result<()> {
    let gitignore_path = root.join(".gitignore");
    let existing = std::fs::read_to_string(&gitignore_path).unwrap_or_default();

    let mut additions = String::new();

    // kdo entries
    if !existing.contains(".kdo") {
        additions.push_str("\n# kdo\n.kdo/\nTODO.md\n");
    }

    // Rust / Anchor
    if (languages.contains(&kdo_core::Language::Rust)
        || languages.contains(&kdo_core::Language::Anchor))
        && !existing.contains("target/")
    {
        additions.push_str("\n# Rust\ntarget/\n");
    }

    // Node / TypeScript / JavaScript
    if (languages.contains(&kdo_core::Language::TypeScript)
        || languages.contains(&kdo_core::Language::JavaScript))
        && !existing.contains("node_modules")
    {
        additions.push_str("\n# Node\nnode_modules/\ndist/\n.next/\n");
    }

    // Python
    if languages.contains(&kdo_core::Language::Python) && !existing.contains("__pycache__") {
        additions.push_str("\n# Python\n__pycache__/\n*.pyc\n.venv/\n");
    }

    // Go
    if languages.contains(&kdo_core::Language::Go) && !existing.contains("vendor/") {
        additions.push_str("\n# Go\nvendor/\n*.test\n");
    }

    // Common
    if !existing.contains(".DS_Store") {
        additions.push_str("\n# OS\n.DS_Store\n");
    }

    if !additions.is_empty() {
        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&gitignore_path)
            .into_diagnostic()?;
        file.write_all(additions.as_bytes()).into_diagnostic()?;
    }
    Ok(())
}

/// Generate context files into `.kdo/context/`.
fn generate_all_context(root: &Path, graph: &WorkspaceGraph) -> miette::Result<usize> {
    let context_dir = root.join(KDO_CONTEXT_DIR);
    std::fs::create_dir_all(&context_dir).into_diagnostic()?;

    let projects = graph.projects();
    let pb = ProgressBar::new(projects.len() as u64);
    pb.set_style(
        ProgressStyle::with_template(
            "  {spinner:.cyan} context {bar:30.cyan/blue} {pos}/{len} {msg}",
        )
        .unwrap()
        .progress_chars("=>-"),
    );
    pb.enable_steady_tick(std::time::Duration::from_millis(80));

    let mut count = 0;
    for project in &projects {
        pb.set_message(project.name.clone());
        let bundle = kdo_context::generate_context(graph, &project.name, 4096);
        if let Ok(bundle) = bundle {
            let md = kdo_context::render_context_md(&bundle);
            let context_path = context_dir.join(format!("{}.md", project.name));
            if std::fs::write(&context_path, &md).is_ok() {
                count += 1;
            }
        }
        pb.inc(1);
    }
    pb.finish_and_clear();

    // Cache graph snapshot
    let graph_output = graph.to_graph_output();
    if let Ok(json) = serde_json::to_string_pretty(&graph_output) {
        let _ = std::fs::write(root.join(KDO_GRAPH_CACHE), json);
    }

    Ok(count)
}

/// Load workspace config, or return default.
fn load_config(root: &Path) -> WorkspaceConfig {
    let path = root.join(KDO_TOML);
    WorkspaceConfig::load(&path).unwrap_or_default()
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

fn discover_graph() -> miette::Result<(WorkspaceGraph, std::path::PathBuf)> {
    let root = std::env::current_dir().into_diagnostic()?;
    let graph = WorkspaceGraph::discover(&root).map_err(|e| miette::miette!("{e}"))?;
    graph.detect_cycles().map_err(|e| miette::miette!("{e}"))?;
    Ok((graph, root))
}

fn cmd_init() -> miette::Result<()> {
    let root = std::env::current_dir().into_diagnostic()?;
    let workspace_name = root
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "workspace".into());

    let has_manifests = has_any_manifest(&root);

    // Create .kdo/ cache structure
    create_kdo_dir(&root)?;
    write_kdoignore(&root)?;

    if has_manifests {
        // Existing repo — discover and adopt
        let spinner = ProgressBar::new_spinner();
        spinner.set_style(
            ProgressStyle::with_template("  {spinner:.cyan} {msg}")
                .unwrap()
                .tick_strings(&["", "", "", "", "", "", "", "", "", ""]),
        );
        spinner.enable_steady_tick(std::time::Duration::from_millis(80));
        spinner.set_message("discovering workspace…");

        let graph = WorkspaceGraph::discover(&root).map_err(|e| {
            spinner.finish_and_clear();
            miette::miette!("{e}")
        })?;
        spinner.finish_and_clear();
        let project_names: Vec<String> = graph.projects().iter().map(|p| p.name.clone()).collect();
        let project_count = project_names.len();

        // Collect detected languages for gitignore generation
        let languages: std::collections::HashSet<kdo_core::Language> = graph
            .projects()
            .iter()
            .map(|p| p.language.clone())
            .collect();
        ensure_gitignore(&root, &languages)?;

        write_kdo_toml(&root, &workspace_name, &project_names, &languages)?;
        let ctx_count = generate_all_context(&root, &graph)?;

        eprintln!(
            "{} Initialized workspace with {} projects.",
            "kdo".cyan().bold(),
            project_count.to_string().green().bold()
        );
        eprintln!("  {} kdo.toml         workspace config", "create".green());
        eprintln!(
            "  {} .kdo/context/    {} context files",
            "create".green(),
            ctx_count
        );
        eprintln!("  {} .kdoignore       ignore rules", "create".green());
        eprintln!("  {} .gitignore       updated", "create".green());
    } else {
        // Empty directory — scaffold template
        let empty = std::collections::HashSet::new();
        ensure_gitignore(&root, &empty)?;
        write_kdo_toml(&root, &workspace_name, &[], &empty)?;

        eprintln!("{} Initialized empty workspace.", "kdo".cyan().bold());
        eprintln!("  {} kdo.toml         workspace config", "create".green());
        eprintln!("  {} .kdo/            cache directory", "create".green());
        eprintln!("  {} .kdoignore       ignore rules", "create".green());
        eprintln!();
        eprintln!(
            "  Run {} to create your first project.",
            "kdo new <name>".yellow().bold()
        );
    }

    Ok(())
}

/// Check if any manifest files exist under root.
fn has_any_manifest(root: &Path) -> bool {
    let manifest_names = [
        "Cargo.toml",
        "package.json",
        "pyproject.toml",
        "Anchor.toml",
    ];
    for name in &manifest_names {
        if root.join(name).exists() {
            return true;
        }
    }
    if let Ok(entries) = std::fs::read_dir(root) {
        for entry in entries.flatten() {
            if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                let dir = entry.path();
                let dir_name = dir.file_name().unwrap_or_default().to_string_lossy();
                if matches!(
                    dir_name.as_ref(),
                    "node_modules" | "target" | ".git" | ".kdo" | "dist"
                ) {
                    continue;
                }
                for name in &manifest_names {
                    if dir.join(name).exists() {
                        return true;
                    }
                }
            }
        }
    }
    false
}

fn cmd_new(name: &str) -> miette::Result<()> {
    let root = std::env::current_dir().into_diagnostic()?;
    let project_dir = root.join(name);

    if project_dir.exists() {
        miette::bail!("directory '{}' already exists", name);
    }

    let language = prompt_select(
        "Language",
        &["rust", "typescript", "python", "anchor", "go"],
    )?;
    let project_type = prompt_select("Type", &["library", "binary"])?;

    let framework = match language.as_str() {
        "typescript" => prompt_select("Framework", &["none", "react", "next"])?,
        "python" => prompt_select("Framework", &["none", "fastapi", "cli"])?,
        "go" => prompt_select("Framework", &["none", "http", "cli"])?,
        "anchor" => "anchor".to_string(),
        _ => "none".to_string(),
    };

    scaffold_project(&project_dir, name, &language, &project_type, &framework)?;

    // Re-discover and update context
    if root.join(KDO_DIR).exists() {
        if let Ok(graph) = WorkspaceGraph::discover(&root) {
            let _ = generate_all_context(&root, &graph);
        }
    }

    eprintln!(
        "\n{} Created {} ({}{})",
        "kdo".cyan().bold(),
        name.green().bold(),
        language,
        if framework != "none" {
            format!("/{framework}")
        } else {
            String::new()
        }
    );
    eprintln!("  path: {}", project_dir.display().to_string().dimmed());

    Ok(())
}

fn cmd_run(
    task: &str,
    filter: Option<&str>,
    parallel: bool,
    dry_run: bool,
    extra_args: &[String],
) -> miette::Result<()> {
    let (graph, root) = discover_graph()?;
    let config = load_config(&root);

    let mode = if dry_run {
        "dry-run".magenta().to_string()
    } else if parallel {
        "parallel".dimmed().to_string()
    } else {
        "sequential".dimmed().to_string()
    };
    eprintln!(
        "{} {} {} {}",
        "kdo".cyan().bold(),
        "run".bold(),
        task.yellow().bold(),
        mode
    );

    run::run_task(&graph, &config, task, filter, parallel, dry_run, extra_args)
}

fn cmd_exec(command: &str, filter: Option<&str>, parallel: bool) -> miette::Result<()> {
    let (graph, _root) = discover_graph()?;

    eprintln!(
        "{} {} {}",
        "kdo".cyan().bold(),
        "exec".bold(),
        command.dimmed()
    );

    run::exec_command(&graph, command, filter, parallel)
}

fn cmd_list(format: OutputFormat) -> miette::Result<()> {
    let (graph, _root) = discover_graph()?;
    let summaries = graph.project_summaries();

    match format {
        OutputFormat::Json => {
            let json = serde_json::to_string_pretty(&summaries).into_diagnostic()?;
            println!("{json}");
        }
        OutputFormat::Table => {
            let rows: Vec<ProjectRow> = summaries
                .iter()
                .map(|s| ProjectRow {
                    name: s.name.clone(),
                    language: s.language.clone(),
                    summary: s
                        .summary
                        .as_deref()
                        .unwrap_or("-")
                        .chars()
                        .take(50)
                        .collect(),
                    dep_count: s.dep_count,
                })
                .collect();

            if rows.is_empty() {
                eprintln!("{}", "No projects found.".yellow());
            } else {
                eprintln!(
                    "{} {} projects\n",
                    "kdo".cyan().bold(),
                    rows.len().to_string().green().bold()
                );
                println!("{}", Table::new(&rows));
            }
        }
    }

    Ok(())
}

fn cmd_graph(format: GraphFormat) -> miette::Result<()> {
    let (graph, _root) = discover_graph()?;

    match format {
        GraphFormat::Text => print!("{}", graph.to_text()),
        GraphFormat::Json => {
            let output = graph.to_graph_output();
            let json = serde_json::to_string_pretty(&output).into_diagnostic()?;
            println!("{json}");
        }
        GraphFormat::Dot => print!("{}", graph.to_dot()),
    }

    Ok(())
}

fn cmd_context(project: &str, budget: usize, format: OutputFormat) -> miette::Result<()> {
    let (graph, root) = discover_graph()?;
    let bundle = kdo_context::generate_context(&graph, project, budget)
        .map_err(|e| miette::miette!("{e}"))?;

    // Cache to .kdo/context/
    let kdo_context_dir = root.join(KDO_CONTEXT_DIR);
    if kdo_context_dir.exists() {
        let md = kdo_context::render_context_md(&bundle);
        let context_path = kdo_context_dir.join(format!("{project}.md"));
        let _ = std::fs::write(context_path, &md);
    }

    match format {
        OutputFormat::Json => {
            let json = serde_json::to_string_pretty(&bundle).into_diagnostic()?;
            println!("{json}");
        }
        OutputFormat::Table => {
            let md = kdo_context::render_context_md(&bundle);
            print!("{md}");
        }
    }

    Ok(())
}

fn cmd_affected(base: &str, format: OutputFormat) -> miette::Result<()> {
    let (graph, _root) = discover_graph()?;
    let affected = graph
        .affected_since_ref(base)
        .map_err(|e| miette::miette!("{e}"))?;

    match format {
        OutputFormat::Json => {
            let json = serde_json::to_string_pretty(&affected).into_diagnostic()?;
            println!("{json}");
        }
        OutputFormat::Table => {
            if affected.is_empty() {
                eprintln!(
                    "{} No projects affected since {}.",
                    "kdo".cyan().bold(),
                    base.yellow()
                );
            } else {
                let rows: Vec<AffectedRow> = affected
                    .iter()
                    .map(|name| AffectedRow { name: name.clone() })
                    .collect();
                println!("{}", Table::new(&rows));
            }
        }
    }

    Ok(())
}

fn cmd_doctor() -> miette::Result<()> {
    let root = std::env::current_dir().into_diagnostic()?;
    let mut issues = 0;
    let mut warnings = 0;

    eprintln!("{}", "kdo doctor".cyan().bold());
    eprintln!();

    // Check kdo.toml
    let kdo_toml = root.join(KDO_TOML);
    if kdo_toml.exists() {
        match WorkspaceConfig::load(&kdo_toml) {
            Ok(config) => {
                eprintln!(
                    "  {} kdo.toml (workspace: {})",
                    "ok".green(),
                    config.workspace.name
                );
            }
            Err(e) => {
                eprintln!("  {} kdo.toml: {}", "err".red(), e);
                issues += 1;
            }
        }
    } else {
        eprintln!("  {} kdo.toml not found. Run `kdo init`.", "warn".yellow());
        warnings += 1;
    }

    // Check .kdo/ directory
    if root.join(KDO_DIR).exists() {
        eprintln!("  {} .kdo/ cache directory", "ok".green());
    } else {
        eprintln!("  {} .kdo/ not found. Run `kdo init`.", "warn".yellow());
        warnings += 1;
    }

    // Check .kdoignore
    if root.join(KDOIGNORE_FILE).exists() {
        eprintln!("  {} .kdoignore", "ok".green());
    } else {
        eprintln!("  {} .kdoignore not found.", "warn".yellow());
        warnings += 1;
    }

    // Check .gitignore includes .kdo/
    let gitignore = std::fs::read_to_string(root.join(".gitignore")).unwrap_or_default();
    if gitignore.contains(".kdo") {
        eprintln!("  {} .gitignore includes .kdo/", "ok".green());
    } else {
        eprintln!(
            "  {} .kdo/ not in .gitignore (cache may be committed)",
            "warn".yellow()
        );
        warnings += 1;
    }

    // Discover and check graph
    match WorkspaceGraph::discover(&root) {
        Ok(graph) => {
            let projects = graph.projects();
            eprintln!("  {} {} projects discovered", "ok".green(), projects.len());

            match graph.detect_cycles() {
                Ok(()) => eprintln!("  {} no circular dependencies", "ok".green()),
                Err(e) => {
                    eprintln!("  {} {}", "err".red(), e);
                    issues += 1;
                }
            }

            // Check context freshness
            let context_dir = root.join(KDO_CONTEXT_DIR);
            if context_dir.exists() {
                let mut stale = 0;
                for project in &projects {
                    let ctx_path = context_dir.join(format!("{}.md", project.name));
                    if !ctx_path.exists() {
                        stale += 1;
                    }
                }
                if stale > 0 {
                    eprintln!(
                        "  {} {} projects missing context files. Run `kdo init` to regenerate.",
                        "warn".yellow(),
                        stale
                    );
                    warnings += 1;
                } else {
                    eprintln!("  {} all context files present", "ok".green());
                }
            }

            // Check git status
            let git_check = std::process::Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(&root)
                .output();
            match git_check {
                Ok(output) if output.status.success() => {
                    let changes = String::from_utf8_lossy(&output.stdout);
                    let change_count = changes.lines().count();
                    if change_count > 0 {
                        eprintln!("  {} {} uncommitted changes", "info".blue(), change_count);
                    } else {
                        eprintln!("  {} git working tree clean", "ok".green());
                    }
                }
                _ => {
                    eprintln!("  {} not a git repository", "info".blue());
                }
            }
        }
        Err(e) => {
            eprintln!("  {} workspace discovery failed: {}", "err".red(), e);
            issues += 1;
        }
    }

    eprintln!();
    if issues > 0 {
        eprintln!(
            "  {} {} issues, {} warnings",
            "FAIL".red().bold(),
            issues,
            warnings
        );
        miette::bail!("{issues} issues found");
    } else if warnings > 0 {
        eprintln!("  {} {} warnings", "WARN".yellow().bold(), warnings);
    } else {
        eprintln!("  {} workspace is healthy", "PASS".green().bold());
    }

    Ok(())
}

fn cmd_completions(shell: Shell) -> miette::Result<()> {
    let mut cmd = Cli::command();
    generate(shell, &mut cmd, "kdo", &mut io::stdout());
    Ok(())
}

fn cmd_serve(transport: &str, agent: &str) -> miette::Result<()> {
    let profile: kdo_mcp::AgentProfile = agent
        .parse()
        .map_err(|e: kdo_mcp::UnknownAgent| miette::miette!("{e}"))?;

    match transport {
        "stdio" => {
            let root = std::env::current_dir().into_diagnostic()?;
            let graph = WorkspaceGraph::discover(&root).map_err(|e| miette::miette!("{e}"))?;
            let ctx_gen = ContextGenerator::new();

            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .into_diagnostic()?;
            runtime
                .block_on(kdo_mcp::run_stdio(graph, ctx_gen, root, profile))
                .map_err(|e| miette::miette!("{e}"))?;
        }
        other => {
            miette::bail!("unsupported transport: {other}. Only 'stdio' is supported.");
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// similar / source / upgrade
// ---------------------------------------------------------------------------

#[derive(Tabled)]
struct SimilarRow {
    #[tabled(rename = "Project")]
    name: String,
    #[tabled(rename = "Language")]
    language: String,
    #[tabled(rename = "Score")]
    score: String,
    #[tabled(rename = "Shared deps")]
    shared: String,
}

/// Find projects structurally similar to `project_name`.
/// Similarity = (same language bonus) + Jaccard(dependency sets).
fn cmd_similar(project_name: &str, limit: usize, format: OutputFormat) -> miette::Result<()> {
    let (graph, _root) = discover_graph()?;
    let target = graph
        .get_project(project_name)
        .map_err(|e| miette::miette!("{e}"))?;
    let target_deps = graph
        .dependency_closure(project_name)
        .map_err(|e| miette::miette!("{e}"))?;
    let target_dep_names: std::collections::HashSet<String> =
        target_deps.iter().map(|p| p.name.clone()).collect();

    let mut scored: Vec<(f32, &kdo_core::Project, Vec<String>)> = Vec::new();
    for candidate in graph.projects() {
        if candidate.name == target.name {
            continue;
        }
        let cand_deps = graph
            .dependency_closure(&candidate.name)
            .map_err(|e| miette::miette!("{e}"))?;
        let cand_dep_names: std::collections::HashSet<String> =
            cand_deps.iter().map(|p| p.name.clone()).collect();

        let shared: Vec<String> = target_dep_names
            .intersection(&cand_dep_names)
            .cloned()
            .collect();
        let union = target_dep_names.union(&cand_dep_names).count().max(1);
        let jaccard = shared.len() as f32 / union as f32;
        let lang_bonus = if candidate.language == target.language {
            0.5
        } else {
            0.0
        };
        let score = jaccard + lang_bonus;
        if score > 0.0 {
            scored.push((score, candidate, shared));
        }
    }
    scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
    scored.truncate(limit);

    match format {
        OutputFormat::Json => {
            let json: Vec<serde_json::Value> = scored
                .iter()
                .map(|(score, p, shared)| {
                    serde_json::json!({
                        "name": p.name,
                        "language": p.language.to_string(),
                        "score": score,
                        "shared_deps": shared,
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&json).into_diagnostic()?);
        }
        OutputFormat::Table => {
            if scored.is_empty() {
                eprintln!("{}", "No similar projects found.".yellow());
                return Ok(());
            }
            let rows: Vec<SimilarRow> = scored
                .iter()
                .map(|(score, p, shared)| SimilarRow {
                    name: p.name.clone(),
                    language: p.language.to_string(),
                    score: format!("{score:.2}"),
                    shared: if shared.is_empty() {
                        "".into()
                    } else {
                        shared.join(", ")
                    },
                })
                .collect();
            eprintln!(
                "{} projects similar to {}",
                "kdo".cyan().bold(),
                project_name.yellow().bold()
            );
            println!("{}", Table::new(rows));
        }
    }
    Ok(())
}

/// Look up a symbol's definition across the workspace by grepping source files.
fn cmd_source(symbol: &str, filter: Option<&str>) -> miette::Result<()> {
    let (graph, _root) = discover_graph()?;
    let projects: Vec<&kdo_core::Project> = graph
        .projects()
        .into_iter()
        .filter(|p| match filter {
            Some(f) => p.name == f || p.name.contains(f),
            None => true,
        })
        .collect();

    if projects.is_empty() {
        miette::bail!("no projects matched filter");
    }

    let patterns = build_symbol_patterns(symbol);
    let mut hits: Vec<SourceHit> = Vec::new();

    for project in &projects {
        for abs in walk_source_files(&project.path) {
            let Ok(content) = std::fs::read_to_string(&abs) else {
                continue;
            };
            let rel = abs.strip_prefix(&project.path).unwrap_or(&abs);
            for (line_no, line) in content.lines().enumerate() {
                if patterns.iter().any(|p| line.contains(p)) {
                    hits.push(SourceHit {
                        project: project.name.clone(),
                        file: rel.display().to_string(),
                        line: line_no + 1,
                        snippet: line.trim().to_string(),
                    });
                }
            }
        }
    }

    if hits.is_empty() {
        eprintln!(
            "{} No definition of {} found.",
            "kdo".cyan().bold(),
            symbol.yellow().bold()
        );
        return Ok(());
    }

    eprintln!(
        "{} {} hits for {}",
        "kdo".cyan().bold(),
        hits.len().to_string().green().bold(),
        symbol.yellow().bold()
    );
    for hit in &hits {
        println!(
            "  {}:{} {}",
            format!("{}/{}", hit.project, hit.file).cyan(),
            hit.line.to_string().yellow(),
            hit.snippet.dimmed()
        );
    }
    Ok(())
}

struct SourceHit {
    project: String,
    file: String,
    line: usize,
    snippet: String,
}

/// Walk a project directory for source files we care about, honoring `.gitignore`
/// / `.kdoignore` via the `ignore` crate.
fn walk_source_files(project_path: &Path) -> Vec<std::path::PathBuf> {
    const SOURCE_EXTS: &[&str] = &["rs", "ts", "tsx", "js", "jsx", "mjs", "cjs", "py", "go"];
    let mut builder = ignore::WalkBuilder::new(project_path);
    ignore::WalkBuilder::hidden(&mut builder, true);
    ignore::WalkBuilder::git_ignore(&mut builder, true);
    builder.add_custom_ignore_filename(".kdoignore");
    builder.filter_entry(|e| {
        let name = e.file_name().to_string_lossy();
        !matches!(
            name.as_ref(),
            "node_modules" | "target" | ".git" | ".kdo" | "dist" | "build" | "__pycache__"
        )
    });

    builder
        .build()
        .filter_map(|e| e.ok())
        .filter(|e: &ignore::DirEntry| e.file_type().map(|ft| ft.is_file()).unwrap_or(false))
        .map(|e| e.into_path())
        .filter(|p: &std::path::PathBuf| {
            p.extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| SOURCE_EXTS.contains(&ext))
        })
        .collect()
}

/// Build language-agnostic definition-ish patterns for a symbol.
fn build_symbol_patterns(symbol: &str) -> Vec<String> {
    vec![
        format!("fn {symbol}"),
        format!("fn {symbol}("),
        format!("pub fn {symbol}"),
        format!("struct {symbol}"),
        format!("enum {symbol}"),
        format!("trait {symbol}"),
        format!("type {symbol}"),
        format!("class {symbol}"),
        format!("interface {symbol}"),
        format!("def {symbol}("),
        format!("function {symbol}"),
        format!("export function {symbol}"),
        format!("export class {symbol}"),
        format!("export const {symbol}"),
        format!("export type {symbol}"),
        format!("const {symbol} ="),
        format!("func {symbol}("),
    ]
}

/// Upgrade kdo in place by downloading the latest release binary.
fn cmd_upgrade(version: Option<&str>, dry_run: bool) -> miette::Result<()> {
    let current_exe = std::env::current_exe().into_diagnostic()?;
    let platform = detect_platform()?;
    let target_version = match version {
        Some(v) => format!("v{}", v.trim_start_matches('v')),
        None => fetch_latest_tag()?,
    };

    let current = env!("CARGO_PKG_VERSION");
    let stripped = target_version.trim_start_matches('v');
    eprintln!(
        "{} {}{}",
        "kdo upgrade".cyan().bold(),
        current.dimmed(),
        stripped.yellow().bold()
    );

    if stripped == current {
        eprintln!("  {} already at {current}.", "ok".green());
        return Ok(());
    }

    let archive = format!("kdo-{target_version}-{platform}.tar.gz");
    let url =
        format!("https://github.com/vivekpal1/kdo/releases/download/{target_version}/{archive}");
    eprintln!("  {} {url}", "url".dimmed());
    eprintln!("  {} {}", "target".dimmed(), current_exe.display());

    if dry_run {
        eprintln!("  {} no changes made.", "dry-run".magenta());
        return Ok(());
    }

    let tmp_dir = std::env::temp_dir().join(format!("kdo-upgrade-{}", std::process::id()));
    std::fs::create_dir_all(&tmp_dir).into_diagnostic()?;
    let archive_path = tmp_dir.join(&archive);

    eprintln!("  {} downloading…", "»".bold());
    download_to_file(&url, &archive_path)?;

    eprintln!("  {} extracting…", "»".bold());
    let status = std::process::Command::new("tar")
        .arg("xzf")
        .arg(&archive_path)
        .arg("-C")
        .arg(&tmp_dir)
        .status()
        .into_diagnostic()?;
    if !status.success() {
        miette::bail!("failed to extract archive");
    }

    let new_binary = tmp_dir.join("kdo");
    if !new_binary.exists() {
        miette::bail!("extracted archive did not contain a `kdo` binary");
    }

    // Atomic replace: write to temp file next to current, then rename.
    let backup = current_exe.with_extension("old");
    std::fs::rename(&current_exe, &backup).into_diagnostic()?;
    if let Err(e) = std::fs::copy(&new_binary, &current_exe) {
        // Roll back on failure.
        let _ = std::fs::rename(&backup, &current_exe);
        return Err(miette::miette!("failed to install new binary: {e}"));
    }
    let _ = std::fs::remove_file(&backup);
    let _ = std::fs::remove_dir_all(&tmp_dir);

    eprintln!(
        "  {} installed kdo {}.",
        "ok".green(),
        stripped.yellow().bold()
    );
    Ok(())
}

/// Match the install-script naming convention.
fn detect_platform() -> miette::Result<&'static str> {
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    match (os, arch) {
        ("linux", "x86_64") => Ok("x86_64-unknown-linux-gnu"),
        ("linux", "aarch64") => Ok("aarch64-unknown-linux-gnu"),
        ("macos", "x86_64") => Ok("x86_64-apple-darwin"),
        ("macos", "aarch64") => Ok("aarch64-apple-darwin"),
        _ => miette::bail!(
            "no prebuilt binary for {os}/{arch}. Install from source with `cargo install kdo`."
        ),
    }
}

/// Fetch the most recent release tag (including prereleases) from the GitHub API.
///
/// `/releases/latest` skips prereleases, which is wrong for an alpha project.
/// We hit `/releases` (list, newest first) and take the first `tag_name`.
fn fetch_latest_tag() -> miette::Result<String> {
    let url = "https://api.github.com/repos/vivekpal1/kdo/releases?per_page=1";
    let curl = std::process::Command::new("curl")
        .args(["-fsSL", "-H", "User-Agent: kdo-upgrade", url])
        .output()
        .into_diagnostic()?;
    if !curl.status.success() {
        miette::bail!("failed to query GitHub releases API — does the repo have any releases yet?");
    }
    let body = String::from_utf8_lossy(&curl.stdout);
    let needle = "\"tag_name\":";
    let start = body.find(needle).ok_or_else(|| {
        miette::miette!("no releases found — install a specific version with --version")
    })?;
    let after = &body[start + needle.len()..];
    let q1 = after
        .find('"')
        .ok_or_else(|| miette::miette!("malformed release response"))?;
    let tail = &after[q1 + 1..];
    let q2 = tail
        .find('"')
        .ok_or_else(|| miette::miette!("malformed release response"))?;
    Ok(tail[..q2].to_string())
}

/// Download via curl (dependency-light; curl ships on macOS/Linux by default).
fn download_to_file(url: &str, dest: &Path) -> miette::Result<()> {
    let status = std::process::Command::new("curl")
        .args(["-fsSL", url, "-o"])
        .arg(dest)
        .status()
        .into_diagnostic()?;
    if !status.success() {
        miette::bail!("download failed for {url}");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Interactive prompts
// ---------------------------------------------------------------------------

fn prompt_select(label: &str, options: &[&str]) -> miette::Result<String> {
    eprint!("  {} ", label.bold());
    for (i, opt) in options.iter().enumerate() {
        if i == 0 {
            eprint!("[{}]", opt.green());
        } else {
            eprint!(" / {opt}");
        }
    }
    eprint!(": ");
    io::stderr().flush().into_diagnostic()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input).into_diagnostic()?;
    let input = input.trim();

    if input.is_empty() {
        return Ok(options[0].to_string());
    }

    for opt in options {
        if opt.starts_with(input) {
            return Ok(opt.to_string());
        }
    }

    Ok(input.to_string())
}

// ---------------------------------------------------------------------------
// Project scaffolding
// ---------------------------------------------------------------------------

fn scaffold_project(
    dir: &Path,
    name: &str,
    language: &str,
    project_type: &str,
    framework: &str,
) -> miette::Result<()> {
    let src_dir = dir.join("src");
    std::fs::create_dir_all(&src_dir).into_diagnostic()?;

    match language {
        "rust" => scaffold_rust(dir, &src_dir, name, project_type)?,
        "typescript" => scaffold_typescript(dir, &src_dir, name, framework)?,
        "python" => scaffold_python(dir, &src_dir, name, framework)?,
        "anchor" => scaffold_anchor(dir, &src_dir, name)?,
        "go" => scaffold_go(dir, name, framework)?,
        _ => scaffold_rust(dir, &src_dir, name, project_type)?,
    }

    Ok(())
}

fn scaffold_rust(dir: &Path, src_dir: &Path, name: &str, project_type: &str) -> miette::Result<()> {
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
description = ""

[dependencies]
"#
    );
    std::fs::write(dir.join("Cargo.toml"), cargo_toml).into_diagnostic()?;

    let (filename, content) = if project_type == "binary" {
        (
            "main.rs",
            format!(
                "//! {name} binary.\n\nfn main() {{\n    println!(\"hello from {name}\");\n}}\n"
            ),
        )
    } else {
        (
            "lib.rs",
            format!(
                "//! {name} library.\n\npub fn hello() -> &'static str {{\n    \"{name}\"\n}}\n\n#[cfg(test)]\nmod tests {{\n    use super::*;\n\n    #[test]\n    fn it_works() {{\n        assert_eq!(hello(), \"{name}\");\n    }}\n}}\n"
            ),
        )
    };
    std::fs::write(src_dir.join(filename), content).into_diagnostic()?;
    Ok(())
}

fn scaffold_typescript(
    dir: &Path,
    src_dir: &Path,
    name: &str,
    framework: &str,
) -> miette::Result<()> {
    let mut deps = serde_json::json!({});
    let mut dev_deps = serde_json::json!({ "typescript": "^5.0.0" });
    let mut scripts =
        serde_json::json!({ "build": "tsc", "dev": "tsc --watch", "test": "echo 'no tests'" });

    match framework {
        "react" => {
            deps = serde_json::json!({ "react": "^18.0.0", "react-dom": "^18.0.0" });
            dev_deps = serde_json::json!({ "typescript": "^5.0.0", "@types/react": "^18.0.0", "@types/react-dom": "^18.0.0" });
        }
        "next" => {
            deps = serde_json::json!({ "next": "^14.0.0", "react": "^18.0.0", "react-dom": "^18.0.0" });
            dev_deps = serde_json::json!({ "typescript": "^5.0.0", "@types/react": "^18.0.0" });
            scripts = serde_json::json!({ "dev": "next dev", "build": "next build", "start": "next start", "test": "echo 'no tests'" });
        }
        _ => {}
    }

    let package_json = serde_json::json!({
        "name": name,
        "version": "0.1.0",
        "description": "",
        "main": "src/index.ts",
        "scripts": scripts,
        "dependencies": deps,
        "devDependencies": dev_deps
    });

    std::fs::write(
        dir.join("package.json"),
        serde_json::to_string_pretty(&package_json).into_diagnostic()?,
    )
    .into_diagnostic()?;

    let tsconfig = serde_json::json!({
        "compilerOptions": {
            "target": "ES2020",
            "module": "commonjs",
            "strict": true,
            "outDir": "./dist",
            "declaration": true
        },
        "include": ["src/**/*"]
    });
    std::fs::write(
        dir.join("tsconfig.json"),
        serde_json::to_string_pretty(&tsconfig).into_diagnostic()?,
    )
    .into_diagnostic()?;

    let index_content = format!(
        "/**\n * {name}\n */\n\nexport function hello(): string {{\n  return \"{name}\";\n}}\n"
    );
    std::fs::write(src_dir.join("index.ts"), index_content).into_diagnostic()?;
    Ok(())
}

fn scaffold_python(dir: &Path, src_dir: &Path, name: &str, framework: &str) -> miette::Result<()> {
    let snake_name = name.replace('-', "_");

    let mut deps = vec![];
    match framework {
        "fastapi" => {
            deps.push("\"fastapi>=0.100\"".to_string());
            deps.push("\"uvicorn>=0.23\"".to_string());
        }
        "cli" => {
            deps.push("\"click>=8.0\"".to_string());
        }
        _ => {}
    }

    let deps_str = deps.join(",\n    ");
    let pyproject = format!(
        r#"[project]
name = "{name}"
version = "0.1.0"
description = ""
dependencies = [
    {deps_str}
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "ruff>=0.1",
]
"#
    );

    std::fs::write(dir.join("pyproject.toml"), pyproject).into_diagnostic()?;

    // Remove src/ for Python — use flat layout
    let _ = std::fs::remove_dir(src_dir);

    let py_content = match framework {
        "fastapi" => format!(
            "\"\"\"{name} — FastAPI application.\"\"\"\n\nfrom fastapi import FastAPI\n\napp = FastAPI(title=\"{name}\")\n\n\n@app.get(\"/\")\ndef root():\n    return {{\"message\": \"hello from {name}\"}}\n"
        ),
        "cli" => format!(
            "\"\"\"{name} — CLI application.\"\"\"\n\nimport click\n\n\n@click.group()\ndef cli():\n    \"\"\"{name} CLI.\"\"\"\n\n\n@cli.command()\ndef hello():\n    \"\"\"Say hello.\"\"\"\n    click.echo(\"hello from {name}\")\n\n\nif __name__ == \"__main__\":\n    cli()\n"
        ),
        _ => format!(
            "\"\"\"{name} library.\"\"\"\n\n\ndef hello() -> str:\n    \"\"\"Return greeting.\"\"\"\n    return \"{name}\"\n"
        ),
    };

    std::fs::write(dir.join(format!("{snake_name}.py")), py_content).into_diagnostic()?;
    Ok(())
}

fn scaffold_go(dir: &Path, name: &str, framework: &str) -> miette::Result<()> {
    let module_path = format!("github.com/user/{name}");

    let go_mod = format!("module {module_path}\n\ngo 1.21\n");
    std::fs::write(dir.join("go.mod"), go_mod).into_diagnostic()?;

    let main_content = match framework {
        "http" => format!(
            "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {{\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {{\n\t\tfmt.Fprintf(w, \"hello from {name}\")\n\t}})\n\thttp.ListenAndServe(\":8080\", nil)\n}}\n"
        ),
        "cli" => format!(
            "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {{\n\tif len(os.Args) > 1 {{\n\t\tfmt.Println(\"hello,\", os.Args[1])\n\t\treturn\n\t}}\n\tfmt.Println(\"hello from {name}\")\n}}\n"
        ),
        _ => format!(
            "package main\n\nimport \"fmt\"\n\n// Hello returns a greeting from {name}.\nfunc Hello() string {{\n\treturn \"hello from {name}\"\n}}\n\nfunc main() {{\n\tfmt.Println(Hello())\n}}\n"
        ),
    };

    std::fs::write(dir.join("main.go"), main_content).into_diagnostic()?;

    // Simple test file
    let test_content =
        "package main\n\nimport \"testing\"\n\nfunc TestHello(t *testing.T) {\n\tif got := Hello(); got == \"\" {\n\t\tt.Error(\"Hello() returned empty string\")\n\t}\n}\n";
    std::fs::write(dir.join("main_test.go"), test_content).into_diagnostic()?;

    Ok(())
}

fn scaffold_anchor(dir: &Path, src_dir: &Path, name: &str) -> miette::Result<()> {
    let snake_name = name.replace('-', "_");

    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
description = "Solana program built with Anchor"

[dependencies]
"#
    );
    std::fs::write(dir.join("Cargo.toml"), cargo_toml).into_diagnostic()?;

    let lib_content = format!(
        r#"//! {name} — Solana program.

/// Program state account.
pub struct State {{
    pub authority: [u8; 32],
    pub data: u64,
}}

/// Initialize the program state.
pub fn initialize(authority: [u8; 32]) -> Result<(), ()> {{
    let _ = authority;
    Ok(())
}}
"#
    );
    std::fs::write(src_dir.join("lib.rs"), lib_content).into_diagnostic()?;

    let anchor_toml = format!(
        r#"[features]
seeds = false

[programs.localnet]
{snake_name} = "11111111111111111111111111111111"

[provider]
cluster = "Localnet"
wallet = "~/.config/solana/id.json"
"#
    );
    std::fs::write(dir.join("Anchor.toml"), anchor_toml).into_diagnostic()?;
    Ok(())
}