io-harness 0.19.0

An embeddable agent runtime for Rust: any task, any provider, in your own process. Run commands, edit files and search a repository under a layered permission boundary on files, commands and network; gate the result on the project's own test command in any language, or on nothing at all; and keep a full SQLite trace of every step, refusal and budget draw. With an execution sandbox, contained sub-agents, an MCP client, and durable resume for unattended runs.
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
//! One config file, layered, projected onto the typed API (0.19.0).
//!
//! # What this is
//!
//! An operator writes `io.toml` and gets a permission boundary, sandbox caps,
//! run budgets, per-ecosystem toolchain commands, MCP servers and a price table
//! without compiling anything. io-cli and io-studio read the same file rather
//! than inventing two formats that would have to be reconciled later.
//!
//! # What this is not
//!
//! **The typed API is the authority.** Every key here lands in a type this crate
//! already had — [`Policy`], [`SandboxConfig`], [`Toolchain`], [`PriceTable`],
//! [`McpServer`], [`TaskContract`] — and a file can express nothing the typed
//! API cannot. Configuration is the ergonomic front end to that API, never a
//! second path into the run loop.
//!
//! **Nothing is loaded implicitly.** No entry point in this crate discovers a
//! config on its own: the caller calls [`Config::discover`] and decides what to
//! do with the result. That is what makes the one guarantee this module can
//! honestly make about an agent true — a config file the agent writes *during* a
//! run cannot widen the boundary that run is already under, because the boundary
//! was read once, by the caller, before the run started.
//!
//! **A config file is not a security boundary against the agent.** The boundary
//! is the [`Policy`] the caller loaded. A file is where that policy was written
//! down.
//!
//! # The four scopes
//!
//! Later wins, key by key:
//!
//! 1. the crate's own defaults — whatever the typed API produces with no file;
//! 2. **user** — `$IO_CONFIG_HOME/io.toml`, else `$XDG_CONFIG_HOME/io/io.toml`
//!    or `~/.config/io/io.toml` on unix, `%APPDATA%\io\io.toml` on Windows;
//! 3. **project** — `io.toml` in the workspace root. Meant to be committed;
//! 4. **local** — `io.local.toml` beside it. Meant to be gitignored.
//!
//! Discovery reads the root it was given and does **not** walk upward out of it:
//! a run's configuration comes from the directory the caller named, never from
//! somewhere above it that the caller did not choose.
//!
//! ```
//! use io_harness::Config;
//!
//! # fn demo() -> io_harness::Result<()> {
//! let dir = tempfile::tempdir()?;
//! std::fs::write(dir.path().join("io.toml"), r#"
//!     [policy.defaults]
//!     write = "ask"
//!
//!     [run]
//!     max_steps = 20
//! "#)?;
//! // The individual overrides one key of the team's file and nothing else.
//! std::fs::write(dir.path().join("io.local.toml"), "[run]\nmax_steps = 4\n")?;
//!
//! let config = Config::discover(dir.path())?;
//! let contract = config.apply_to(io_harness::TaskContract::new(
//!     "tidy the module",
//!     dir.path().join("src/lib.rs"),
//!     io_harness::Verification::FileContains("fn".into()),
//! ));
//!
//! assert_eq!(contract.max_steps, 4, "the local scope wins");
//! assert_eq!(
//!     config.policy().expect("a [policy] section").defaults.write,
//!     io_harness::Effect::Ask,
//! );
//! # Ok(()) }
//! # demo().unwrap();
//! ```
//!
//! # Two rules that make it trustworthy
//!
//! **An unknown key is an error.** A typo in a permission rule that is silently
//! ignored leaves an operator believing in a boundary that is not there.
//!
//! **A substitution resolves or fails; it never empties.** `${env:NAME}` and
//! `${file:path}` keep a credential out of a committed file. A variable that is
//! unset, a file that cannot be read, and a value that resolves to nothing are
//! all errors naming the key — because an empty string in a boundary rule is a
//! rule that matches nothing.
//!
//! ```
//! use io_harness::Config;
//!
//! // Rejected, naming the key: `max_stepz` is not a key this crate has.
//! let err = Config::from_toml("[run]\nmax_stepz = 3\n").unwrap_err();
//! assert!(err.to_string().contains("max_stepz"), "{err}");
//!
//! // Rejected, naming the key: an unset variable is not an empty string.
//! let err = Config::from_toml(
//!     "[[mcp]]\nid = \"gh\"\ntransport = \"stdio\"\ncommand = \"${env:IO_HARNESS_NOT_SET}\"\n",
//! )
//! .unwrap_err();
//! assert!(err.to_string().contains("IO_HARNESS_NOT_SET"), "{err}");
//! ```

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::context::ContextBudget;
use crate::error::{Error, Result};
use crate::mcp::McpServer;
use crate::policy::{Defaults, Effect, Layer, Policy};
use crate::pricing::{Price, PriceTable};
use crate::resilience::{RetryPolicy, StallPolicy};
use crate::sandbox::SandboxConfig;
use crate::toolchain::Toolchain;
use crate::tools::git::Identity;
use crate::TaskContract;

/// The project-scope file name: committed, and inherited by everyone on the team.
pub const PROJECT_FILE: &str = "io.toml";

/// The local-scope file name: gitignored, and an individual's own overrides.
pub const LOCAL_FILE: &str = "io.local.toml";

/// Environment variable that names the user-scope config directory outright,
/// ahead of every platform convention.
pub const CONFIG_HOME_VAR: &str = "IO_CONFIG_HOME";

/// Which file a value came from.
///
/// Reported by [`Config::sources`] so an operator whose setting did not take
/// effect can see which file won rather than guess.
///
/// ```
/// use io_harness::config::Scope;
///
/// // Later wins: the individual's own file is the last word.
/// assert!(Scope::Local > Scope::Project);
/// assert!(Scope::Project > Scope::User);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Scope {
    /// The operator's own file, outside any project.
    User,
    /// `io.toml` in the workspace root — the committed, shared one.
    Project,
    /// `io.local.toml` in the workspace root — the gitignored, personal one.
    Local,
}

// ---------------------------------------------------------------------------
// The file format
// ---------------------------------------------------------------------------

/// The whole file, every section optional.
///
/// `deny_unknown_fields` is on every section: an unknown key is the failure this
/// module exists to make loud.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct File {
    #[serde(default)]
    policy: Option<PolicySection>,
    #[serde(default)]
    sandbox: Option<SandboxSection>,
    #[serde(default)]
    run: Option<RunSection>,
    #[serde(default)]
    toolchain: BTreeMap<String, ToolchainSection>,
    #[serde(default)]
    prices: Option<PricesSection>,
    // `McpServer` is `#[serde(flatten)]`-based and serde refuses `flatten`
    // beside `deny_unknown_fields`, so an unknown key *inside* one of these
    // tables is not rejected. Stated in the guide rather than papered over.
    #[serde(default)]
    mcp: Vec<McpServer>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicySection {
    #[serde(default)]
    defaults: Option<DefaultsSection>,
    #[serde(default)]
    layers: Vec<Layer>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct DefaultsSection {
    read: Option<Effect>,
    write: Option<Effect>,
    exec: Option<Effect>,
    net: Option<Effect>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SandboxSection {
    #[serde(default)]
    limits: Option<LimitsSection>,
    allow_network: Option<bool>,
    force_floor: Option<bool>,
}

/// Every cap optional and merged one key at a time — unlike [`SandboxLimits`](crate::sandbox::SandboxLimits)
/// itself, which a config naming `limits` at all would otherwise have to spell
/// out whole. `0` means *no cap*, since TOML has no null to write.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct LimitsSection {
    max_cpu_secs: Option<u64>,
    max_wall_secs: Option<u64>,
    max_memory_bytes: Option<u64>,
    max_processes: Option<u64>,
    max_open_files: Option<u64>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RunSection {
    max_steps: Option<u32>,
    max_duration_secs: Option<u64>,
    max_tokens: Option<u64>,
    max_retries: Option<u32>,
    exec_timeout_secs: Option<u64>,
    skills: Option<PathBuf>,
    retry: Option<RetryPolicy>,
    stall: Option<StallPolicy>,
    context: Option<ContextBudget>,
    commit_identity: Option<Identity>,
}

/// An operator's override for one ecosystem, applied onto what
/// [`crate::toolchain::detect`] found. Every command optional: a file that
/// changes the test command should not have to restate the build one.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolchainSection {
    manager: Option<String>,
    install: Option<Vec<String>>,
    build: Option<Vec<String>>,
    test: Option<Vec<String>>,
    lint: Option<Vec<String>>,
    format: Option<Vec<String>>,
    run: Option<Vec<String>>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct PricesSection {
    /// Required, for the same reason [`PriceTable::new`] requires it: a price
    /// list with no date is a claim with no expiry.
    as_of: String,
    #[serde(default)]
    models: BTreeMap<String, Price>,
}

// ---------------------------------------------------------------------------
// Loading
// ---------------------------------------------------------------------------

/// A loaded configuration: the merged value, and which files it came from.
///
/// ```
/// use io_harness::Config;
///
/// // A config carrying no sections is the crate's defaults, and says so.
/// let empty = Config::from_toml("").unwrap();
/// assert!(empty.is_empty());
/// assert!(empty.policy().is_none(), "no [policy] section is not an empty policy");
/// ```
#[derive(Debug, Clone, Default)]
pub struct Config {
    file: File,
    sources: Vec<(Scope, PathBuf)>,
}

impl Config {
    /// Read every scope that exists for `root` and merge them.
    ///
    /// A scope whose file is absent is skipped; a workspace with no files at all
    /// is not an error, it is the crate's defaults.
    ///
    /// ```
    /// use io_harness::config::{Config, Scope};
    ///
    /// # fn demo() -> io_harness::Result<()> {
    /// let dir = tempfile::tempdir()?;
    /// std::fs::write(dir.path().join("io.toml"), "[run]\nmax_tokens = 100000\n")?;
    ///
    /// let config = Config::discover(dir.path())?;
    /// assert_eq!(config.sources()[0].0, Scope::Project);
    /// # Ok(()) }
    /// # demo().unwrap();
    /// ```
    pub fn discover(root: impl AsRef<Path>) -> Result<Self> {
        let root = root.as_ref();
        let mut candidates: Vec<(Scope, PathBuf)> = Vec::new();
        if let Some(user) = user_path() {
            candidates.push((Scope::User, user));
        }
        candidates.push((Scope::Project, root.join(PROJECT_FILE)));
        candidates.push((Scope::Local, root.join(LOCAL_FILE)));

        let mut merged = toml::value::Table::new();
        let mut sources = Vec::new();
        for (scope, path) in candidates {
            if !path.is_file() {
                continue;
            }
            let table = read_scope(&path)?;
            merge(&mut merged, table, &mut Vec::new());
            sources.push((scope, path));
        }

        Ok(Self {
            file: deserialize(toml::Value::Table(merged), Path::new("<merged>"))?,
            sources,
        })
    }

    /// Parse one config from text, as the project scope.
    ///
    /// For a caller that holds its configuration somewhere this crate does not
    /// know about, and for tests. `${file:...}` resolves against the current
    /// directory, since there is no file to resolve against.
    ///
    /// ```
    /// use io_harness::Config;
    ///
    /// let config = Config::from_toml("[sandbox]\nallow_network = true\n").unwrap();
    /// assert!(config.sandbox().unwrap().allow_network);
    /// ```
    pub fn from_toml(text: &str) -> Result<Self> {
        let path = Path::new(PROJECT_FILE);
        let table = parse(text, path)?;
        Ok(Self {
            file: deserialize(toml::Value::Table(table), path)?,
            sources: Vec::new(),
        })
    }

    /// The files this configuration was merged from, in the order they were
    /// applied — so the last one that names a key is the one that won it.
    ///
    /// ```
    /// use io_harness::Config;
    ///
    /// let config = Config::from_toml("").unwrap();
    /// assert!(config.sources().is_empty(), "parsed text has no file behind it");
    /// ```
    pub fn sources(&self) -> &[(Scope, PathBuf)] {
        &self.sources
    }

    /// Does this configuration set anything at all?
    ///
    /// ```
    /// use io_harness::Config;
    ///
    /// assert!(Config::from_toml("").unwrap().is_empty());
    /// assert!(!Config::from_toml("[run]\nmax_steps = 3\n").unwrap().is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.file.policy.is_none()
            && self.file.sandbox.is_none()
            && self.file.run.is_none()
            && self.file.toolchain.is_empty()
            && self.file.prices.is_none()
            && self.file.mcp.is_empty()
    }

    // -----------------------------------------------------------------------
    // Projection
    // -----------------------------------------------------------------------

    /// The [`Policy`] this configuration describes, or `None` where it has no
    /// `[policy]` section.
    ///
    /// The base is [`Policy::default`] — the tiered default, with the secret
    /// patterns already denied — not [`Policy::permissive`]: a file that names a
    /// layer and forgets a default must not end up enforcing less than a caller
    /// who wrote no file at all. Configured layers are appended after the
    /// built-in ones, and the type's own rule still holds across the seam: a
    /// later layer may add capability and may never re-allow an earlier deny.
    ///
    /// ```
    /// use io_harness::{Act, Config, Effect};
    ///
    /// let config = Config::from_toml(r#"
    ///     [policy.defaults]
    ///     write = "deny"
    ///
    ///     [[policy.layers]]
    ///     name = "ops-baseline"
    ///     rules = [{ act = "read", effect = "allow", pattern = "src/*" }]
    /// "#).unwrap();
    ///
    /// let policy = config.policy().unwrap();
    /// assert_eq!(policy.check(Act::Write, "src/lib.rs").effect, Effect::Deny);
    /// assert_eq!(policy.check(Act::Read, "src/lib.rs").effect, Effect::Allow);
    /// // The built-in secret denies survive a file that never mentioned them.
    /// assert_eq!(policy.check(Act::Read, ".env").effect, Effect::Deny);
    /// ```
    pub fn policy(&self) -> Option<Policy> {
        let section = self.file.policy.as_ref()?;
        let base = Policy::default();
        let defaults = match &section.defaults {
            None => base.defaults,
            Some(d) => Defaults {
                read: d.read.unwrap_or(base.defaults.read),
                write: d.write.unwrap_or(base.defaults.write),
                exec: d.exec.unwrap_or(base.defaults.exec),
                net: d.net.unwrap_or(base.defaults.net),
            },
        };
        let mut layers = base.layers;
        layers.extend(section.layers.iter().cloned());
        Some(Policy { layers, defaults })
    }

    /// The [`SandboxConfig`] this configuration describes, or `None` where it has
    /// no `[sandbox]` section.
    ///
    /// Caps merge one key at a time onto [`SandboxLimits::default`](crate::sandbox::SandboxLimits::default), so a file
    /// that lowers the wall clock keeps the default memory cap. `0` means *no
    /// cap* — TOML has no null, and "absent" already means "inherit".
    ///
    /// ```
    /// use io_harness::Config;
    ///
    /// let config = Config::from_toml(r#"
    ///     [sandbox.limits]
    ///     max_wall_secs = 30
    ///     max_cpu_secs = 0
    /// "#).unwrap();
    ///
    /// let sandbox = config.sandbox().unwrap();
    /// assert_eq!(sandbox.limits.max_wall_secs, Some(30));
    /// assert_eq!(sandbox.limits.max_cpu_secs, None, "0 is no cap, not a zero-second cap");
    /// assert_eq!(sandbox.limits.max_open_files, Some(512), "untouched caps keep their default");
    /// assert!(!sandbox.allow_network, "and the default-deny on egress still holds");
    /// ```
    pub fn sandbox(&self) -> Option<SandboxConfig> {
        let section = self.file.sandbox.as_ref()?;
        let mut config = SandboxConfig::new();
        if let Some(limits) = &section.limits {
            let base = &mut config.limits;
            for (from, to) in [
                (limits.max_cpu_secs, &mut base.max_cpu_secs),
                (limits.max_wall_secs, &mut base.max_wall_secs),
                (limits.max_memory_bytes, &mut base.max_memory_bytes),
                (limits.max_processes, &mut base.max_processes),
                (limits.max_open_files, &mut base.max_open_files),
            ] {
                if let Some(v) = from {
                    *to = if v == 0 { None } else { Some(v) };
                }
            }
        }
        if let Some(v) = section.allow_network {
            config.allow_network = v;
        }
        if let Some(v) = section.force_floor {
            config.force_floor = v;
        }
        Some(config)
    }

    /// The [`PriceTable`] this configuration describes, or `None` where it has no
    /// `[prices]` section.
    ///
    /// This is where a price comes from. The crate ships none — it cannot keep a
    /// vendor's list accurate on its own release schedule — so until an operator
    /// writes one down, [`crate::pricing`] reports unpriced calls rather than a
    /// cost.
    ///
    /// ```
    /// use io_harness::{Config, Usage};
    ///
    /// let config = Config::from_toml(r#"
    ///     [prices]
    ///     as_of = "2026-07-29"
    ///
    ///     [prices.models."some-vendor/some-model"]
    ///     input = 3_000_000
    ///     output = 15_000_000
    /// "#).unwrap();
    ///
    /// let prices = config.prices().unwrap();
    /// let usage = Usage { prompt_tokens: 1_000_000, completion_tokens: 0, ..Default::default() };
    /// assert_eq!(prices.cost_micros("some-vendor/some-model", &usage), Some(3_000_000));
    /// assert_eq!(prices.as_of(), "2026-07-29");
    /// ```
    pub fn prices(&self) -> Option<PriceTable> {
        let section = self.file.prices.as_ref()?;
        let mut table = PriceTable::new(section.as_of.clone());
        for (model, price) in &section.models {
            table = table.with(model.clone(), *price);
        }
        Some(table)
    }

    /// `detected` with this configuration's override for its ecosystem applied.
    ///
    /// Keyed on [`Toolchain::ecosystem`], so a file may carry an override for
    /// every ecosystem a team works in and only the matching one is used. A
    /// detection with no override comes back unchanged.
    ///
    /// This projection is for the embedding application: the harness's own run
    /// loop detects for itself and does not consult a config, because reaching it
    /// would mean a new `TaskContract` field, which is a break this release does
    /// not carry.
    ///
    /// ```
    /// use io_harness::Config;
    ///
    /// # fn demo() -> std::io::Result<()> {
    /// let dir = tempfile::tempdir()?;
    /// std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"x\"\n")?;
    /// let detected = io_harness::toolchain::detect(dir.path()).unwrap();
    /// assert_eq!(detected.test, ["cargo", "test"]);
    ///
    /// let config = Config::from_toml(r#"
    ///     [toolchain.cargo]
    ///     test = ["cargo", "nextest", "run"]
    /// "#).unwrap();
    ///
    /// let tuned = config.toolchain(detected);
    /// assert_eq!(tuned.test, ["cargo", "nextest", "run"]);
    /// assert_eq!(tuned.build, ["cargo", "build"], "what the file did not name is unchanged");
    /// # Ok(()) }
    /// # demo().unwrap();
    /// ```
    pub fn toolchain(&self, detected: Toolchain) -> Toolchain {
        let Some(section) = self.file.toolchain.get(&detected.ecosystem) else {
            return detected;
        };
        let mut out = detected;
        if let Some(v) = &section.manager {
            out.manager = v.clone();
        }
        for (from, to) in [
            (&section.install, &mut out.install),
            (&section.build, &mut out.build),
            (&section.test, &mut out.test),
            (&section.lint, &mut out.lint),
            (&section.format, &mut out.format),
            (&section.run, &mut out.run),
        ] {
            if let Some(v) = from {
                *to = v.clone();
            }
        }
        out
    }

    /// The MCP servers this configuration declares.
    ///
    /// ```
    /// use io_harness::Config;
    ///
    /// let config = Config::from_toml(r#"
    ///     [[mcp]]
    ///     id = "github"
    ///     transport = "stdio"
    ///     command = "github-mcp-server"
    ///     args = ["stdio"]
    /// "#).unwrap();
    ///
    /// assert_eq!(config.mcp_servers()[0].id, "github");
    /// ```
    pub fn mcp_servers(&self) -> &[McpServer] {
        &self.file.mcp
    }

    /// `contract` with everything this configuration's `[run]` and `[[mcp]]`
    /// sections set.
    ///
    /// A method on `Config` rather than a field on [`TaskContract`]: a new public
    /// field is a break, and this release carries none. What the file cannot set
    /// is the task itself — `goal`, `file`, `root` and `verify` are what the
    /// caller is asking for now, not a property of the project.
    ///
    /// ```
    /// use std::time::Duration;
    /// use io_harness::{Config, TaskContract, Verification};
    ///
    /// let config = Config::from_toml(r#"
    ///     [run]
    ///     max_steps = 30
    ///     max_duration_secs = 900
    ///     max_retries = 4
    ///
    ///     [run.retry]
    ///     base_ms = 2000
    ///
    ///     [run.stall]
    ///     window = 5
    /// "#).unwrap();
    ///
    /// let contract = config.apply_to(TaskContract::new(
    ///     "make the suite pass",
    ///     "src/lib.rs",
    ///     Verification::FileContains("fn".into()),
    /// ));
    ///
    /// assert_eq!(contract.max_steps, 30);
    /// assert_eq!(contract.max_duration, Some(Duration::from_secs(900)));
    /// assert_eq!(contract.max_retries, 4);
    /// assert_eq!(contract.retry.base, Duration::from_millis(2000));
    /// // A key the file left out keeps the type's own default.
    /// assert_eq!(contract.retry.max, Duration::from_secs(30));
    /// assert_eq!(contract.stall.window, 5);
    /// ```
    #[must_use]
    pub fn apply_to(&self, contract: TaskContract) -> TaskContract {
        let mut out = contract;
        if !self.file.mcp.is_empty() {
            out = out.with_mcp(self.file.mcp.iter().cloned());
        }
        let Some(run) = &self.file.run else {
            return out;
        };
        if let Some(v) = run.max_steps {
            out = out.with_max_steps(v);
        }
        if let Some(v) = run.max_duration_secs {
            out = out.with_time_budget(Duration::from_secs(v));
        }
        if let Some(v) = run.max_tokens {
            out = out.with_token_budget(v);
        }
        if let Some(v) = run.max_retries {
            out = out.with_max_retries(v);
        }
        if let Some(v) = run.exec_timeout_secs {
            out = out.with_exec_timeout(Duration::from_secs(v));
        }
        if let Some(v) = &run.skills {
            out = out.with_skills(v.clone());
        }
        if let Some(v) = run.retry {
            out = out.with_retry_policy(v);
        }
        if let Some(v) = run.stall {
            out = out.with_stall_policy(v);
        }
        if let Some(v) = run.context {
            out = out.with_context_budget(v);
        }
        if let Some(v) = &run.commit_identity {
            out = out.with_commit_identity(v.name.clone(), v.email.clone());
        }
        out
    }
}

/// Where the user-scope file lives on this platform, or `None` where no home
/// directory could be determined.
///
/// `$IO_CONFIG_HOME` wins outright, then `$XDG_CONFIG_HOME/io` or `~/.config/io`
/// on unix and `%APPDATA%\io` on Windows.
///
/// ```
/// // Whatever it resolves to, it is the same answer twice — a config path that
/// // moved between two calls would make "which file won" unanswerable.
/// assert_eq!(io_harness::config::user_path(), io_harness::config::user_path());
/// ```
#[must_use]
pub fn user_path() -> Option<PathBuf> {
    if let Some(dir) = env_dir(CONFIG_HOME_VAR) {
        return Some(dir.join(PROJECT_FILE));
    }
    #[cfg(windows)]
    let base = env_dir("APPDATA")?;
    #[cfg(not(windows))]
    let base = match env_dir("XDG_CONFIG_HOME") {
        Some(dir) => dir,
        None => env_dir("HOME")?.join(".config"),
    };
    Some(base.join("io").join(PROJECT_FILE))
}

/// A directory named by an environment variable, ignoring one set to nothing —
/// an empty `HOME` is not a home directory at the filesystem root.
fn env_dir(var: &str) -> Option<PathBuf> {
    let value = std::env::var_os(var)?;
    if value.is_empty() {
        return None;
    }
    Some(PathBuf::from(value))
}

// ---------------------------------------------------------------------------
// Parse, substitute, validate, merge
// ---------------------------------------------------------------------------

/// Read one scope: parse it, substitute against its own directory, and validate
/// it on its own so an error can name the file it came from.
fn read_scope(path: &Path) -> Result<toml::value::Table> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| Error::Config(format!("{}: {e}", path.display())))?;
    let table = parse(&text, path)?;
    // Validated here and discarded: the value that is kept is the merged one,
    // but an error found now can name this file rather than "<merged>".
    let _: File = deserialize(toml::Value::Table(table.clone()), path)?;
    Ok(table)
}

/// Parse and substitute, in that order — a substitution is a value, not syntax.
fn parse(text: &str, path: &Path) -> Result<toml::value::Table> {
    let mut table: toml::value::Table = toml::from_str(text)
        .map_err(|e| Error::Config(format!("{}: {}", path.display(), e.message())))?;
    let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
    let mut key = Vec::new();
    for (k, v) in table.iter_mut() {
        key.push(k.clone());
        substitute(v, &dir, &mut key, path)?;
        key.pop();
    }
    Ok(table)
}

fn deserialize(value: toml::Value, path: &Path) -> Result<File> {
    value
        .try_into()
        .map_err(|e: toml::de::Error| Error::Config(format!("{}: {}", path.display(), e.message())))
}

/// Expand `${env:...}` and `${file:...}` in every string this value contains.
fn substitute(
    value: &mut toml::Value,
    dir: &Path,
    key: &mut Vec<String>,
    path: &Path,
) -> Result<()> {
    match value {
        toml::Value::String(s) => *s = expand(s, dir, key, path)?,
        toml::Value::Array(items) => {
            for (i, item) in items.iter_mut().enumerate() {
                key.push(format!("[{i}]"));
                substitute(item, dir, key, path)?;
                key.pop();
            }
        }
        toml::Value::Table(table) => {
            for (k, v) in table.iter_mut() {
                key.push(k.clone());
                substitute(v, dir, key, path)?;
                key.pop();
            }
        }
        _ => {}
    }
    Ok(())
}

/// One string's worth of substitution.
///
/// Every failure is an error naming the key. None of them is an empty string: a
/// config that silently disarms itself is the worst outcome this feature can
/// produce.
fn expand(raw: &str, dir: &Path, key: &[String], path: &Path) -> Result<String> {
    let mut out = String::new();
    let mut rest = raw;
    while let Some(at) = rest.find("${") {
        out.push_str(&rest[..at]);
        let after = &rest[at + 2..];
        let Some(end) = after.find('}') else {
            return Err(bad_key(path, key, "unterminated `${` substitution"));
        };
        let inner = &after[..end];
        let Some((kind, arg)) = inner.split_once(':') else {
            return Err(bad_key(
                path,
                key,
                format!("`${{{inner}}}` names neither `env:` nor `file:`"),
            ));
        };
        let value = match kind {
            "env" => std::env::var(arg).map_err(|_| {
                bad_key(
                    path,
                    key,
                    format!("environment variable `{arg}` is not set"),
                )
            })?,
            "file" => {
                let at = dir.join(arg);
                std::fs::read_to_string(&at)
                    .map_err(|e| {
                        bad_key(path, key, format!("cannot read `{}`: {e}", at.display()))
                    })?
                    .trim()
                    .to_string()
            }
            other => {
                return Err(bad_key(
                    path,
                    key,
                    format!("`{other}:` is not a substitution this crate knows"),
                ))
            }
        };
        if value.is_empty() {
            return Err(bad_key(
                path,
                key,
                format!("`${{{inner}}}` resolved to nothing, and an empty value is never what a config meant"),
            ));
        }
        out.push_str(&value);
        rest = &after[end + 1..];
    }
    out.push_str(rest);
    Ok(out)
}

fn bad_key(path: &Path, key: &[String], why: impl std::fmt::Display) -> Error {
    Error::Config(format!(
        "{}: key `{}`: {why}",
        path.display(),
        key.join(".")
    ))
}

/// The keys whose arrays *append* across scopes instead of being replaced.
///
/// Only one, and it is the one the [`Policy`] type's own semantics call for: a
/// later scope adds a layer, it does not rewrite the boundary. Everything else
/// replaces, because a half-merged MCP server definition is not a server.
const APPENDING: &[&[&str]] = &[&["policy", "layers"]];

/// Deep-merge `over` onto `base`, later winning key by key.
fn merge(base: &mut toml::value::Table, over: toml::value::Table, at: &mut Vec<String>) {
    for (key, value) in over {
        at.push(key.clone());
        match (base.get_mut(&key), value) {
            (Some(toml::Value::Table(b)), toml::Value::Table(o)) => merge(b, o, at),
            (Some(toml::Value::Array(b)), toml::Value::Array(o))
                if APPENDING.iter().any(|p| p == &at.as_slice()) =>
            {
                b.extend(o);
            }
            (_, value) => {
                base.insert(key.clone(), value);
            }
        }
        at.pop();
    }
}

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

    fn table(text: &str) -> toml::value::Table {
        toml::from_str(text).unwrap()
    }

    #[test]
    fn a_later_scope_wins_one_key_and_leaves_its_siblings() {
        let mut base = table("[sandbox.limits]\nmax_wall_secs = 120\nmax_cpu_secs = 60\n");
        merge(
            &mut base,
            table("[sandbox.limits]\nmax_wall_secs = 5\n"),
            &mut Vec::new(),
        );
        let limits = base["sandbox"]["limits"].as_table().unwrap();
        assert_eq!(limits["max_wall_secs"].as_integer(), Some(5));
        assert_eq!(
            limits["max_cpu_secs"].as_integer(),
            Some(60),
            "a sibling key the later scope never named is not disturbed"
        );
    }

    #[test]
    fn policy_layers_append_and_every_other_array_replaces() {
        let mut base = table(
            "[[policy.layers]]\nname = \"ops\"\nrules = []\n\
             [toolchain.cargo]\ntest = [\"cargo\", \"test\"]\n",
        );
        merge(
            &mut base,
            table(
                "[[policy.layers]]\nname = \"mine\"\nrules = []\n\
                 [toolchain.cargo]\ntest = [\"cargo\", \"nextest\", \"run\"]\n",
            ),
            &mut Vec::new(),
        );
        let layers = base["policy"]["layers"].as_array().unwrap();
        assert_eq!(layers.len(), 2, "layers append");
        assert_eq!(layers[0]["name"].as_str(), Some("ops"));
        assert_eq!(layers[1]["name"].as_str(), Some("mine"));
        let test = base["toolchain"]["cargo"]["test"].as_array().unwrap();
        assert_eq!(test.len(), 3, "an ordinary array is replaced whole");
    }

    #[test]
    fn substitution_resolves_or_fails_and_never_empties() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("token"), "  s3cret\n").unwrap();
        std::env::set_var("IO_HARNESS_TEST_SET", "from-the-environment");
        std::env::set_var("IO_HARNESS_TEST_EMPTY", "");

        let key = ["run".to_string()];
        let path = Path::new("io.toml");
        assert_eq!(
            expand("${env:IO_HARNESS_TEST_SET}", dir.path(), &key, path).unwrap(),
            "from-the-environment"
        );
        assert_eq!(
            expand("Bearer ${file:token}", dir.path(), &key, path).unwrap(),
            "Bearer s3cret",
            "a file's value is trimmed, and substitution is inside a larger string"
        );
        for (input, expect) in [
            ("${env:IO_HARNESS_TEST_UNSET}", "is not set"),
            ("${env:IO_HARNESS_TEST_EMPTY}", "resolved to nothing"),
            ("${file:absent}", "cannot read"),
            ("${nope:x}", "not a substitution"),
            ("${env:X", "unterminated"),
        ] {
            let err = expand(input, dir.path(), &key, path)
                .unwrap_err()
                .to_string();
            assert!(err.contains(expect), "{input}: {err}");
            assert!(err.contains("key `run`"), "the error names the key: {err}");
        }
        // The negative control for the whole set: a string with no substitution
        // in it is returned unchanged rather than being parsed at all.
        assert_eq!(
            expand("plain $HOME value", dir.path(), &key, path).unwrap(),
            "plain $HOME value"
        );
    }
}