tftio-clanker 0.2.0

Launch AI harnesses with runtime-configured context, domains, models, and prompts
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
//! Runtime configuration loading, validation, and overlay merging.

use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Deserializer, Serialize, de::Error as _};

const CONTEXT_PLACEHOLDER: &str = "{context}";

/// Error returned when a configured name is empty or unsafe as one path-like
/// component.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("invalid {kind} name `{value}`; use letters, digits, '.', '_', or '-'")]
pub struct InvalidName {
    kind: &'static str,
    value: String,
}

fn valid_name(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
}

macro_rules! name_type {
    ($name:ident, $kind:literal, $docs:literal) => {
        #[doc = $docs]
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
        #[serde(transparent)]
        pub struct $name(String);

        impl $name {
            #[doc = concat!("Create a validated ", $kind, " name.")]
            ///
            /// # Errors
            /// Returns [`InvalidName`] when the value is empty or contains an
            /// unsupported character.
            pub fn new(value: impl Into<String>) -> Result<Self, InvalidName> {
                let value = value.into();
                if valid_name(&value) {
                    Ok(Self(value))
                } else {
                    Err(InvalidName { kind: $kind, value })
                }
            }

            #[doc = concat!("Return the validated ", $kind, " name.")]
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                let value = String::deserialize(deserializer)?;
                Self::new(value).map_err(D::Error::custom)
            }
        }

        impl Borrow<str> for $name {
            fn borrow(&self) -> &str {
                self.as_str()
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(self.as_str())
            }
        }
    };
}

name_type!(ContextName, "context", "A validated context name.");
name_type!(DomainName, "domain", "A validated domain name.");
name_type!(HarnessName, "harness", "A validated harness name.");
name_type!(ModelName, "model", "A validated model alias.");
name_type!(SkillName, "skill", "A validated agent skill name.");

/// A validated prompter family name from runtime configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelFamily(prompter::FamilyName);

impl ModelFamily {
    /// Return the prompter family value.
    #[must_use]
    pub const fn as_prompter_family(&self) -> &prompter::FamilyName {
        &self.0
    }
}

impl<'de> Deserialize<'de> for ModelFamily {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        prompter::FamilyName::new(value)
            .map(Self)
            .map_err(D::Error::custom)
    }
}

/// Top-level runtime configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Runtime defaults and filesystem locations.
    pub defaults: DefaultsConfig,
    /// Harness definitions keyed by command name.
    pub harness: BTreeMap<HarnessName, HarnessConfig>,
    /// Model aliases and provider environment bundles.
    pub model: BTreeMap<ModelName, ModelConfig>,
    /// Domain prompt compositions.
    pub domain: BTreeMap<DomainName, DomainConfig>,
}

/// Runtime defaults and shared filesystem locations.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DefaultsConfig {
    /// Default domain for subcommand launches.
    pub domain: DomainName,
    /// Registry of every launchable context.
    pub contexts: Vec<ContextName>,
    /// Context used when no higher-precedence source resolves.
    pub context_fallback: ContextName,
    /// Hostname-specific context defaults.
    pub context_by_hostname: BTreeMap<String, ContextName>,
    /// Directory prepended to every launched process's `PATH`.
    pub shim_path: String,
    /// Executable used to wrap sandboxed launches.
    pub sandbox_wrapper: String,
    /// Prompter bundle containing `config.toml` and `library/`.
    pub prompter_bundle: String,
    /// Agent skill bundle containing one directory per vendorable skill.
    pub skills_bundle: String,
    /// Directory holding rendered prompt files for file-based injection.
    pub prompt_cache: String,
    /// Age after which cached prompt files are removed opportunistically.
    pub prompt_cache_ttl_seconds: u64,
}

/// One executable harness and its prompt/config integration.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HarnessConfig {
    /// Executable name or path.
    pub bin: String,
    /// Default model-family prompt variant.
    pub family: ModelFamily,
    /// Native arguments prepended to every command-mode launch.
    pub default_args: Vec<String>,
    /// Prompt injection contract.
    pub injection: InjectionConfig,
    /// Optional context-derived config directory.
    pub config_dir: Option<ConfigDirectory>,
}

/// Prompt injection contract for a harness.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum InjectionConfig {
    /// Inject prompt text as arguments, replacing `{text}`.
    ArgText {
        /// Argument template.
        args: Vec<String>,
    },
    /// Write prompt text to a file and inject its path as arguments.
    ArgFile {
        /// Argument template containing `{file}`.
        args: Vec<String>,
    },
    /// Write prompt text to a file and export its path through an environment variable.
    EnvFile {
        /// Target environment variable.
        environment: String,
    },
}

/// Context-derived harness configuration directory.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConfigDirectory {
    /// Environment variable exported for the context-derived directory.
    pub environment: String,
    /// Path template containing `{context}`.
    pub path: String,
}

/// One configured model alias.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ModelConfig {
    /// Harness this model can launch through.
    pub harness: HarnessName,
    /// Optional family override; the harness family is the fallback.
    pub family: Option<ModelFamily>,
    /// Literal environment values applied by the model.
    pub env: BTreeMap<String, String>,
    /// Target environment variable to source variable name mappings.
    pub env_from_secrets: BTreeMap<String, String>,
    /// Native arguments appended for this model.
    pub harness_args: Vec<String>,
}

/// One domain's prompt profiles and optional runtime defaults.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DomainConfig {
    /// Prompter profiles composed in order.
    pub profiles: Vec<String>,
    /// Cloud-portable skills vendored when this domain is baked.
    pub skills: Vec<SkillName>,
    /// Environment defaults applied by the domain.
    pub env: BTreeMap<String, String>,
    /// Optional model selected when no higher-precedence source exists.
    pub default_model: Option<ModelName>,
}

/// One semantic configuration validation failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigIssue {
    /// Dotted configuration key.
    pub key: String,
    /// Human-readable correction.
    pub message: String,
}

impl fmt::Display for ConfigIssue {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}: {}", self.key, self.message)
    }
}

/// Loaded and validated configuration plus its source paths.
#[derive(Debug, Clone)]
pub struct LoadedConfig {
    /// Required base configuration path.
    pub base_path: PathBuf,
    /// Applied overlay path, when present.
    pub overlay_path: Option<PathBuf>,
    /// Validated merged configuration.
    pub config: Config,
}

/// Fail-closed configuration loading errors.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// Required runtime config does not exist.
    #[error(
        "clanker config not found at {path}; run `just install-clanker` in agent-toolkit or set CLANKER_CONFIG"
    )]
    Missing {
        /// Missing path.
        path: PathBuf,
    },
    /// Config file could not be read.
    #[error("failed to read clanker config {path}: {source}")]
    Read {
        /// Failing path.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// TOML syntax is invalid.
    #[error("failed to parse clanker config {path}: {source}")]
    Parse {
        /// Failing path.
        path: PathBuf,
        /// TOML parse error.
        source: toml::de::Error,
    },
    /// Merged config does not match the typed schema.
    #[error("invalid clanker config schema from {sources}: {source}")]
    Schema {
        /// Base and optional overlay paths whose merged document failed.
        sources: String,
        /// Deserialization error.
        source: toml::de::Error,
    },
    /// Typed config violates cross-field invariants.
    #[error("invalid clanker config from {sources}:\n{issues}")]
    Invalid {
        /// Base and optional overlay paths whose merged document failed.
        sources: String,
        /// Newline-separated per-key issues.
        issues: String,
    },
}

impl Config {
    /// Validate cross-field and template invariants.
    #[must_use]
    pub fn issues(&self) -> Vec<ConfigIssue> {
        let mut issues = Vec::new();

        if self.harness.is_empty() {
            issues.push(ConfigIssue {
                key: "harness".to_string(),
                message: "must contain at least one harness".to_string(),
            });
        }

        check_nonempty(&mut issues, "defaults.shim_path", &self.defaults.shim_path);
        check_nonempty(
            &mut issues,
            "defaults.sandbox_wrapper",
            &self.defaults.sandbox_wrapper,
        );
        check_nonempty(
            &mut issues,
            "defaults.prompter_bundle",
            &self.defaults.prompter_bundle,
        );
        check_nonempty(
            &mut issues,
            "defaults.skills_bundle",
            &self.defaults.skills_bundle,
        );
        check_nonempty(
            &mut issues,
            "defaults.prompt_cache",
            &self.defaults.prompt_cache,
        );
        if !self.domain.contains_key(&self.defaults.domain) {
            issues.push(ConfigIssue {
                key: "defaults.domain".to_string(),
                message: format!("unknown domain `{}`", self.defaults.domain),
            });
        }
        if self.defaults.contexts.is_empty() {
            issues.push(ConfigIssue {
                key: "defaults.contexts".to_string(),
                message: "must contain at least one context".to_string(),
            });
        }
        if !self
            .defaults
            .contexts
            .contains(&self.defaults.context_fallback)
        {
            issues.push(ConfigIssue {
                key: "defaults.context_fallback".to_string(),
                message: format!(
                    "context `{}` is not in defaults.contexts",
                    self.defaults.context_fallback
                ),
            });
        }
        for (hostname, context) in &self.defaults.context_by_hostname {
            if hostname.trim().is_empty() {
                issues.push(ConfigIssue {
                    key: "defaults.context_by_hostname".to_string(),
                    message: "hostname keys must not be empty".to_string(),
                });
            }
            if !self.defaults.contexts.contains(context) {
                issues.push(ConfigIssue {
                    key: format!("defaults.context_by_hostname.{hostname}"),
                    message: format!("context `{context}` is not in defaults.contexts"),
                });
            }
        }

        for (name, harness) in &self.harness {
            check_nonempty(&mut issues, &format!("harness.{name}.bin"), &harness.bin);
            validate_injection(name, &harness.injection, &mut issues);
            if let Some(config_dir) = &harness.config_dir {
                let prefix = format!("harness.{name}.config_dir");
                check_environment_name(
                    &mut issues,
                    &format!("{prefix}.environment"),
                    &config_dir.environment,
                );
                require_placeholder(
                    &mut issues,
                    &format!("{prefix}.path"),
                    &config_dir.path,
                    CONTEXT_PLACEHOLDER,
                );
            }
        }

        for (name, model) in &self.model {
            if !self.harness.contains_key(&model.harness) {
                issues.push(ConfigIssue {
                    key: format!("model.{name}.harness"),
                    message: format!("unknown harness `{}`", model.harness),
                });
            }
            for environment in model.env.keys() {
                check_environment_name(
                    &mut issues,
                    &format!("model.{name}.env.{environment}"),
                    environment,
                );
            }
            for (target, source) in &model.env_from_secrets {
                check_environment_name(
                    &mut issues,
                    &format!("model.{name}.env_from_secrets.{target}"),
                    target,
                );
                check_environment_name(
                    &mut issues,
                    &format!("model.{name}.env_from_secrets.{target}"),
                    source,
                );
                if model.env.contains_key(target) {
                    issues.push(ConfigIssue {
                        key: format!("model.{name}.env_from_secrets.{target}"),
                        message: "duplicates a literal model.env target".to_string(),
                    });
                }
            }
        }

        for (name, domain) in &self.domain {
            if domain.profiles.is_empty() {
                issues.push(ConfigIssue {
                    key: format!("domain.{name}.profiles"),
                    message: "must contain at least one profile".to_string(),
                });
            }
            for (index, profile) in domain.profiles.iter().enumerate() {
                check_nonempty(
                    &mut issues,
                    &format!("domain.{name}.profiles[{index}]"),
                    profile,
                );
            }
            if let Some(model) = &domain.default_model {
                if !self.model.contains_key(model) {
                    issues.push(ConfigIssue {
                        key: format!("domain.{name}.default_model"),
                        message: format!("unknown model `{model}`"),
                    });
                }
            }
            for environment in domain.env.keys() {
                check_environment_name(
                    &mut issues,
                    &format!("domain.{name}.env.{environment}"),
                    environment,
                );
            }
        }

        issues
    }

    /// Validate filesystem-backed configuration references.
    #[must_use]
    pub fn filesystem_issues(&self, home: &Path) -> Vec<ConfigIssue> {
        let mut issues = Vec::new();
        let bundle = match expand_configured_path(&self.defaults.skills_bundle, home) {
            Ok(bundle) => bundle,
            Err(message) => {
                issues.push(ConfigIssue {
                    key: "defaults.skills_bundle".to_string(),
                    message,
                });
                return issues;
            }
        };

        if !bundle.is_dir() {
            issues.push(ConfigIssue {
                key: "defaults.skills_bundle".to_string(),
                message: format!("{} is not a directory", bundle.display()),
            });
        }

        for (domain_name, domain) in &self.domain {
            for skill in &domain.skills {
                let skill_path = bundle.join(skill.as_str()).join("SKILL.md");
                if !skill_path.is_file() {
                    issues.push(ConfigIssue {
                        key: format!("domain.{domain_name}.skills.{}", skill.as_str()),
                        message: format!("{} does not exist", skill_path.display()),
                    });
                }
            }
        }

        issues
    }
}

fn expand_configured_path(value: &str, home: &Path) -> Result<PathBuf, String> {
    if value == "~" {
        return Ok(home.to_path_buf());
    }
    if let Some(relative) = value.strip_prefix("~/") {
        return Ok(home.join(relative));
    }
    if value.starts_with('~') {
        return Err(format!(
            "unsupported configured path `{value}`; use `~` or `~/...`"
        ));
    }
    Ok(PathBuf::from(value))
}

fn validate_injection(
    name: &HarnessName,
    injection: &InjectionConfig,
    issues: &mut Vec<ConfigIssue>,
) {
    match injection {
        InjectionConfig::ArgText { args } => require_argument_placeholder(
            issues,
            &format!("harness.{name}.injection.args"),
            args,
            "{text}",
        ),
        InjectionConfig::ArgFile { args } => require_argument_placeholder(
            issues,
            &format!("harness.{name}.injection.args"),
            args,
            "{file}",
        ),
        InjectionConfig::EnvFile { environment } => check_environment_name(
            issues,
            &format!("harness.{name}.injection.environment"),
            environment,
        ),
    }
}

fn require_argument_placeholder(
    issues: &mut Vec<ConfigIssue>,
    key: &str,
    args: &[String],
    placeholder: &str,
) {
    if !args.iter().any(|argument| argument.contains(placeholder)) {
        issues.push(ConfigIssue {
            key: key.to_string(),
            message: format!("must contain `{placeholder}`"),
        });
    }
}

fn require_placeholder(issues: &mut Vec<ConfigIssue>, key: &str, value: &str, placeholder: &str) {
    if !value.contains(placeholder) {
        issues.push(ConfigIssue {
            key: key.to_string(),
            message: format!("must contain `{placeholder}`"),
        });
    }
}

fn check_nonempty(issues: &mut Vec<ConfigIssue>, key: &str, value: &str) {
    if value.trim().is_empty() {
        issues.push(ConfigIssue {
            key: key.to_string(),
            message: "must not be empty".to_string(),
        });
    }
}

fn check_environment_name(issues: &mut Vec<ConfigIssue>, key: &str, value: &str) {
    let mut bytes = value.bytes();
    let starts_valid = bytes
        .next()
        .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_');
    if !starts_valid || !bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') {
        issues.push(ConfigIssue {
            key: key.to_string(),
            message: format!("invalid environment variable name `{value}`"),
        });
    }
}

/// Return the standard machine overlay path for a base config path.
#[must_use]
pub fn local_overlay_path(base_path: &Path) -> PathBuf {
    base_path.with_file_name("local.toml")
}

/// Load, deep-merge, deserialize, and validate runtime configuration.
///
/// The optional `local.toml` sibling replaces scalar/array values and merges
/// tables recursively.
///
/// # Errors
/// Returns [`ConfigError`] for missing files, I/O failures, invalid TOML,
/// schema mismatches, or cross-field validation failures.
pub fn load_config(base_path: &Path) -> Result<LoadedConfig, ConfigError> {
    let overlay_path = local_overlay_path(base_path);
    load_config_with_overlay(base_path, Some(&overlay_path))
}

/// Load runtime configuration with an explicit optional overlay.
///
/// # Errors
/// Returns [`ConfigError`] for missing files, I/O failures, invalid TOML,
/// schema mismatches, or cross-field validation failures.
pub fn load_config_with_overlay(
    base_path: &Path,
    overlay_path: Option<&Path>,
) -> Result<LoadedConfig, ConfigError> {
    let mut merged = read_toml(base_path, true)?.ok_or_else(|| ConfigError::Missing {
        path: base_path.to_path_buf(),
    })?;

    let applied_overlay = if let Some(path) = overlay_path {
        read_toml(path, false)?.map(|overlay| {
            deep_merge(&mut merged, overlay);
            path.to_path_buf()
        })
    } else {
        None
    };

    let sources = config_sources(base_path, applied_overlay.as_deref());
    let config: Config = merged.try_into().map_err(|source| ConfigError::Schema {
        sources: sources.clone(),
        source,
    })?;
    let issues = config.issues();
    if !issues.is_empty() {
        return Err(ConfigError::Invalid {
            sources,
            issues: issues
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join("\n"),
        });
    }

    Ok(LoadedConfig {
        base_path: base_path.to_path_buf(),
        overlay_path: applied_overlay,
        config,
    })
}

fn config_sources(base_path: &Path, overlay_path: Option<&Path>) -> String {
    overlay_path.map_or_else(
        || base_path.display().to_string(),
        |overlay_path| {
            format!(
                "{} merged with {}",
                base_path.display(),
                overlay_path.display()
            )
        },
    )
}

fn read_toml(path: &Path, required: bool) -> Result<Option<toml::Value>, ConfigError> {
    let text = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound && !required => {
            return Ok(None);
        }
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
            return Err(ConfigError::Missing {
                path: path.to_path_buf(),
            });
        }
        Err(source) => {
            return Err(ConfigError::Read {
                path: path.to_path_buf(),
                source,
            });
        }
    };
    toml::from_str(&text)
        .map(Some)
        .map_err(|source| ConfigError::Parse {
            path: path.to_path_buf(),
            source,
        })
}

fn deep_merge(base: &mut toml::Value, overlay: toml::Value) {
    match (base, overlay) {
        (toml::Value::Table(base_table), toml::Value::Table(overlay_table)) => {
            for (key, overlay_value) in overlay_table {
                if let Some(base_value) = base_table.get_mut(&key) {
                    deep_merge(base_value, overlay_value);
                } else {
                    base_table.insert(key, overlay_value);
                }
            }
        }
        (base_value, overlay_value) => *base_value = overlay_value,
    }
}

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

    const COMPLETE_CONFIG: &str = r#"
[defaults]
domain = "eng"
contexts = ["personal", "work"]
context_fallback = "personal"
context_by_hostname = {}
shim_path = "~/.local/clankers/bin"
sandbox_wrapper = "~/.config/sandbox-exec/run-sandboxed.sh"
prompter_bundle = "~/.local/prompter"
skills_bundle = "~/.local/clanker/skills"
prompt_cache = "~/.cache/clanker/prompts"
prompt_cache_ttl_seconds = 86400

[harness.claude]
bin = "claude"
family = "claude"
default_args = []

[harness.claude.injection]
kind = "arg-text"
args = ["--append-system-prompt", "{text}"]

[model]

[domain.eng]
profiles = ["core.base", "domain.eng"]
skills = []
env = {}
"#;

    #[test]
    fn deep_merge_replaces_scalars_and_preserves_siblings() {
        let mut base: toml::Value = toml::from_str(
            r#"
[defaults]
domain = "eng"
context_fallback = "personal"
"#,
        )
        .unwrap();
        let overlay: toml::Value = toml::from_str(
            r#"
[defaults]
context_fallback = "work"
"#,
        )
        .unwrap();

        deep_merge(&mut base, overlay);

        assert_eq!(base["defaults"]["domain"].as_str(), Some("eng"));
        assert_eq!(base["defaults"]["context_fallback"].as_str(), Some("work"));
    }

    #[test]
    fn configured_names_reject_path_components() {
        assert!(HarnessName::new("claude").is_ok());
        assert!(HarnessName::new("../claude").is_err());
        assert!(ContextName::new("").is_err());
    }

    #[test]
    fn warnings_table_is_an_unknown_field_schema_error() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(
            &path,
            format!("{COMPLETE_CONFIG}\n[warnings]\nunknown_profile = \"{{invocation}}\"\n"),
        )
        .unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();

        assert!(error.to_string().contains("unknown field `warnings`"));
    }

    #[test]
    fn omitted_contexts_registry_is_a_schema_error() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(
            &path,
            COMPLETE_CONFIG.replace("contexts = [\"personal\", \"work\"]\n", ""),
        )
        .unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();

        assert!(error.to_string().contains("missing field `contexts`"));
    }

    #[test]
    fn unregistered_fallback_and_hostname_contexts_are_invalid() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(
            &path,
            COMPLETE_CONFIG
                .replace(
                    "contexts = [\"personal\", \"work\"]",
                    "contexts = [\"other\"]",
                )
                .replace(
                    "context_by_hostname = {}",
                    "context_by_hostname = { workstation = \"work\" }",
                ),
        )
        .unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();
        let message = error.to_string();

        assert!(message.contains("defaults.context_fallback"));
        assert!(message.contains("defaults.context_by_hostname.workstation"));
        assert!(message.contains("is not in defaults.contexts"));
    }

    #[test]
    fn omitted_required_collection_is_a_schema_error() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(
            &path,
            COMPLETE_CONFIG.replace("context_by_hostname = {}\n", ""),
        )
        .unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();
        let message = error.to_string();

        assert!(message.contains(path.to_str().unwrap()));
        assert!(message.contains("missing field `context_by_hostname`"));
    }

    #[test]
    fn omitted_harness_default_args_is_a_schema_error() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(&path, COMPLETE_CONFIG.replace("default_args = []\n", "")).unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();
        let message = error.to_string();

        assert!(message.contains(path.to_str().unwrap()));
        assert!(message.contains("missing field `default_args`"));
    }

    #[test]
    fn omitted_skills_bundle_is_a_schema_error() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(
            &path,
            COMPLETE_CONFIG.replace("skills_bundle = \"~/.local/clanker/skills\"\n", ""),
        )
        .unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();
        let message = error.to_string();

        assert!(message.contains(path.to_str().unwrap()));
        assert!(message.contains("missing field `skills_bundle`"));
    }

    #[test]
    fn omitted_domain_skills_is_a_schema_error() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(&path, COMPLETE_CONFIG.replace("skills = []\n", "")).unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();
        let message = error.to_string();

        assert!(message.contains(path.to_str().unwrap()));
        assert!(message.contains("missing field `skills`"));
    }

    #[test]
    fn filesystem_issues_report_missing_bundle_and_skills() {
        let temp = TempDir::new().unwrap();
        let mut config = toml::from_str::<Config>(
            &COMPLETE_CONFIG
                .replace(
                    "skills_bundle = \"~/.local/clanker/skills\"",
                    "skills_bundle = \"~/missing-skills\"",
                )
                .replace("skills = []", "skills = [\"current-session\"]"),
        )
        .unwrap();

        let missing_bundle = config.filesystem_issues(temp.path());
        assert!(
            missing_bundle
                .iter()
                .any(|issue| issue.key == "defaults.skills_bundle")
        );
        assert!(missing_bundle.iter().any(|issue| {
            issue.key == "domain.eng.skills.current-session"
                && issue.message.contains("current-session/SKILL.md")
        }));

        let bundle = temp.path().join("skills");
        fs::create_dir_all(bundle.join("current-session")).unwrap();
        fs::write(bundle.join("current-session/SKILL.md"), "skill").unwrap();
        config.defaults.skills_bundle = bundle.display().to_string();

        assert!(config.filesystem_issues(temp.path()).is_empty());
    }

    #[test]
    fn unknown_base_parameter_is_a_hard_schema_error() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        fs::write(
            &path,
            COMPLETE_CONFIG.replace(
                "prompter_bundle = \"~/.local/prompter\"",
                "prompter_bundle = \"~/.local/prompter\"\nunknown_parameter = true",
            ),
        )
        .unwrap();

        let error = load_config_with_overlay(&path, None).unwrap_err();
        let message = error.to_string();

        assert!(message.contains(path.to_str().unwrap()));
        assert!(message.contains("unknown field `unknown_parameter`"));
    }

    #[test]
    fn unknown_overlay_parameter_is_a_hard_schema_error() {
        let temp = TempDir::new().unwrap();
        let base_path = temp.path().join("config.toml");
        let overlay_path = temp.path().join("local.toml");
        fs::write(&base_path, COMPLETE_CONFIG).unwrap();
        fs::write(
            &overlay_path,
            "[harness.claude]\nunknown_parameter = true\n",
        )
        .unwrap();

        let error = load_config_with_overlay(&base_path, Some(&overlay_path)).unwrap_err();
        let message = error.to_string();

        assert!(message.contains(base_path.to_str().unwrap()));
        assert!(message.contains(overlay_path.to_str().unwrap()));
        assert!(message.contains("unknown field `unknown_parameter`"));
    }
}