knot 1.3.4

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, Build Systems, and HTML/CSS codebases
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
//! Configuration module.
//!
//! Resolves runtime configuration from three sources with the following precedence:
//!   1. CLI arguments (highest priority).
//!   2. Environment variables (set in the process environment).
//!   3. `$HOME/.config/knot/.env` (lowest priority — loaded from knot's
//!      XDG-style config directory, never from the current working directory).
//!
//! Provides specialized loaders for different binaries:
//! - [`Config::load_indexer`] for knot-indexer (indexing operations)
//! - [`Config::load_mcp`] for knot-mcp (MCP server)

use anyhow::{Context, Result};
use clap::{Parser, ValueEnum};

#[derive(Debug, Clone, ValueEnum, PartialEq, Default)]
pub enum OutputFormat {
    #[default]
    Table,
    Json,
    Markdown,
}

/// Command-line arguments for knot-indexer.
/// Includes all options for indexing, file watching, and query customization.
#[derive(Debug, Parser)]
#[command(
    name = "knot-indexer",
    version,
    about = "Codebase Graph + Vector RAG Indexer"
)]
pub struct IndexerCli {
    /// Path to the repository root that will be indexed.
    /// If not provided, defaults to the current working directory.
    #[arg(long, env = "KNOT_REPO_PATH")]
    pub repo_path: Option<String>,

    /// Logical repository name for multi-repository isolation.
    /// If not provided, defaults to the last component of repo_path.
    /// Example: 'my-java-repo', 'my-microservice'
    #[arg(long, env = "KNOT_REPO_NAME")]
    pub repo_name: Option<String>,

    /// Qdrant server URL (e.g. http://localhost:6334).
    #[arg(long, env = "KNOT_QDRANT_URL", default_value = "http://localhost:6334")]
    pub qdrant_url: String,

    /// Qdrant collection name where vectors will be stored.
    #[arg(long, env = "KNOT_QDRANT_COLLECTION", default_value = "knot_entities")]
    pub qdrant_collection: String,

    /// Neo4j Bolt URI (e.g. bolt://localhost:7687).
    #[arg(long, env = "KNOT_NEO4J_URI", default_value = "bolt://localhost:7687")]
    pub neo4j_uri: String,

    /// Neo4j username.
    #[arg(long, env = "KNOT_NEO4J_USER", default_value = "neo4j")]
    pub neo4j_user: String,

    /// Neo4j password.
    #[arg(long, env = "KNOT_NEO4J_PASSWORD")]
    pub neo4j_password: Option<String>,

    /// Optional path to a directory containing custom Tree-sitter query files
    /// (`java.scm`, `typescript.scm`). When set, these override the built-in
    /// queries shipped with the binary.
    #[arg(long, env = "KNOT_CUSTOM_QUERIES_PATH")]
    pub custom_queries_path: Option<String>,

    /// Embedding model dimension (must match the deployed fastembed model).
    #[arg(long, env = "KNOT_EMBED_DIM", default_value_t = 384)]
    pub embed_dim: u64,

    /// Number of files to process in each rayon parallel batch.
    #[arg(long, env = "KNOT_BATCH_SIZE", default_value_t = 64)]
    pub batch_size: usize,

    /// Force a full re-index by deleting all existing data for this repository.
    /// When false (default), performs incremental indexing by tracking file changes.
    #[arg(long, env = "KNOT_CLEAN", default_value_t = false)]
    pub clean: bool,

    /// Comma-separated list of repository names to include during cross-repository
    /// dependency analysis. When set, the indexer will load entity mappings from
    /// these additional repositories and resolve cross-repo calls/references.
    /// Example: `KNOT_DEPENDENCIES=core-lib,shared-types`
    #[arg(long, env = "KNOT_DEPENDENCIES")]
    pub dependencies: Option<String>,

    /// Run the indexer in watch mode.
    /// When enabled, the indexer will watch for filesystem changes and
    /// perform real-time incremental updates.
    #[arg(long, env = "KNOT_WATCH", default_value_t = false)]
    pub watch: bool,

    /// Path to a custom CA certificate bundle for corporate network model downloads.
    /// Used to enable fastembed model downloads through SSL-inspecting proxies.
    #[arg(long, env = "KNOT_CUSTOM_CA_CERTS")]
    pub custom_ca_certs: Option<String>,

    /// Maximum number of concurrent ingestion tasks.
    /// Controls how many batches are ingested into Qdrant + Neo4j simultaneously.
    /// Higher values increase throughput but also database load.
    #[arg(long, env = "KNOT_INGEST_CONCURRENCY", default_value_t = 4)]
    pub ingest_concurrency: usize,

    /// Number of threads for the Rayon parallel parsing thread pool.
    /// When not set, defaults to (logical CPUs - 1), leaving 1 core
    /// for the Tokio async runtime and OS. Minimum: 2.
    #[arg(long, env = "KNOT_RAYON_THREADS")]
    pub rayon_threads: Option<usize>,

    /// Include configuration files (YAML, JSON, .properties) and Kubernetes/Helm
    /// manifests in the index. Disabled by default to avoid indexing secrets and
    /// to speed up indexing in repos with heavy config content.
    /// Build system files (package.json, tsconfig.json, pom.xml, Cargo.toml,
    /// Jenkinsfile) are always indexed regardless of this flag.
    #[arg(long, env = "KNOT_INCLUDE_CONFIG_FILES", default_value_t = false)]
    pub include_config_files: bool,
}

/// Command-line arguments for knot-mcp.
/// Only includes options necessary for the MCP server to connect to databases.
#[derive(Debug, Parser)]
#[command(
    name = "knot-mcp",
    version,
    about = "knot MCP Server for Codebase Semantic Search"
)]
pub struct McpCli {
    /// Path to the repository root that will be indexed.
    /// If not provided, defaults to the current working directory.
    #[arg(long, env = "KNOT_REPO_PATH")]
    pub repo_path: Option<String>,

    /// Logical repository name for multi-repository isolation.
    /// If not provided, defaults to the last component of repo_path.
    /// Example: 'my-java-repo', 'my-microservice'
    #[arg(long, env = "KNOT_REPO_NAME")]
    pub repo_name: Option<String>,

    /// Qdrant server URL (e.g. http://localhost:6334).
    #[arg(long, env = "KNOT_QDRANT_URL", default_value = "http://localhost:6334")]
    pub qdrant_url: String,

    /// Qdrant collection name where vectors will be stored.
    #[arg(long, env = "KNOT_QDRANT_COLLECTION", default_value = "knot_entities")]
    pub qdrant_collection: String,

    /// Neo4j Bolt URI (e.g. bolt://localhost:7687).
    #[arg(long, env = "KNOT_NEO4J_URI", default_value = "bolt://localhost:7687")]
    pub neo4j_uri: String,

    /// Neo4j username.
    #[arg(long, env = "KNOT_NEO4J_USER", default_value = "neo4j")]
    pub neo4j_user: String,

    /// Neo4j password.
    #[arg(long, env = "KNOT_NEO4J_PASSWORD")]
    pub neo4j_password: Option<String>,

    /// Embedding model dimension (must match the deployed fastembed model).
    #[arg(long, env = "KNOT_EMBED_DIM", default_value_t = 384, hide = true)]
    pub embed_dim: u64,

    /// Run in offline/dry-run mode (for quality checks on deployment platforms).
    /// When enabled, skips all database and model initialization.
    /// The server responds to protocol requests but cannot execute queries.
    #[arg(long, env = "KNOT_DRY_RUN", default_value_t = false, hide = true)]
    pub dry_run: bool,

    /// Path to a custom CA certificate bundle for corporate network model downloads.
    /// Used to enable fastembed model downloads through SSL-inspecting proxies.
    #[arg(long, env = "KNOT_CUSTOM_CA_CERTS")]
    pub custom_ca_certs: Option<String>,
}

/// Resolved, validated configuration used throughout the application.
#[derive(Debug, Clone)]
pub struct Config {
    pub repo_path: String,
    pub repo_name: String,
    pub qdrant_url: String,
    pub qdrant_collection: String,
    pub neo4j_uri: String,
    pub neo4j_user: String,
    pub neo4j_password: String,
    pub custom_queries_path: Option<String>,
    pub embed_dim: u64,
    pub batch_size: usize,
    pub clean: bool,
    pub dependency_repos: Vec<String>,
    pub watch: bool,
    pub dry_run: bool,
    pub custom_ca_certs: Option<String>,
    pub output_format: OutputFormat,
    pub ingest_concurrency: usize,
    pub rayon_threads: Option<usize>,
    pub include_config_files: bool,
}

/// Returns the path where knot's `.env` file should be located.
///
/// Lookup order (first match wins):
/// 1. `$KNOT_CONFIG_DIR/.env` — explicit override for testing or custom setups
/// 2. `$HOME/.config/knot/.env` — Unix/Linux/macOS XDG-style default
/// 3. `$USERPROFILE/.config/knot/.env` — Windows fallback
///
/// This **never** resolves to the current working directory, unlike
/// `dotenvy::dotenv()` which walks up the directory tree from CWD.
fn knot_env_path() -> Option<std::path::PathBuf> {
    std::env::var("KNOT_CONFIG_DIR")
        .ok()
        .map(|d| std::path::PathBuf::from(d).join(".env"))
        .or_else(|| {
            std::env::var("HOME")
                .ok()
                .map(|d| std::path::PathBuf::from(d).join(".config/knot/.env"))
        })
        .or_else(|| {
            std::env::var("USERPROFILE")
                .ok()
                .map(|d| std::path::PathBuf::from(d).join(".config/knot/.env"))
        })
}

/// Load environment variables from knot's `.env` file.
///
/// Only loads from knot's XDG-style config directory (see [`knot_env_path`]).
/// Never loads from the current working directory, preventing `.env` files in
/// target repositories from hijacking knot's configuration.
fn load_knot_env() {
    let Some(env_path) = knot_env_path() else {
        tracing::debug!("No .env location found (set KNOT_CONFIG_DIR, HOME, or USERPROFILE)");
        return;
    };

    match dotenvy::from_path(&env_path) {
        Ok(_) => tracing::info!("Loaded env from {}", env_path.display()),
        Err(dotenvy::Error::Io(ref e)) if e.kind() == std::io::ErrorKind::NotFound => {
            tracing::debug!(
                "No .env file at {} — using environment variables and CLI args",
                env_path.display()
            );
        }
        Err(e) => {
            tracing::warn!("Failed to load .env from {}: {e}", env_path.display());
        }
    }
}

impl Config {
    /// Load configuration for the indexer binary (knot-indexer).
    /// Parses IndexerCli and includes all indexing-specific options.
    pub fn load_indexer() -> Result<Self> {
        Self::load_env_and_parse(IndexerCli::parse).map(
            |(cli, repo_path, repo_name, neo4j_password)| {
                let dependency_repos = if let Some(deps_str) = &cli.dependencies {
                    deps_str
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect()
                } else {
                    Vec::new()
                };

                Self {
                    repo_path,
                    repo_name,
                    qdrant_url: cli.qdrant_url,
                    qdrant_collection: cli.qdrant_collection,
                    neo4j_uri: cli.neo4j_uri,
                    neo4j_user: cli.neo4j_user,
                    neo4j_password,
                    custom_queries_path: cli.custom_queries_path,
                    embed_dim: cli.embed_dim,
                    batch_size: cli.batch_size,
                    clean: cli.clean,
                    dependency_repos,
                    watch: cli.watch,
                    dry_run: false,
                    custom_ca_certs: cli.custom_ca_certs,
                    output_format: OutputFormat::Markdown,
                    ingest_concurrency: cli.ingest_concurrency,
                    rayon_threads: cli.rayon_threads,
                    include_config_files: cli.include_config_files,
                }
            },
        )
    }

    /// Load configuration for the MCP server binary (knot-mcp).
    /// Parses McpCli and only includes MCP-relevant options.
    pub fn load_mcp() -> Result<Self> {
        Self::load_env_and_parse(McpCli::parse).map(
            |(cli, repo_path, repo_name, neo4j_password)| Self {
                repo_path,
                repo_name,
                qdrant_url: cli.qdrant_url,
                qdrant_collection: cli.qdrant_collection,
                neo4j_uri: cli.neo4j_uri,
                neo4j_user: cli.neo4j_user,
                neo4j_password,
                custom_queries_path: None,
                embed_dim: cli.embed_dim,
                batch_size: 0,
                clean: false,
                dependency_repos: Vec::new(),
                watch: false,
                dry_run: cli.dry_run,
                custom_ca_certs: cli.custom_ca_certs,
                output_format: OutputFormat::Markdown,
                ingest_concurrency: 4,
                rayon_threads: None,
                include_config_files: false,
            },
        )
    }

    /// Load configuration for the CLI binary (knot).
    /// Uses McpCli parser but ignores CLI subcommand arguments to avoid conflicts.
    /// This allows the CLI to accept search/callers/explore subcommands without
    /// clap trying to parse them as configuration arguments.
    pub fn load_knot_cli() -> Result<Self> {
        load_knot_env();

        // Parse McpCli from empty args to get defaults from env vars only
        // This avoids conflicts with knot subcommand arguments (search, callers, explore)
        let cli = McpCli::try_parse_from(["knot"])?;

        // Validate required fields from environment
        let neo4j_password = cli.neo4j_password()
            .or_else(|| std::env::var("KNOT_NEO4J_PASSWORD").ok())
            .context("Neo4j password is required. Provide it via KNOT_NEO4J_PASSWORD environment variable.")?;

        // Resolve repo_path: if not provided, use current directory and canonicalize
        let repo_path = if let Some(path) = cli.repo_path() {
            std::fs::canonicalize(&path)
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or(path)
        } else {
            std::env::current_dir()
                .context("Failed to determine current working directory for repo_path")?
                .to_string_lossy()
                .into_owned()
        };

        tracing::info!("Resolved repo_path: {repo_path}");

        // Auto-detect repo_name from the resolved canonical repo_path if not provided
        let repo_name = if let Some(name) = cli.repo_name() {
            name
        } else {
            std::path::Path::new(&repo_path)
                .file_name()
                .and_then(|n| n.to_str())
                .map(String::from)
                .unwrap_or_else(|| "unnamed-repo".to_string())
        };

        Ok(Self {
            repo_path,
            repo_name,
            qdrant_url: cli.qdrant_url,
            qdrant_collection: cli.qdrant_collection,
            neo4j_uri: cli.neo4j_uri,
            neo4j_user: cli.neo4j_user,
            neo4j_password,
            custom_queries_path: None,
            embed_dim: cli.embed_dim,
            batch_size: 0,
            clean: false,
            dependency_repos: Vec::new(),
            watch: false,
            dry_run: false,
            custom_ca_certs: cli.custom_ca_certs,
            output_format: OutputFormat::Table,
            ingest_concurrency: 4,
            rayon_threads: None,
            include_config_files: false,
        })
    }

    /// Common shared logic for loading environment and resolving repo_path/repo_name.
    /// Takes a closure that parses the CLI arguments.
    fn load_env_and_parse<T, F>(parse_cli: F) -> Result<(T, String, String, String)>
    where
        T: HasCommonFields,
        F: Fn() -> T,
    {
        load_knot_env();

        let cli = parse_cli();

        // Validate required fields that can come from CLI or Env.
        let neo4j_password = cli.neo4j_password()
            .or_else(|| std::env::var("KNOT_NEO4J_PASSWORD").ok())
            .context("Neo4j password is required. Provide it via --neo4j-password or KNOT_NEO4J_PASSWORD environment variable.")?;

        // Resolve repo_path: if not provided, use current directory and canonicalize
        let repo_path = if let Some(path) = cli.repo_path() {
            // If provided, canonicalize it to get an absolute path
            std::fs::canonicalize(&path)
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or(path)
        } else {
            // Fallback: use current working directory
            std::env::current_dir()
                .context("Failed to determine current working directory for repo_path")?
                .to_string_lossy()
                .into_owned()
        };

        tracing::info!("Resolved repo_path: {repo_path}");

        // Auto-detect repo_name from the resolved canonical repo_path if not provided
        let repo_name = if let Some(name) = cli.repo_name() {
            name
        } else {
            // Extract last component of the canonical repo_path as default
            std::path::Path::new(&repo_path)
                .file_name()
                .and_then(|n| n.to_str())
                .map(String::from)
                .unwrap_or_else(|| "unnamed-repo".to_string())
        };

        Ok((cli, repo_path, repo_name, neo4j_password))
    }
}

/// Trait to abstract common fields between IndexerCli and McpCli.
trait HasCommonFields {
    fn repo_path(&self) -> Option<String>;
    fn repo_name(&self) -> Option<String>;
    fn neo4j_password(&self) -> Option<String>;
}

impl HasCommonFields for IndexerCli {
    fn repo_path(&self) -> Option<String> {
        self.repo_path.clone()
    }

    fn repo_name(&self) -> Option<String> {
        self.repo_name.clone()
    }

    fn neo4j_password(&self) -> Option<String> {
        self.neo4j_password.clone()
    }
}

impl HasCommonFields for McpCli {
    fn repo_path(&self) -> Option<String> {
        self.repo_path.clone()
    }

    fn repo_name(&self) -> Option<String> {
        self.repo_name.clone()
    }

    fn neo4j_password(&self) -> Option<String> {
        self.neo4j_password.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use std::fs;
    use std::sync::Mutex;
    use tempfile::tempdir;

    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    #[test]
    fn test_repo_name_auto_detection() {
        // We use dummy CLI struct to test the logic
        let repo_path = "/path/to/my-project";
        let repo_name_opt: Option<String> = None;

        let repo_name = if let Some(name) = repo_name_opt {
            name
        } else {
            std::path::Path::new(repo_path)
                .file_name()
                .and_then(|n| n.to_str())
                .map(String::from)
                .unwrap_or_else(|| "unnamed-repo".to_string())
        };

        assert_eq!(repo_name, "my-project");
    }

    #[test]
    fn test_repo_name_provided() {
        let repo_path = "/path/to/my-project";
        let repo_name_opt: Option<String> = Some("custom-name".to_string());

        let repo_name = if let Some(name) = repo_name_opt {
            name
        } else {
            std::path::Path::new(repo_path)
                .file_name()
                .and_then(|n| n.to_str())
                .map(String::from)
                .unwrap_or_else(|| "unnamed-repo".to_string())
        };

        assert_eq!(repo_name, "custom-name");
    }

    #[test]
    fn test_indexer_cli_parsing_basic() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.repo_path, Some("/tmp/repo".to_string()));
        assert_eq!(cli.neo4j_password, Some("secret".to_string()));
        assert_eq!(cli.qdrant_url, "http://localhost:6334"); // default
    }

    #[test]
    fn test_indexer_cli_parsing_full() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--repo-name",
            "my-repo",
            "--qdrant-url",
            "http://qdrant:6334",
            "--qdrant-collection",
            "custom_collection",
            "--neo4j-uri",
            "bolt://neo4j:7687",
            "--neo4j-user",
            "admin",
            "--neo4j-password",
            "admin123",
            "--embed-dim",
            "768",
            "--batch-size",
            "128",
            "--clean",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.repo_path, Some("/tmp/repo".to_string()));
        assert_eq!(cli.repo_name, Some("my-repo".to_string()));
        assert_eq!(cli.qdrant_url, "http://qdrant:6334");
        assert_eq!(cli.qdrant_collection, "custom_collection");
        assert_eq!(cli.neo4j_uri, "bolt://neo4j:7687");
        assert_eq!(cli.neo4j_user, "admin");
        assert_eq!(cli.neo4j_password, Some("admin123".to_string()));
        assert_eq!(cli.embed_dim, 768);
        assert_eq!(cli.batch_size, 128);
        assert!(cli.clean);
    }

    #[test]
    fn test_parse_dependencies_single() {
        let deps_str = "core-lib";
        let dependency_repos: Vec<String> = deps_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        assert_eq!(dependency_repos.len(), 1);
        assert_eq!(dependency_repos[0], "core-lib");
    }

    #[test]
    fn test_parse_dependencies_multiple() {
        let deps_str = "core-lib,shared-types,utils";
        let dependency_repos: Vec<String> = deps_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        assert_eq!(dependency_repos.len(), 3);
        assert_eq!(dependency_repos[0], "core-lib");
        assert_eq!(dependency_repos[1], "shared-types");
        assert_eq!(dependency_repos[2], "utils");
    }

    #[test]
    fn test_parse_dependencies_with_whitespace() {
        let deps_str = "core-lib , shared-types , utils";
        let dependency_repos: Vec<String> = deps_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        assert_eq!(dependency_repos.len(), 3);
        assert_eq!(dependency_repos[0], "core-lib");
        assert_eq!(dependency_repos[1], "shared-types");
        assert_eq!(dependency_repos[2], "utils");
    }

    #[test]
    fn test_parse_dependencies_empty() {
        let deps_str = "";
        let dependency_repos: Vec<String> = deps_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        assert_eq!(dependency_repos.len(), 0);
    }

    #[test]
    fn test_parse_dependencies_with_trailing_comma() {
        let deps_str = "core-lib,shared-types,";
        let dependency_repos: Vec<String> = deps_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        assert_eq!(dependency_repos.len(), 2);
        assert_eq!(dependency_repos[0], "core-lib");
        assert_eq!(dependency_repos[1], "shared-types");
    }

    #[test]
    fn test_indexer_cli_with_watch() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
            "--watch",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert!(cli.watch);
    }

    #[test]
    fn test_indexer_cli_without_watch() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert!(!cli.watch);
    }

    #[test]
    fn test_indexer_cli_repo_path_optional() {
        let args = vec!["knot-indexer", "--neo4j-password", "secret"];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.repo_path, None);
        assert_eq!(cli.neo4j_password, Some("secret".to_string()));
    }

    #[test]
    fn test_mcp_cli_parsing_basic() {
        let args = vec![
            "knot-mcp",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = McpCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.repo_path, Some("/tmp/repo".to_string()));
        assert_eq!(cli.neo4j_password, Some("secret".to_string()));
        assert_eq!(cli.qdrant_url, "http://localhost:6334"); // default
        assert_eq!(cli.embed_dim, 384); // default
    }

    #[test]
    fn test_mcp_cli_repo_path_optional() {
        let args = vec!["knot-mcp", "--neo4j-password", "secret"];

        let cli = McpCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.repo_path, None);
        assert_eq!(cli.neo4j_password, Some("secret".to_string()));
    }

    #[test]
    fn test_mcp_cli_parsing_full() {
        let args = vec![
            "knot-mcp",
            "--repo-path",
            "/tmp/repo",
            "--repo-name",
            "my-repo",
            "--qdrant-url",
            "http://qdrant:6334",
            "--qdrant-collection",
            "custom_collection",
            "--neo4j-uri",
            "bolt://neo4j:7687",
            "--neo4j-user",
            "admin",
            "--neo4j-password",
            "admin123",
            "--embed-dim",
            "768",
        ];

        let cli = McpCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.repo_path, Some("/tmp/repo".to_string()));
        assert_eq!(cli.repo_name, Some("my-repo".to_string()));
        assert_eq!(cli.qdrant_url, "http://qdrant:6334");
        assert_eq!(cli.qdrant_collection, "custom_collection");
        assert_eq!(cli.neo4j_uri, "bolt://neo4j:7687");
        assert_eq!(cli.neo4j_user, "admin");
        assert_eq!(cli.neo4j_password, Some("admin123".to_string()));
        assert_eq!(cli.embed_dim, 768);
    }

    #[test]
    fn test_mcp_cli_no_indexer_specific_options() {
        // Verify that McpCli doesn't accept indexer-specific options
        let args = vec![
            "knot-mcp",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
            "--watch",
        ];

        // This should fail because --watch is not a valid option for knot-mcp
        assert!(McpCli::try_parse_from(args).is_err());
    }

    #[test]
    fn test_indexer_cli_accepts_all_options() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
            "--watch",
            "--clean",
            "--dependencies",
            "core-lib,shared-types",
            "--custom-queries-path",
            "/custom/queries",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.repo_path, Some("/tmp/repo".to_string()));
        assert!(cli.watch);
        assert!(cli.clean);
        assert_eq!(cli.dependencies, Some("core-lib,shared-types".to_string()));
        assert_eq!(cli.custom_queries_path, Some("/custom/queries".to_string()));
    }

    #[test]
    fn test_resolve_repo_path_with_dot() {
        // Test that passing "." gets canonicalized to an absolute path
        let repo_path_opt: Option<String> = Some(".".to_string());

        let repo_path = if let Some(path) = repo_path_opt {
            std::fs::canonicalize(&path)
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or(path)
        } else {
            std::env::current_dir()
                .unwrap()
                .to_string_lossy()
                .into_owned()
        };

        // Should be an absolute path, not "."
        assert!(!repo_path.contains("."));
        assert!(std::path::Path::new(&repo_path).is_absolute());
    }

    #[test]
    fn test_resolve_repo_path_fallback_current_dir() {
        // Test that when repo_path is None, it defaults to current directory
        let repo_path_opt: Option<String> = None;

        let repo_path = if let Some(path) = repo_path_opt {
            std::fs::canonicalize(&path)
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or(path)
        } else {
            std::env::current_dir()
                .unwrap()
                .to_string_lossy()
                .into_owned()
        };

        let expected = std::env::current_dir()
            .unwrap()
            .to_string_lossy()
            .into_owned();

        assert_eq!(repo_path, expected);
        assert!(std::path::Path::new(&repo_path).is_absolute());
    }

    #[test]
    fn test_repo_name_extraction_from_canonical_path() {
        // When repo_path is canonicalized, repo_name should extract correctly
        let current_dir = std::env::current_dir()
            .unwrap()
            .to_string_lossy()
            .into_owned();

        let repo_name = std::path::Path::new(&current_dir)
            .file_name()
            .and_then(|n| n.to_str())
            .map(String::from)
            .unwrap_or_else(|| "unnamed-repo".to_string());

        // Should get the actual directory name, not something empty or weird
        assert!(!repo_name.is_empty());
        assert!(
            repo_name != "unnamed-repo" || std::env::current_dir().unwrap().file_name().is_none()
        );
        assert!(!repo_name.contains("/"));
        assert!(!repo_name.contains("\\"));
    }

    #[test]
    fn test_repo_name_explicit_override() {
        // When --repo-name is provided, it should override auto-detection
        let repo_path = "/some/path/to/project";
        let repo_name_opt: Option<String> = Some("custom-repo-name".to_string());

        let repo_name = if let Some(name) = repo_name_opt {
            name
        } else {
            std::path::Path::new(repo_path)
                .file_name()
                .and_then(|n| n.to_str())
                .map(String::from)
                .unwrap_or_else(|| "unnamed-repo".to_string())
        };

        assert_eq!(repo_name, "custom-repo-name");
    }

    #[test]
    fn test_knot_cli_parsing_from_empty_args() {
        // Test that McpCli can parse from empty args (used by load_knot_cli)
        let args = vec!["knot"];
        let cli = McpCli::try_parse_from(args).expect("Failed to parse from empty args");

        // Should have valid configuration (values may be overridden by env vars)
        assert!(!cli.qdrant_url.is_empty());
        assert!(!cli.qdrant_collection.is_empty());
        assert!(!cli.neo4j_uri.is_empty());
        assert!(!cli.neo4j_user.is_empty());
        assert!(cli.embed_dim > 0);
    }

    #[test]
    fn test_knot_cli_no_subcommand_interference() {
        // Verify that McpCli parsing doesn't interfere with CLI subcommands
        // (knot uses separate Cli with subcommands: search, callers, explore)
        let args = vec!["knot"];
        let result = McpCli::try_parse_from(args);
        assert!(result.is_ok());
    }

    #[test]
    fn test_knot_cli_env_var_precedence() {
        // Test that environment variables can be read (simple test, doesn't modify env)
        // Just verify that parsing works and values are not empty
        let args = vec!["knot"];
        let cli = McpCli::try_parse_from(args).expect("Failed to parse");

        // Should have valid configuration
        assert!(!cli.qdrant_url.is_empty());
        assert_eq!(cli.neo4j_user, "neo4j"); // Default value
    }

    #[test]
    fn test_indexer_cli_with_custom_ca_certs() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
            "--custom-ca-certs",
            "/etc/ssl/certs/corporate-bundle.pem",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(
            cli.custom_ca_certs,
            Some("/etc/ssl/certs/corporate-bundle.pem".to_string())
        );
    }

    #[test]
    fn test_indexer_cli_without_custom_ca_certs() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.custom_ca_certs, None);
    }

    #[test]
    fn test_mcp_cli_with_custom_ca_certs() {
        let args = vec![
            "knot-mcp",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
            "--custom-ca-certs",
            "/etc/ssl/certs/my-certs.crt",
        ];

        let cli = McpCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(
            cli.custom_ca_certs,
            Some("/etc/ssl/certs/my-certs.crt".to_string())
        );
    }

    #[test]
    fn test_mcp_cli_without_custom_ca_certs() {
        let args = vec![
            "knot-mcp",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = McpCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.custom_ca_certs, None);
    }

    #[test]
    fn test_config_custom_ca_certs_propagation() {
        let config = Config {
            repo_path: "/tmp/repo".to_string(),
            repo_name: "test-repo".to_string(),
            qdrant_url: "http://localhost:6334".to_string(),
            qdrant_collection: "knot_entities".to_string(),
            neo4j_uri: "bolt://localhost:7687".to_string(),
            neo4j_user: "neo4j".to_string(),
            neo4j_password: "secret".to_string(),
            custom_queries_path: None,
            embed_dim: 384,
            batch_size: 64,
            clean: false,
            dependency_repos: Vec::new(),
            watch: false,
            dry_run: false,
            custom_ca_certs: Some("/etc/ssl/certs/corp.pem".to_string()),
            output_format: OutputFormat::Table,
            ingest_concurrency: 4,
            rayon_threads: None,
            include_config_files: false,
        };

        assert_eq!(
            config.custom_ca_certs,
            Some("/etc/ssl/certs/corp.pem".to_string())
        );
    }

    #[test]
    fn test_output_format_default_is_table() {
        assert_eq!(OutputFormat::default(), OutputFormat::Table);
    }

    #[test]
    fn test_output_format_all_variants() {
        let variants = [
            OutputFormat::Table,
            OutputFormat::Json,
            OutputFormat::Markdown,
        ];
        assert_eq!(variants.len(), 3);
        assert_ne!(OutputFormat::Table, OutputFormat::Json);
        assert_ne!(OutputFormat::Table, OutputFormat::Markdown);
        assert_ne!(OutputFormat::Json, OutputFormat::Markdown);
    }

    #[test]
    fn test_output_format_clone() {
        let fmt = OutputFormat::Json;
        let cloned = fmt.clone();
        assert_eq!(fmt, cloned);
    }

    #[test]
    fn test_output_format_debug() {
        let fmt = OutputFormat::Markdown;
        let debug_str = format!("{:?}", fmt);
        assert!(debug_str.contains("Markdown"));
    }

    #[test]
    fn test_ingest_concurrency_default() {
        let _guard = ENV_MUTEX.lock().unwrap();
        let prev = std::env::var("KNOT_INGEST_CONCURRENCY").ok();
        unsafe { std::env::remove_var("KNOT_INGEST_CONCURRENCY") };
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        // Default should be 4
        assert_eq!(cli.ingest_concurrency, 4);
        // Restore previous env var if it was set
        if let Some(val) = prev {
            unsafe { std::env::set_var("KNOT_INGEST_CONCURRENCY", val) };
        }
    }

    #[test]
    fn test_ingest_concurrency_explicit() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
            "--ingest-concurrency",
            "8",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.ingest_concurrency, 8);
    }

    #[test]
    fn test_ingest_concurrency_env_var() {
        // Test that the env var is mapped correctly (check the attribute)
        // Clap sets env = "KNOT_INGEST_CONCURRENCY" for this field
        let _guard = ENV_MUTEX.lock().unwrap();
        let prev = std::env::var("KNOT_INGEST_CONCURRENCY").ok();
        unsafe { std::env::set_var("KNOT_INGEST_CONCURRENCY", "16") };
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.ingest_concurrency, 16);
        // Restore previous env var value
        if let Some(val) = prev {
            unsafe { std::env::set_var("KNOT_INGEST_CONCURRENCY", val) };
        } else {
            unsafe { std::env::remove_var("KNOT_INGEST_CONCURRENCY") };
        }
    }

    #[test]
    fn test_ingest_concurrency_in_config() {
        let config = Config {
            repo_path: "/tmp/repo".to_string(),
            repo_name: "test-repo".to_string(),
            qdrant_url: "http://localhost:6334".to_string(),
            qdrant_collection: "knot_entities".to_string(),
            neo4j_uri: "bolt://localhost:7687".to_string(),
            neo4j_user: "neo4j".to_string(),
            neo4j_password: "secret".to_string(),
            custom_queries_path: None,
            embed_dim: 384,
            batch_size: 64,
            clean: false,
            dependency_repos: Vec::new(),
            watch: false,
            dry_run: false,
            custom_ca_certs: None,
            output_format: OutputFormat::Table,
            ingest_concurrency: 8,
            rayon_threads: None,
            include_config_files: false,
        };

        assert_eq!(config.ingest_concurrency, 8);
    }

    #[test]
    fn test_rayon_threads_default() {
        let _guard = ENV_MUTEX.lock().unwrap();
        let prev = std::env::var("KNOT_RAYON_THREADS").ok();
        unsafe { std::env::remove_var("KNOT_RAYON_THREADS") };
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.rayon_threads, None);
        // Restore previous env var if it was set
        if let Some(val) = prev {
            unsafe { std::env::set_var("KNOT_RAYON_THREADS", val) };
        }
    }

    #[test]
    fn test_rayon_threads_explicit() {
        let args = vec![
            "knot-indexer",
            "--repo-path",
            "/tmp/repo",
            "--neo4j-password",
            "secret",
            "--rayon-threads",
            "8",
        ];

        let cli = IndexerCli::try_parse_from(args).expect("Failed to parse CLI args");
        assert_eq!(cli.rayon_threads, Some(8));
    }

    #[test]
    fn test_rayon_threads_in_config() {
        let config = Config {
            repo_path: "/tmp/repo".to_string(),
            repo_name: "test-repo".to_string(),
            qdrant_url: "http://localhost:6334".to_string(),
            qdrant_collection: "knot_entities".to_string(),
            neo4j_uri: "bolt://localhost:7687".to_string(),
            neo4j_user: "neo4j".to_string(),
            neo4j_password: "secret".to_string(),
            custom_queries_path: None,
            embed_dim: 384,
            batch_size: 64,
            clean: false,
            dependency_repos: Vec::new(),
            watch: false,
            dry_run: false,
            custom_ca_certs: None,
            output_format: OutputFormat::Table,
            ingest_concurrency: 4,
            rayon_threads: Some(6),
            include_config_files: false,
        };

        assert_eq!(config.rayon_threads, Some(6));
    }

    #[test]
    fn test_rayon_threads_none() {
        let config = Config {
            repo_path: "/tmp/repo".to_string(),
            repo_name: "test-repo".to_string(),
            qdrant_url: "http://localhost:6334".to_string(),
            qdrant_collection: "knot_entities".to_string(),
            neo4j_uri: "bolt://localhost:7687".to_string(),
            neo4j_user: "neo4j".to_string(),
            neo4j_password: "secret".to_string(),
            custom_queries_path: None,
            embed_dim: 384,
            batch_size: 64,
            clean: false,
            dependency_repos: Vec::new(),
            watch: false,
            dry_run: false,
            custom_ca_certs: None,
            output_format: OutputFormat::Table,
            ingest_concurrency: 4,
            rayon_threads: None,
            include_config_files: false,
        };

        assert_eq!(config.rayon_threads, None);
    }

    #[test]
    fn test_knot_env_path_prefers_knot_config_dir() {
        unsafe { std::env::set_var("KNOT_CONFIG_DIR", "/custom/knot/config") };
        let path = knot_env_path();
        unsafe { std::env::remove_var("KNOT_CONFIG_DIR") };

        assert_eq!(
            path,
            Some(std::path::PathBuf::from("/custom/knot/config/.env"))
        );
    }

    #[test]
    fn test_knot_env_path_falls_back_to_home() {
        // Remove KNOT_CONFIG_DIR to test HOME fallback
        let had_config_dir = std::env::var("KNOT_CONFIG_DIR").ok();
        unsafe { std::env::remove_var("KNOT_CONFIG_DIR") };

        let home = std::env::var("HOME").ok();
        let path = knot_env_path();

        // Restore KNOT_CONFIG_DIR if it was set
        if let Some(v) = had_config_dir {
            unsafe { std::env::set_var("KNOT_CONFIG_DIR", v) };
        }

        match home {
            Some(h) => {
                assert_eq!(
                    path,
                    Some(std::path::PathBuf::from(format!("{h}/.config/knot/.env")))
                );
            }
            None => {
                // On Windows with no HOME, may fall through to USERPROFILE
                // or return None
            }
        }
    }

    #[test]
    fn test_knot_env_path_never_resolves_to_cwd() {
        // knot_env_path must not use std::env::current_dir() or dotenvy::dotenv()
        // Verify by checking that a .env file in CWD does NOT affect the resolved path.
        let temp = tempdir().unwrap();
        let env_file = temp.path().join(".env");
        fs::write(&env_file, "KNOT_REPO_PATH=/from/cwd\n").unwrap();

        // knot_env_path should resolve from $HOME or $KNOT_CONFIG_DIR, never CWD
        let path = knot_env_path();
        assert!(
            path.as_ref().is_none_or(|p| p != &env_file),
            "knot_env_path must not resolve to a .env in the current (temp) directory"
        );
    }

    #[test]
    fn test_load_knot_env_reads_from_explicit_path() {
        let temp = tempdir().unwrap();
        let env_file = temp.path().join(".env");
        fs::write(&env_file, "KNOT_REPO_PATH=/from/explicit/path\n").unwrap();

        // dotenvy::from_path should load from the specified path
        let result = dotenvy::from_path(&env_file);
        assert!(result.is_ok(), "Should load .env from explicit path");
        assert_eq!(
            std::env::var("KNOT_REPO_PATH").unwrap(),
            "/from/explicit/path"
        );

        // Cleanup
        unsafe { std::env::remove_var("KNOT_REPO_PATH") };
    }
}