jarvy 0.4.0

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

use crate::roles::definition::{RoleAssignment, RolesConfig};
use crate::team::Extends;
use crate::telemetry;
use crate::tools::{Os, current_os};

/// Default timeout for hooks in seconds (5 minutes)
pub const DEFAULT_HOOK_TIMEOUT: u64 = 300;

// ============================================================================
// Environment Variable Configuration
// ============================================================================

/// Environment variable value - can be simple string or complex with options
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum EnvValue {
    /// Complex value with additional options
    Complex {
        /// The value of the environment variable (supports template expansion)
        value: String,
        /// Description for documentation
        #[serde(default)]
        description: Option<String>,
        /// Whether to append to existing PATH-like variables
        #[serde(default)]
        append: bool,
        /// Whether this is per-tool (prefixed with tool name context)
        #[serde(default)]
        per_tool: bool,
    },
    /// Simple string value (supports template expansion)
    Simple(String),
}

impl EnvValue {
    /// Get the raw value string
    pub fn value(&self) -> &str {
        match self {
            EnvValue::Complex { value, .. } => value,
            EnvValue::Simple(s) => s,
        }
    }

    /// Check if this should append to existing values
    #[allow(dead_code)] // Public API for env value manipulation
    pub fn should_append(&self) -> bool {
        match self {
            EnvValue::Complex { append, .. } => *append,
            EnvValue::Simple(_) => false,
        }
    }
}

/// Secret variable configuration
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum SecretValue {
    /// Load secret from a file
    FromFile {
        /// Path to file containing the secret
        from_file: String,
    },
    /// Prompt for secret (with optional default env var to check)
    Prompt {
        /// Environment variable to check before prompting
        #[serde(default)]
        env: Option<String>,
        /// Whether this secret is required
        #[serde(default = "default_true")]
        required: bool,
        /// Description shown when prompting
        #[serde(default)]
        description: Option<String>,
    },
    /// Simple prompt marker (just the variable name)
    Simple(String),
}

fn default_true() -> bool {
    true
}

/// Settings for environment variable generation
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct EnvSettings {
    /// Target shell for rc file updates (bash, zsh, fish)
    #[serde(default)]
    pub shell: Option<String>,
    /// Whether to update shell rc files
    #[serde(default)]
    pub update_rc: bool,
    /// Whether to generate .env file
    #[serde(default = "default_true")]
    pub generate_dotenv: bool,
    /// Path for .env file (default: ./.env)
    #[serde(default = "default_dotenv_path")]
    pub dotenv_path: PathBuf,
    /// Whether to add .env to .gitignore
    #[serde(default)]
    pub add_to_gitignore: bool,
    /// Backup rc files before modification
    #[serde(default = "default_true")]
    pub backup_rc: bool,
}

fn default_dotenv_path() -> PathBuf {
    PathBuf::from(".env")
}

impl Default for EnvSettings {
    fn default() -> Self {
        Self {
            shell: None,
            update_rc: false,
            generate_dotenv: true,
            dotenv_path: default_dotenv_path(),
            add_to_gitignore: false,
            backup_rc: true,
        }
    }
}

/// Environment configuration section in jarvy.toml
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct EnvConfig {
    /// Regular environment variables
    #[serde(default)]
    pub vars: HashMap<String, EnvValue>,
    /// Secret variables (prompted or loaded from file)
    #[serde(default)]
    pub secrets: HashMap<String, SecretValue>,
    /// Settings for env generation
    #[serde(default)]
    pub config: EnvSettings,
    /// Per-tool environment variables
    #[serde(flatten)]
    pub tool_env: HashMap<String, ToolEnvConfig>,
}

/// Per-tool environment variables
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct ToolEnvConfig {
    /// Environment variables specific to this tool
    #[serde(default)]
    pub vars: HashMap<String, EnvValue>,
}

/// Configuration for a single hook
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct ToolHooks {
    /// Script to run after this tool is installed
    #[serde(default)]
    pub post_install: Option<String>,
}

/// Settings for hook execution
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct HookSettings {
    /// Shell to use for running hooks (bash, zsh, sh, powershell)
    #[serde(default = "default_shell")]
    pub shell: String,
    /// Timeout in seconds for each hook (default: 300 = 5 minutes)
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// Whether to continue setup if a hook fails
    #[serde(default)]
    pub continue_on_error: bool,
}

fn default_shell() -> String {
    #[cfg(windows)]
    {
        "powershell".to_string()
    }
    #[cfg(not(windows))]
    {
        std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string())
    }
}

fn default_timeout() -> u64 {
    DEFAULT_HOOK_TIMEOUT
}

impl Default for HookSettings {
    fn default() -> Self {
        Self {
            shell: default_shell(),
            timeout: DEFAULT_HOOK_TIMEOUT,
            continue_on_error: false,
        }
    }
}

// ============================================================================
// Services Configuration
// ============================================================================

/// Services configuration section in jarvy.toml
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct ServicesConfig {
    /// Whether services feature is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Whether to auto-start services during jarvy setup
    #[serde(default)]
    pub auto_start: bool,
    /// Override path to docker-compose.yml (relative to project root)
    #[serde(default)]
    pub compose_file: Option<PathBuf>,
    /// Override path to Tiltfile (relative to project root)
    #[serde(default)]
    pub tilt_file: Option<PathBuf>,
    /// Whether to auto-start services in CI mode (default: false)
    #[serde(default)]
    pub start_in_ci: bool,
}

impl ServicesConfig {
    /// Returns true if services should be started during setup
    pub fn should_auto_start(&self, is_ci: bool) -> bool {
        if !self.enabled {
            return false;
        }
        if is_ci && !self.start_in_ci {
            return false;
        }
        self.auto_start
    }
}

// ============================================================================
// Hooks Configuration
// ============================================================================

#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct HooksConfig {
    /// Script to run before any tool installation
    #[serde(default)]
    pub pre_setup: Option<String>,
    /// Script to run after all tools are installed
    #[serde(default)]
    pub post_setup: Option<String>,
    /// Hook settings (shell, timeout, etc.)
    #[serde(default)]
    pub config: HookSettings,
    /// Per-tool hooks, keyed by tool name
    #[serde(flatten)]
    pub tool_hooks: HashMap<String, ToolHooks>,
}

#[derive(Deserialize)]
pub struct Config {
    /// Parent configs to extend (URL or local path)
    #[serde(default)]
    #[allow(dead_code)] // Used during config inheritance resolution
    pub extends: Option<Extends>,
    /// Role assignment for this config (single or multiple roles)
    /// Use `role = "name"` for single role or `role = ["a", "b"]` for multiple
    #[serde(default)]
    pub role: Option<RoleAssignment>,
    #[serde(rename = "provisioner")]
    tools: HashMap<String, ToolConfig>,
    #[serde(default)]
    privileges: Option<PrivilegeConfig>,
    /// Hooks configuration section
    #[serde(default)]
    pub hooks: HooksConfig,
    /// Environment variables configuration
    #[serde(default)]
    pub env: EnvConfig,
    /// Services configuration (docker-compose, tilt)
    #[serde(default)]
    pub services: ServicesConfig,
    /// Role definitions section
    #[serde(default, rename = "roles")]
    pub roles_config: RolesConfig,
    /// Network/proxy configuration
    #[serde(default)]
    #[allow(dead_code)] // Used for proxy configuration in corporate environments
    pub network: crate::network::NetworkConfig,
    /// npm package configuration
    #[serde(default)]
    pub npm: Option<crate::packages::NpmConfig>,
    /// pip package configuration
    #[serde(default)]
    pub pip: Option<crate::packages::PipConfig>,
    /// cargo binary configuration
    #[serde(default)]
    pub cargo: Option<crate::packages::CargoConfig>,
    /// .NET global tool configuration (`[nuget]`)
    #[serde(default)]
    pub nuget: Option<crate::packages::NugetConfig>,
    /// Ruby gem configuration (`[gem]`)
    #[serde(default)]
    pub gem: Option<crate::packages::GemConfig>,
    /// Go binary configuration (`[go]`)
    #[serde(default)]
    pub go: Option<crate::packages::GoConfig>,
    /// Git configuration
    #[serde(default)]
    pub git: Option<crate::git::GitConfig>,
    /// Git hook framework integration (`[git_hooks]`)
    #[serde(default, rename = "git_hooks")]
    pub git_hooks: Option<crate::git_hooks::GitHooksConfig>,
    /// AI agent skill installation (`[skills]` — PRD-049 + PRD-054)
    #[serde(default)]
    pub skills: Option<crate::skills::SkillsConfig>,
    /// Drift detection configuration
    #[serde(default)]
    pub drift: Option<crate::drift::DriftConfig>,
    /// Telemetry/OTEL configuration (project-level override for security audit)
    #[serde(default)]
    pub telemetry: Option<crate::telemetry::TelemetryConfig>,
    /// Custom project commands for interactive menu
    #[serde(default)]
    #[allow(dead_code)] // Read by interactive module via direct TOML parsing
    pub commands: CommandsConfig,
    /// Workspace configuration for monorepo support
    #[serde(default)]
    #[allow(dead_code)] // Used by workspace module for config inheritance
    pub workspace: Option<crate::workspace::WorkspaceConfig>,
    /// AI agent hook provisioning (`[ai_hooks]` section). Distributes
    /// guardrails like `block-rm-rf` or `block-edit-env-files` across
    /// Claude Code, Cursor, Codex, Windsurf, Cline, and Continue from a
    /// single config block.
    #[serde(default, rename = "ai_hooks")]
    pub ai_hooks: Option<crate::ai_hooks::AiHooksConfig>,
    /// MCP server registration (`[mcp_register]` section). Registers the
    /// built-in Jarvy MCP server (and optional custom servers) with
    /// each developer's AI agents so they can discover Jarvy's tools
    /// without manual setup. Same trust boundary as `[ai_hooks]`.
    #[serde(default, rename = "mcp_register")]
    pub mcp_register: Option<crate::mcp_register::McpRegisterConfig>,
    /// `[discover]` block — custom detection rules and ignore_dirs for
    /// `jarvy discover` (PRD-044 phase 2). Built-in rules always run;
    /// the custom rules file is APPENDED so a user tree can't silence
    /// built-in detection. Consumed by `discover::commands` via direct
    /// TOML parse (not through this struct) because discover is the
    /// only reader and the indirection isn't worth the dep on Config.
    #[allow(dead_code)]
    #[serde(default)]
    pub discover: Option<crate::discover::config::DiscoverConfig>,
    /// Top-level `[packages]` trust knob. Mirrors `[ai_hooks]
    /// allow_custom_commands` and `[mcp_register] allow_custom_servers`
    /// for the package ecosystems. When `Config` is tagged
    /// `ConfigOrigin::Remote` (loaded via `jarvy setup --from <url>`),
    /// the package handlers refuse every `[npm]/[pip]/[cargo]/[nuget]`
    /// entry unless this flag is explicitly set true. Defaults to
    /// false — a remote config CANNOT broaden trust on its own.
    #[serde(default)]
    pub packages: PackagesTrustConfig,
    /// Where this `Config` came from. Populated by `mark_remote()`
    /// when the user supplies `--from <url>`. Drives the trust gate
    /// for `[packages] allow_remote` and (legacy)
    /// `mark_ai_hooks_remote`. Not serialized; `#[serde(skip)]`.
    #[serde(skip)]
    pub origin: crate::ai_hooks::ConfigOrigin,
}

/// Top-level `[packages]` block. Currently only carries the
/// `allow_remote` opt-in trust knob; package-manager-specific config
/// lives in `[npm]/[pip]/[cargo]/[nuget]` per the existing taxonomy.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct PackagesTrustConfig {
    /// When true, allow `[npm]/[pip]/[cargo]/[nuget]` entries to flow
    /// through from a remote-fetched config (`jarvy setup --from
    /// <url>`). Defaults to false so a hostile / unvetted remote
    /// config cannot install arbitrary global tools on the operator's
    /// machine. Local configs ignore this flag — they're already
    /// under the user's control.
    #[serde(default)]
    pub allow_remote: bool,
}

/// Canonical list of top-level section names that `jarvy.toml` may use.
///
/// This is the single source of truth for `jarvy validate`'s
/// known-section check. Adding a new top-level section to `Config`
/// without updating this list — or vice versa — will be rejected by
/// the compile-time destructure test in `Config::tests`. That test
/// is what stops the "validator warns about a section the parser
/// silently accepts" class of bug.
///
/// `logging` is included here even though it is not (yet) a field on
/// `Config` — it is parsed by `src/observability/logging.rs` and is
/// documented as a valid jarvy.toml section.
pub const TOP_LEVEL_SECTIONS: &[&str] = &[
    "extends",
    "role",
    "provisioner",
    "privileges",
    "hooks",
    "env",
    "services",
    "roles",
    "network",
    "npm",
    "pip",
    "cargo",
    "nuget",
    "gem",
    "go",
    "packages",
    "git",
    "git_hooks",
    "skills",
    "drift",
    "telemetry",
    "commands",
    "workspace",
    "ai_hooks",
    "mcp_register",
    "discover",
    // Parsed by src/observability/logging.rs, not Config — kept here so
    // jarvy validate accepts it without warning.
    "logging",
];

/// Custom project commands that override the interactive menu defaults.
///
/// # Example
/// ```toml
/// [commands]
/// run = "npm start"
/// test = "npm test"
/// setup = "jarvy setup"
/// ```
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct CommandsConfig {
    /// Command to run the project (default: "cargo run")
    #[serde(default)]
    pub run: Option<String>,
    /// Command to test the project (default: "cargo test")
    #[serde(default)]
    pub test: Option<String>,
    /// Command to set up the dev environment (default: "jarvy setup")
    #[serde(default)]
    pub setup: Option<String>,
    /// Any additional commands not in the three well-known slots
    /// (e.g. `format`, `migrate`, `publish`, `scaffold`). Captured here
    /// so the parser doesn't drop them silently — they surface in the
    /// interactive menu as "Run <name>" entries.
    #[serde(flatten)]
    pub extras: HashMap<String, String>,
}

#[derive(Deserialize, Debug, Default)]
pub struct PrivilegeConfig {
    // Global default; if None, a sensible per-OS default is used
    #[serde(default)]
    pub use_sudo: Option<bool>,
    // Per-OS overrides, e.g., { linux = true, macos = false }
    #[serde(default)]
    pub per_os: HashMap<Os, bool>,
}

impl PrivilegeConfig {
    // Sensible defaults if nothing specified
    fn default_for(_os: Os) -> Option<bool> {
        // Returning None indicates: auto-detect per operation
        None
    }

    pub fn effective_for(&self, os: Os) -> Option<bool> {
        if let Some(v) = self.per_os.get(&os) {
            Some(*v)
        } else if let Some(global) = self.use_sudo {
            Some(global)
        } else {
            Self::default_for(os)
        }
    }
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(untagged)]
pub enum ToolConfig {
    Detailed {
        version: String,
        version_manager: Option<bool>,
        use_sudo: Option<bool>,
    },
    Simple(String),
}

/// Build a Tool from config, returning (key, tool) with minimal cloning.
/// This helper consolidates tool construction logic and reduces redundant clones.
fn build_tool_entry(name: &str, config: &ToolConfig) -> (String, Tool) {
    let name_owned = name.to_string();
    let (version, version_manager, use_sudo) = match config {
        ToolConfig::Detailed {
            version,
            version_manager,
            use_sudo,
        } => (version.clone(), version_manager.unwrap_or(true), *use_sudo),
        ToolConfig::Simple(version) => (version.clone(), true, None),
    };

    let tool = Tool {
        name: name_owned.clone(),
        version,
        version_manager,
        use_sudo,
    };

    (name_owned, tool)
}

impl Config {
    /// Construct a Config from raw TOML text. Public for tests so that
    /// callers don't have to write to disk to construct a fixture.
    /// Production code should go through `Config::new(path)`.
    #[doc(hidden)]
    #[allow(dead_code)] // Test-only seam
    pub fn from_toml_str(toml_text: &str) -> Result<Self, toml::de::Error> {
        toml::from_str::<Config>(toml_text)
    }

    /// Tag the config as remote-origin. Called by `setup --from <url>`
    /// after loading the cached config so the runtime can refuse
    /// privileged operations (raw `command = "..."` entries on AI
    /// hooks, custom MCP servers, AND now `[npm]/[pip]/[cargo]/
    /// [nuget]` entries unless `[packages] allow_remote = true`) from
    /// untrusted sources. Remote configs can NARROW trust but cannot
    /// BROADEN it — `allow_remote` is the only opt-in switch and it
    /// must be set explicitly.
    pub fn mark_remote(&mut self) {
        self.origin = crate::ai_hooks::ConfigOrigin::Remote;
        if let Some(ref mut cfg) = self.ai_hooks {
            cfg.origin = crate::ai_hooks::ConfigOrigin::Remote;
        }
        if let Some(ref mut cfg) = self.mcp_register {
            cfg.origin = crate::ai_hooks::ConfigOrigin::Remote;
        }
        // Review item 4 (P0) — PRD-054 trust gate for `[skills]
        // library_sources` was wired in skills_cmd.rs but its origin
        // tag was never propagated. A remote `jarvy setup --from <url>`
        // config could ship `[[skills.library_sources]]` and bypass
        // the gate entirely. Same fix shape as ai_hooks / mcp_register.
        if let Some(ref mut cfg) = self.skills {
            cfg.origin = crate::ai_hooks::ConfigOrigin::Remote;
        }
        // Review item 5 (P0) — `[git_hooks]` declared `allow_remote`
        // as a documented trust gate but no `origin` field existed on
        // `GitHooksConfig` to compare against. Field added in the
        // companion git_hooks/config.rs edit; this propagates it.
        if let Some(ref mut cfg) = self.git_hooks {
            cfg.origin = crate::ai_hooks::ConfigOrigin::Remote;
        }
    }

    pub fn new(config_path: &str) -> Self {
        let config_content = match fs::read_to_string(config_path) {
            Ok(content) => content,
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to read config file at: {}", config_path);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        };

        match toml::from_str::<Config>(&config_content) {
            Ok(config) => {
                // Emit telemetry on successful load
                telemetry::config_loaded(
                    config_path,
                    config.tools.len(),
                    config.has_hooks(),
                    config.has_env(),
                    config.services.enabled,
                );
                config
            }
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to parse config file: {}", e);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        }
    }

    /// Load the config at `config_path`, walking up to find a workspace root and
    /// merging inherited sections from the root config when present.
    ///
    /// When the current directory is inside a workspace member, sections listed
    /// in the root's `[workspace] inherit = [...]` are merged in (member wins
    /// on conflict; for `provisioner`, individual tools merge tool-by-tool).
    ///
    /// Falls back to plain `Config::new(config_path)` semantics when no
    /// workspace root is discovered.
    pub fn new_with_workspace(config_path: &str) -> Self {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let Some(ctx) = crate::workspace::find_workspace_root(&cwd) else {
            return Self::new(config_path);
        };

        // If the active config_path IS the root config, plain load is fine.
        let abs_config_path =
            std::fs::canonicalize(config_path).unwrap_or_else(|_| PathBuf::from(config_path));
        let abs_root =
            std::fs::canonicalize(&ctx.root_config).unwrap_or_else(|_| ctx.root_config.clone());
        if abs_config_path == abs_root {
            return Self::new(config_path);
        }

        // We are in a member. Read root + member as toml::Value, merge, then
        // deserialize. This avoids re-implementing every Config field merge.
        let root_text = match fs::read_to_string(&ctx.root_config) {
            Ok(s) => s,
            Err(e) => {
                tracing::warn!(
                    event = "workspace.root_read_failed",
                    path = %ctx.root_config.display(),
                    error = %e,
                );
                return Self::new(config_path);
            }
        };
        let member_text = match fs::read_to_string(config_path) {
            Ok(s) => s,
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to read config file at: {}", config_path);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        };

        let root_value = match toml::from_str::<toml::Value>(&root_text) {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(
                    event = "workspace.root_parse_failed",
                    path = %ctx.root_config.display(),
                    error = %e,
                );
                return Self::new(config_path);
            }
        };
        let member_value = match toml::from_str::<toml::Value>(&member_text) {
            Ok(v) => v,
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to parse config file: {}", e);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        };

        let effective_inherit = ctx.workspace.effective_inherit();
        let merged =
            crate::workspace::merge_configs(&root_value, &member_value, &effective_inherit);

        match merged.try_into::<Config>() {
            Ok(config) => {
                tracing::info!(
                    event = "workspace.config_merged",
                    member = ctx.current_member.as_deref().unwrap_or(""),
                    inherit_count = effective_inherit.len(),
                );
                telemetry::config_loaded(
                    config_path,
                    config.tools.len(),
                    config.has_hooks(),
                    config.has_env(),
                    config.services.enabled,
                );
                config
            }
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to parse merged workspace config: {}", e);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        }
    }

    /// Count of tools configured under `[provisioner]`. Used by the MCP
    /// `jarvy_validate_config` tool to surface a quick health-check
    /// number without serializing the whole tool table.
    pub fn tool_configs_len(&self) -> usize {
        self.tools.len()
    }

    pub fn get_tool_configs(&self) -> HashMap<String, Tool> {
        self.tools
            .iter()
            .map(|(name, config)| build_tool_entry(name, config))
            .collect()
    }

    // Returns whether sudo should be used on the current OS; None => auto-detect per op
    pub fn use_sudo(&self) -> Option<bool> {
        let os = current_os();
        self.privileges
            .as_ref()
            .map(|p| p.effective_for(os))
            .unwrap_or_else(|| PrivilegeConfig::default_for(os))
    }

    /// Get the hooks configuration
    pub fn get_hooks(&self) -> &HooksConfig {
        &self.hooks
    }

    /// Get hooks for a specific tool
    pub fn get_tool_hooks(&self, tool_name: &str) -> Option<&ToolHooks> {
        self.hooks.tool_hooks.get(tool_name)
    }

    /// Check if any hooks are configured
    pub fn has_hooks(&self) -> bool {
        self.hooks.pre_setup.is_some()
            || self.hooks.post_setup.is_some()
            || self
                .hooks
                .tool_hooks
                .values()
                .any(|h| h.post_install.is_some())
    }

    /// Get the environment configuration
    pub fn get_env(&self) -> &EnvConfig {
        &self.env
    }

    /// Get environment variables for a specific tool
    #[allow(dead_code)] // Public API for tool-specific environment access
    pub fn get_tool_env(&self, tool_name: &str) -> Option<&ToolEnvConfig> {
        self.env.tool_env.get(tool_name)
    }

    /// Check if any environment variables are configured
    pub fn has_env(&self) -> bool {
        !self.env.vars.is_empty()
            || !self.env.secrets.is_empty()
            || self.env.tool_env.values().any(|t| !t.vars.is_empty())
    }

    /// Get the roles configuration
    pub fn get_roles_config(&self) -> &RolesConfig {
        &self.roles_config
    }

    /// Check if any roles are defined
    pub fn has_roles(&self) -> bool {
        !self.roles_config.roles.is_empty()
    }

    /// Get assigned role(s) if any
    pub fn get_assigned_roles(&self) -> Option<Vec<&str>> {
        self.role.as_ref().map(|r| r.as_vec())
    }

    /// Check if a role is assigned
    #[allow(dead_code)] // Public API for role configuration access
    pub fn has_assigned_role(&self) -> bool {
        self.role.as_ref().map(|r| !r.is_empty()).unwrap_or(false)
    }

    /// Borrowed view of the npm/pip/cargo/nuget sections. Zero-clone:
    /// constructing this is just collecting four references. Use this
    /// from `run_packages_phase` and `install_packages`. The owned
    /// variant `get_packages_config` is retained for the small number
    /// of call sites that genuinely need ownership.
    pub fn packages_ref(&self) -> crate::packages::PackagesConfigRef<'_> {
        crate::packages::PackagesConfigRef {
            npm: self.npm.as_ref(),
            pip: self.pip.as_ref(),
            cargo: self.cargo.as_ref(),
            nuget: self.nuget.as_ref(),
            gem: self.gem.as_ref(),
            go: self.go.as_ref(),
            origin: self.origin,
            allow_remote_packages: self.packages.allow_remote,
        }
    }

    /// Check if any packages are configured
    pub fn has_packages(&self) -> bool {
        self.npm.is_some()
            || self.pip.is_some()
            || self.cargo.is_some()
            || self.nuget.is_some()
            || self.gem.is_some()
            || self.go.is_some()
    }

    /// Get the git configuration
    pub fn get_git(&self) -> Option<&crate::git::GitConfig> {
        self.git.as_ref()
    }

    /// Check if git configuration is present
    pub fn has_git(&self) -> bool {
        self.git.is_some()
    }

    /// Get tool configs with roles applied
    /// This merges role tools with directly configured tools
    /// Direct tools override role tools
    #[allow(dead_code)] // Public API for role-based tool configuration
    pub fn get_tool_configs_with_roles(&self) -> HashMap<String, Tool> {
        use crate::roles::resolver::RoleResolver;

        let mut result = HashMap::new();

        // If roles are assigned, resolve and add those tools first
        if let Some(role_assignment) = &self.role {
            let role_names = role_assignment.as_vec();
            if !role_names.is_empty() && self.has_roles() {
                let mut resolver = RoleResolver::new(&self.roles_config);
                if let Ok(resolved) = resolver.resolve_multiple(&role_names) {
                    for (name, tool) in resolved.tools {
                        result.insert(
                            name.clone(),
                            Tool {
                                name,
                                version: tool.version,
                                version_manager: tool.version_manager,
                                use_sudo: tool.use_sudo,
                            },
                        );
                    }
                }
            }
        }

        // Direct tools override role tools - use helper for minimal cloning
        for (name, config) in &self.tools {
            let (key, tool) = build_tool_entry(name, config);
            result.insert(key, tool);
        }

        result
    }

    /// Get tool configs with an optional CLI role override
    /// If role_override is Some, it temporarily replaces the config's role assignment
    /// This is used by the --role flag in the setup command
    pub fn get_tool_configs_with_role_override(
        &self,
        role_override: Option<&str>,
    ) -> HashMap<String, Tool> {
        use crate::roles::resolver::RoleResolver;

        let mut result = HashMap::new();

        // Determine which role(s) to use: CLI override takes precedence
        // Avoid cloning self.role by computing role_names directly
        let role_names: Vec<&str> = match (role_override, &self.role) {
            (Some(name), _) => vec![name],
            (None, Some(assignment)) => assignment.as_vec(),
            (None, None) => vec![],
        };

        // If roles are assigned, resolve and add those tools first
        if !role_names.is_empty() && self.has_roles() {
            let mut resolver = RoleResolver::new(&self.roles_config);
            if let Ok(resolved) = resolver.resolve_multiple(&role_names) {
                for (name, tool) in resolved.tools {
                    // Move name into Tool.name, only clone for HashMap key
                    result.insert(
                        name.clone(),
                        Tool {
                            name,
                            version: tool.version,
                            version_manager: tool.version_manager,
                            use_sudo: tool.use_sudo,
                        },
                    );
                }
            }
        }

        // Direct tools override role tools - use helper for minimal cloning
        for (name, config) in &self.tools {
            let (key, tool) = build_tool_entry(name, config);
            result.insert(key, tool);
        }

        result
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Tool {
    pub name: String,
    pub version: String,
    pub version_manager: bool,
    pub use_sudo: Option<bool>, // carry per-tool override
}

pub fn create_default_config() {
    let default_config = r#"
[privileges]
use_sudo = true

[privileges.per_os]
linux = true
macos = false
windows = false

[provisioner]
git = "latest"
docker = "latest"

# Hook configuration (optional)
# [hooks]
# pre_setup = "echo 'Starting Jarvy setup...'"
# post_setup = "echo 'Setup complete!'"
#
# [hooks.config]
# shell = "zsh"           # or "bash", "sh", "powershell"
# timeout = 300           # seconds (default: 5 minutes)
# continue_on_error = false
#
# [hooks.node]
# post_install = "npm install -g yarn"

# Environment variables (optional)
# [env.vars]
# MY_VAR = "simple_value"
# PROJECT_ROOT = "$PWD"
# NODE_PATH = { value = "$HOME/.node/bin", append = true }
#
# [env.secrets]
# API_KEY = { env = "MY_API_KEY", required = true }
# DB_PASSWORD = { from_file = "~/.secrets/db_pass" }
#
# [env.config]
# generate_dotenv = true
# dotenv_path = ".env"
# update_rc = false
# add_to_gitignore = true
"#;
    let mut file = match File::create("jarvy.toml") {
        Ok(f) => f,
        Err(e) => {
            eprintln!("Could not create jarvy.toml: {e}");
            return;
        }
    };
    if let Err(e) = file.write_all(default_config.as_bytes()) {
        eprintln!("Could not write to jarvy.toml: {e}");
        return;
    }
    println!("Created jarvy.toml with default configuration");
}

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

    /// Regression guard against drift between `Config` and
    /// `TOP_LEVEL_SECTIONS`. If a new top-level field is added to
    /// `Config` without also updating `TOP_LEVEL_SECTIONS`, this test
    /// fails to compile because the destructure pattern is missing the
    /// new binding. That breakage points the developer at both the
    /// const and `jarvy validate`'s allowlist in one step.
    ///
    /// If a field is removed from `Config`, the destructure breaks the
    /// other way (unused binding warning under `-D warnings`).
    #[test]
    fn top_level_sections_matches_config_fields() {
        // Destructure every field on Config. If anyone adds a new
        // top-level field, this won't compile — and the fix is to
        // update both the destructure here AND TOP_LEVEL_SECTIONS.
        fn _enforce(c: Config) {
            let Config {
                extends: _,
                role: _,
                tools: _,
                gem: _,
                go: _,
                privileges: _,
                hooks: _,
                env: _,
                services: _,
                roles_config: _,
                network: _,
                npm: _,
                pip: _,
                cargo: _,
                nuget: _,
                git: _,
                git_hooks: _,
                skills: _,
                drift: _,
                telemetry: _,
                commands: _,
                workspace: _,
                ai_hooks: _,
                mcp_register: _,
                discover: _,
                packages: _,
                origin: _,
            } = c;
        }

        // Runtime cross-check: every TOML field on `Config` (via serde
        // names — `provisioner` not `tools`, `roles` not `roles_config`)
        // must appear in TOP_LEVEL_SECTIONS. Hard-coded list mirrors the
        // destructure above with serde renames applied.
        let config_sections: &[&str] = &[
            "extends",
            "role",
            "provisioner",
            "privileges",
            "hooks",
            "env",
            "services",
            "roles",
            "network",
            "npm",
            "pip",
            "cargo",
            "nuget",
            "gem",
            "go",
            "packages",
            "git",
            "git_hooks",
            "skills",
            "drift",
            "telemetry",
            "commands",
            "workspace",
            "ai_hooks",
            "mcp_register",
        ];
        for s in config_sections {
            assert!(
                TOP_LEVEL_SECTIONS.contains(s),
                "Config has field `{}` but TOP_LEVEL_SECTIONS is missing it. \
                 Update src/config.rs::TOP_LEVEL_SECTIONS so jarvy validate \
                 stops warning users about this section.",
                s
            );
        }
    }

    /// Review items 4 + 5 (P0). `mark_remote()` must propagate the
    /// origin tag into every sub-config that owns one — otherwise the
    /// per-subsystem trust gates fire against the default `Local`
    /// value and a hostile remote config bypasses them.
    #[test]
    fn mark_remote_propagates_to_all_origin_bearing_subconfigs() {
        let toml_str = r#"
[provisioner]
git = "latest"

[ai_hooks]
agents = ["claude-code"]

[mcp_register]
agents = ["claude-code"]

[skills]
auto_install = false

[git_hooks]
enabled = true
"#;
        let mut cfg: Config = toml::from_str(toml_str).unwrap();
        // Baseline: every sub-config defaults to Local.
        assert_eq!(cfg.origin, crate::ai_hooks::ConfigOrigin::Local);
        assert_eq!(
            cfg.ai_hooks.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Local
        );
        assert_eq!(
            cfg.mcp_register.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Local
        );
        assert_eq!(
            cfg.skills.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Local
        );
        assert_eq!(
            cfg.git_hooks.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Local
        );

        cfg.mark_remote();

        // Every origin-bearing sub-config now Remote. If a future
        // sub-config adds an `origin` field and forgets the
        // propagation, add the assertion here so the next test run
        // catches it.
        assert_eq!(cfg.origin, crate::ai_hooks::ConfigOrigin::Remote);
        assert_eq!(
            cfg.ai_hooks.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Remote
        );
        assert_eq!(
            cfg.mcp_register.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Remote
        );
        assert_eq!(
            cfg.skills.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Remote
        );
        assert_eq!(
            cfg.git_hooks.as_ref().unwrap().origin,
            crate::ai_hooks::ConfigOrigin::Remote
        );
    }

    #[test]
    fn test_hooks_config_parsing() {
        let toml_str = r#"
[provisioner]
git = "latest"

[hooks]
pre_setup = "echo 'Starting setup'"
post_setup = "echo 'Done'"

[hooks.config]
shell = "zsh"
timeout = 120
continue_on_error = true

[hooks.node]
post_install = "npm install -g yarn"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert_eq!(
            config.hooks.pre_setup,
            Some("echo 'Starting setup'".to_string())
        );
        assert_eq!(config.hooks.post_setup, Some("echo 'Done'".to_string()));
        assert_eq!(config.hooks.config.shell, "zsh");
        assert_eq!(config.hooks.config.timeout, 120);
        assert!(config.hooks.config.continue_on_error);

        let node_hooks = config
            .get_tool_hooks("node")
            .expect("node hooks should exist");
        assert_eq!(
            node_hooks.post_install,
            Some("npm install -g yarn".to_string())
        );
    }

    #[test]
    fn test_hooks_config_defaults() {
        let toml_str = r#"
[provisioner]
git = "latest"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(config.hooks.pre_setup.is_none());
        assert!(config.hooks.post_setup.is_none());
        assert_eq!(config.hooks.config.timeout, DEFAULT_HOOK_TIMEOUT);
        assert!(!config.hooks.config.continue_on_error);
        assert!(!config.has_hooks());
    }

    #[test]
    fn test_has_hooks() {
        let toml_str = r#"
[provisioner]
git = "latest"

[hooks]
pre_setup = "echo 'hi'"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");
        assert!(config.has_hooks());
    }

    #[test]
    fn test_hook_settings_default_shell() {
        let settings = HookSettings::default();
        // Should be the value of SHELL env var or /bin/sh on Unix, powershell on Windows
        #[cfg(not(windows))]
        {
            assert!(!settings.shell.is_empty());
        }
        #[cfg(windows)]
        {
            assert_eq!(settings.shell, "powershell");
        }
        assert_eq!(settings.timeout, DEFAULT_HOOK_TIMEOUT);
        assert!(!settings.continue_on_error);
    }

    #[test]
    fn test_env_config_parsing_simple() {
        let toml_str = r#"
[provisioner]
git = "latest"

[env.vars]
MY_VAR = "simple_value"
PROJECT_ROOT = "$PWD"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert_eq!(config.env.vars.len(), 2);
        assert!(config.has_env());

        let my_var = config.env.vars.get("MY_VAR").expect("MY_VAR should exist");
        assert_eq!(my_var.value(), "simple_value");
        assert!(!my_var.should_append());
    }

    #[test]
    fn test_env_config_parsing_complex() {
        let toml_str = r#"
[provisioner]
git = "latest"

[env.vars]
NODE_PATH = { value = "$HOME/.node/bin", append = true, description = "Node binaries" }
SIMPLE = "just_a_value"

[env.config]
generate_dotenv = true
dotenv_path = ".env.local"
update_rc = true
add_to_gitignore = true
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        let node_path = config
            .env
            .vars
            .get("NODE_PATH")
            .expect("NODE_PATH should exist");
        assert_eq!(node_path.value(), "$HOME/.node/bin");
        assert!(node_path.should_append());

        assert!(config.env.config.generate_dotenv);
        assert_eq!(config.env.config.dotenv_path, PathBuf::from(".env.local"));
        assert!(config.env.config.update_rc);
        assert!(config.env.config.add_to_gitignore);
    }

    #[test]
    fn test_env_config_secrets() {
        let toml_str = r#"
[provisioner]
git = "latest"

[env.secrets]
API_KEY = { env = "MY_API_KEY", required = true }
DB_PASSWORD = { from_file = "~/.secrets/db_pass" }
OPTIONAL_KEY = { required = false, description = "Optional API key" }
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert_eq!(config.env.secrets.len(), 3);
        assert!(config.has_env());
    }

    #[test]
    fn test_env_config_defaults() {
        let toml_str = r#"
[provisioner]
git = "latest"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(config.env.vars.is_empty());
        assert!(config.env.secrets.is_empty());
        assert!(config.env.config.generate_dotenv);
        assert_eq!(config.env.config.dotenv_path, PathBuf::from(".env"));
        assert!(!config.env.config.update_rc);
        assert!(!config.has_env());
    }

    #[test]
    fn test_env_settings_default() {
        let settings = EnvSettings::default();
        assert!(settings.shell.is_none());
        assert!(!settings.update_rc);
        assert!(settings.generate_dotenv);
        assert_eq!(settings.dotenv_path, PathBuf::from(".env"));
        assert!(!settings.add_to_gitignore);
        assert!(settings.backup_rc);
    }

    #[test]
    fn test_services_config_defaults() {
        let toml_str = r#"
[provisioner]
git = "latest"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(!config.services.enabled);
        assert!(!config.services.auto_start);
        assert!(config.services.compose_file.is_none());
        assert!(config.services.tilt_file.is_none());
        assert!(!config.services.start_in_ci);
    }

    #[test]
    fn test_services_config_parsing() {
        let toml_str = r#"
[provisioner]
git = "latest"

[services]
enabled = true
auto_start = true
compose_file = "docker/docker-compose.yml"
start_in_ci = false
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(config.services.enabled);
        assert!(config.services.auto_start);
        assert_eq!(
            config.services.compose_file,
            Some(PathBuf::from("docker/docker-compose.yml"))
        );
        assert!(!config.services.start_in_ci);
    }

    #[test]
    fn test_services_should_auto_start() {
        // Test disabled services
        let disabled = ServicesConfig {
            enabled: false,
            auto_start: true,
            ..Default::default()
        };
        assert!(!disabled.should_auto_start(false));
        assert!(!disabled.should_auto_start(true));

        // Test enabled with auto_start off
        let no_auto = ServicesConfig {
            enabled: true,
            auto_start: false,
            ..Default::default()
        };
        assert!(!no_auto.should_auto_start(false));
        assert!(!no_auto.should_auto_start(true));

        // Test enabled with auto_start on, CI off
        let auto_no_ci = ServicesConfig {
            enabled: true,
            auto_start: true,
            start_in_ci: false,
            ..Default::default()
        };
        assert!(auto_no_ci.should_auto_start(false)); // not in CI
        assert!(!auto_no_ci.should_auto_start(true)); // in CI, start_in_ci is false

        // Test enabled with auto_start and start_in_ci on
        let auto_with_ci = ServicesConfig {
            enabled: true,
            auto_start: true,
            start_in_ci: true,
            ..Default::default()
        };
        assert!(auto_with_ci.should_auto_start(false));
        assert!(auto_with_ci.should_auto_start(true));
    }

    // ====================================================================
    // Deserialization regression tests (parallel-code-review item 8).
    //
    // Pin every documented `jarvy.toml` value-shape so a `#[serde(...)]`
    // annotation rename or a removed default surfaces here, not as a
    // user reporting "my config stopped parsing." Previously config.rs
    // had zero unit-level coverage of these shapes.
    // ====================================================================

    #[derive(Deserialize)]
    struct EnvWrap {
        value: EnvValue,
    }

    fn parse_env(toml_text: &str) -> EnvValue {
        let w: EnvWrap = toml::from_str(toml_text).expect("parse EnvValue");
        w.value
    }

    #[test]
    fn env_value_simple_string_form() {
        let v = parse_env(r#"value = "hello""#);
        assert_eq!(v.value(), "hello");
        assert!(!v.should_append());
    }

    #[test]
    fn env_value_complex_form_append_and_per_tool() {
        let v = parse_env(
            r#"
            [value]
            value = "/usr/local/bin"
            description = "extra path"
            append = true
            per_tool = false
            "#,
        );
        assert_eq!(v.value(), "/usr/local/bin");
        assert!(v.should_append());
        match v {
            EnvValue::Complex {
                description,
                append,
                per_tool,
                ..
            } => {
                assert_eq!(description.as_deref(), Some("extra path"));
                assert!(append);
                assert!(!per_tool);
            }
            EnvValue::Simple(_) => panic!("expected Complex variant"),
        }
    }

    #[derive(Deserialize)]
    struct SecretWrap {
        value: SecretValue,
    }

    fn parse_secret(toml_text: &str) -> SecretValue {
        let w: SecretWrap = toml::from_str(toml_text).expect("parse SecretValue");
        w.value
    }

    #[test]
    fn secret_value_simple_string_form() {
        let v = parse_secret(r#"value = "MY_VAR""#);
        assert!(matches!(v, SecretValue::Simple(ref s) if s == "MY_VAR"));
    }

    #[test]
    fn secret_value_from_file_form() {
        let v = parse_secret(
            r#"
            [value]
            from_file = "~/.secrets/db.txt"
            "#,
        );
        match v {
            SecretValue::FromFile { from_file } => {
                assert_eq!(from_file, "~/.secrets/db.txt");
            }
            _ => panic!("expected FromFile variant"),
        }
    }

    #[test]
    fn secret_value_prompt_with_env_default_required_true() {
        let v = parse_secret(
            r#"
            [value]
            env = "GITHUB_TOKEN"
            description = "token for private deps"
            "#,
        );
        match v {
            SecretValue::Prompt {
                env,
                required,
                description,
            } => {
                assert_eq!(env.as_deref(), Some("GITHUB_TOKEN"));
                // `required` defaults to true when omitted (default_true fn).
                assert!(required);
                assert_eq!(description.as_deref(), Some("token for private deps"));
            }
            _ => panic!("expected Prompt variant"),
        }
    }

    #[test]
    fn secret_value_prompt_explicit_required_false() {
        let v = parse_secret(
            r#"
            [value]
            env = "OPTIONAL_TOKEN"
            required = false
            "#,
        );
        match v {
            SecretValue::Prompt { required, .. } => assert!(!required),
            _ => panic!("expected Prompt variant"),
        }
    }

    #[derive(Deserialize)]
    struct ToolWrap {
        tool: ToolConfig,
    }

    fn parse_tool(toml_text: &str) -> ToolConfig {
        let w: ToolWrap = toml::from_str(toml_text).expect("parse ToolConfig");
        w.tool
    }

    #[test]
    fn tool_config_simple_string_form_defaults_to_version_manager_on() {
        let cfg = parse_tool(r#"tool = "20.10.0""#);
        let (key, tool) = build_tool_entry("node", &cfg);
        assert_eq!(key, "node");
        assert_eq!(tool.version, "20.10.0");
        // Simple form implies version_manager: true (CLAUDE.md contract).
        assert!(tool.version_manager);
        assert_eq!(tool.use_sudo, None);
    }

    #[test]
    fn tool_config_detailed_form_honors_version_manager_false() {
        let cfg = parse_tool(
            r#"
            [tool]
            version = "2.40"
            version_manager = false
            "#,
        );
        let (_key, tool) = build_tool_entry("git", &cfg);
        assert_eq!(tool.version, "2.40");
        assert!(!tool.version_manager);
    }

    #[test]
    fn tool_config_detailed_form_carries_use_sudo() {
        let cfg = parse_tool(
            r#"
            [tool]
            version = "1.0"
            use_sudo = true
            "#,
        );
        let (_, tool) = build_tool_entry("foo", &cfg);
        assert_eq!(tool.use_sudo, Some(true));
    }

    #[test]
    fn tool_config_detailed_omitting_version_manager_defaults_true() {
        let cfg = parse_tool(
            r#"
            [tool]
            version = "1.0"
            "#,
        );
        let (_, tool) = build_tool_entry("foo", &cfg);
        // Per build_tool_entry: Detailed form's version_manager
        // unwraps_or(true).
        assert!(tool.version_manager);
    }
}