eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! The settings catalogue, and the one setter all three surfaces use.
//!
//! M24 exists because every setting was a file edit: `config` could write a starter file, show
//! the result and check the keys nothing reads, but it could not change *one key*, so the answer
//! to "how do I change this" was a document. This module is the missing half.
//!
//! # Where the list of keys comes from
//!
//! Not from a list written by hand. `Config::default()` serialised to TOML *is* the schema: every
//! table and key a struct holds, with the value a build uses when the file says nothing. The
//! loaded config serialised the same way is the effective value. So the catalogue is derived, and
//! a field added later is settable the moment it exists — the same rule [`crate::config::check`]
//! already follows for unknown keys, which is why the setter and the checker cannot disagree
//! about what a key is called.
//!
//! Two shapes are deliberately **not** in the catalogue: a nested table (`provider.route` is a
//! list of routes, `[hooks.<name>]` belongs to its hook) and an array of tables. They are
//! structures, not values; a settings page that offers to "set" one has misunderstood it.
//!
//! # The one hand-written list, and why it is a test
//!
//! A field of type `Option<T>` that is `None` by default is *absent* from the serialised config,
//! so the derivation cannot see it — and `provider.api_key` is exactly that. [`ABSENT_BY_DEFAULT`]
//! declares those keys and their types, and
//! `every_key_that_is_absent_by_default_is_real_and_settable` proves each one by setting it,
//! parsing the result and reading the value back: an entry for a field that does not exist would
//! be refused by the setter's own round-trip check.
//!
//! # Why the setter edits text instead of re-serialising
//!
//! Re-serialising would be simpler and would delete every comment the user wrote. `toml_set_value`
//! replaces one line — or turns a commented `# key = …` into the real thing, or inserts the key
//! under its section header — so ordering, comments and unrelated lines survive exactly. What is
//! written is then **proved**: the edited text is parsed as a [`Config`] and the key is read back
//! to equal what was asked for. A setter that can leave an unloadable config behind is worse than
//! no setter.

use super::{is_secret_key, Config};
use std::fmt;

/// When a changed key takes effect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Applies {
    /// The next run reads it. Every key the agent is built from: the provider, the tools, the
    /// context files, the hooks.
    NextRun,
    /// The process that is serving reads it once, at startup: `[web]`, which is the address, the
    /// token and the session lifetime of an `eclipse-web` that is already running, and `[gateway]`,
    /// whose intervals are captured when `eclipse-gateway` starts (`#403`).
    RestartProcess,
}

/// Which sections a running process has already read.
///
/// `[gateway]`'s intervals are captured when `eclipse-gateway` starts, so a change to one is not
/// "next run" — the separate process has to come up again for it to matter (`#403`).
fn applies_to(section: &str) -> Applies {
    match section {
        "web" | "gateway" => Applies::RestartProcess,
        _ => Applies::NextRun,
    }
}

impl Applies {
    pub fn as_str(&self) -> &'static str {
        match self {
            Applies::NextRun => "next run",
            Applies::RestartProcess => "restart the background process",
        }
    }
}

/// The type a key holds, used both to validate what was typed and to say what went wrong.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Str,
    Integer,
    Float,
    Bool,
    List,
    Datetime,
}

impl Kind {
    fn of(value: &toml::Value) -> Kind {
        match value {
            toml::Value::String(_) => Kind::Str,
            toml::Value::Integer(_) => Kind::Integer,
            toml::Value::Float(_) => Kind::Float,
            toml::Value::Boolean(_) => Kind::Bool,
            toml::Value::Array(_) => Kind::List,
            toml::Value::Datetime(_) => Kind::Datetime,
            // A table is not a setting; the catalogue skips them, so this is unreachable in
            // practice and named anyway rather than guessed at.
            toml::Value::Table(_) => Kind::List,
        }
    }
}

impl Kind {
    /// The spelling a surface switches on — `"bool"`, `"integer"` — as opposed to [`Display`],
    /// which is the same thing in a sentence. A control is chosen from this, so it is a closed set
    /// on the wire and cannot be a sentence a page has to pattern-match.
    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Str => "str",
            Kind::Integer => "integer",
            Kind::Float => "float",
            Kind::Bool => "bool",
            Kind::List => "list",
            Kind::Datetime => "datetime",
        }
    }
}

impl fmt::Display for Kind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Kind::Str => "a string",
            Kind::Integer => "an integer",
            Kind::Float => "a number",
            Kind::Bool => "true or false",
            Kind::List => "a list",
            Kind::Datetime => "a date",
        })
    }
}

/// Whether this is the empty string — the spelling that means "not in use".
fn is_empty_string(value: &toml::Value) -> bool {
    matches!(value, toml::Value::String(s) if s.is_empty())
}

/// One key a person can read and write: `[section] key`, its default and its current value.
#[derive(Debug, Clone, PartialEq)]
pub struct Setting {
    pub section: String,
    pub key: String,
    /// What this build uses when the file does not set it. `None` for a key that is simply absent
    /// until somebody sets it (`provider.api_key`), which is not the same as an empty string.
    pub default: Option<toml::Value>,
    /// What the loaded config holds now. `None` when the key is unset.
    pub value: Option<toml::Value>,
    pub kind: Kind,
    /// A secret: never printed, never rendered to a page, only set.
    pub secret: bool,
    pub applies: Applies,
    /// One line: what this key does. See [`about`].
    pub about: &'static str,
    /// The values it accepts when the set is closed. See [`choices`].
    pub choices: &'static [&'static str],
}

impl Setting {
    /// `provider.model` — the spelling `config set` takes and the surfaces show.
    pub fn path(&self) -> String {
        format!("{}.{}", self.section, self.key)
    }

    /// Whether the loaded value is the default, so a surface can say "not set here".
    pub fn is_default(&self) -> bool {
        self.value == self.default
    }

    /// The value as a person should see it: the TOML rendering, a redaction for a secret, or
    /// `(not set)` for a key the file leaves alone.
    pub fn rendered(&self) -> String {
        if self.secret {
            return "«redacted»".to_string();
        }
        match &self.value {
            Some(value) => render(value),
            None => "(not set)".to_string(),
        }
    }

    /// The default in the same form [`Self::rendered`] uses, when this build has one for the key.
    ///
    /// Not every absent key has a default (an API key has none), which is why it is an `Option`
    /// and why `config keys` prints nothing rather than `(not set)` twice.
    pub fn rendered_default(&self) -> Option<String> {
        if self.secret {
            return None;
        }
        self.default.as_ref().map(render)
    }
}

impl fmt::Display for Setting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} = {}", self.path(), self.rendered())?;
        if self.is_default() {
            write!(f, " (default)")?;
        }
        if self.applies == Applies::RestartProcess {
            write!(f, " [{}]", self.applies.as_str())?;
        }
        Ok(())
    }
}

/// Keys that exist, are read, and serialise to nothing when unset: `(table, key, type)`.
///
/// A field of type `Option<T>` that is `None` by default has no TOML representation, so the
/// derived catalogue cannot see it. This list is the exception, and the test below is what keeps
/// it honest.
pub(crate) const ABSENT_BY_DEFAULT: &[(&str, &str, Kind)] = &[
    // `[provider]`: everything `provider.rs` reads and a default config does not write.
    ("flares", "total_tokens", Kind::Integer),
    ("provider", "api_key", Kind::Str),
    ("provider", "api_key_env", Kind::Str),
    ("provider", "aux", Kind::Str),
    ("provider", "delegate", Kind::Str),
    ("provider", "fallback", Kind::List),
    ("provider", "temperature", Kind::Float),
    ("provider", "max_tokens", Kind::Integer),
    ("provider", "profile", Kind::Str),
    ("provider", "top_p", Kind::Float),
    ("provider", "seed", Kind::Integer),
    ("provider", "stop", Kind::List),
    ("provider", "reasoning_effort", Kind::Str),
    ("provider", "parallel_tool_calls", Kind::Bool),
    ("provider", "tool_choice", Kind::Str),
    ("provider", "vision", Kind::Bool),
    ("agent", "output_schema", Kind::Str),
    ("tools", "workspace_root", Kind::Str),
    ("sessions", "dir", Kind::Str),
    ("attachments", "dir", Kind::Str),
    ("plugins", "dir", Kind::Str),
    ("plugins", "mcp_timeout_secs", Kind::Integer),
    ("web", "auth_token", Kind::Str),
    ("web", "default_profile", Kind::Str),
    ("cli", "color", Kind::Bool),
    ("cli", "markdown", Kind::Bool),
    ("update", "remote", Kind::Str),
    ("update", "releases", Kind::Str),
];

/// Fields that are deliberately *not* settings, each for a reason the catalogue's own rule gives:
/// structures (a table of routes, a map of per-hook options) are not scalar settings; `dotenv` is
/// what the loader *read*, not something a person sets; and the `serde(skip)` fields come from the
/// invocation (`--profile`, `--route`, `--no-mcp`), which their doc comments say outright.
///
/// It sits here, beside the list it complements, but only the completeness test reads it.
#[cfg(test)]
const NOT_SETTINGS: &[&str] = &[
    "provider.route",
    "provider.extra_body",
    "hooks.settings",
    "dotenv",
    "profile",
    "route_pin",
    "no_mcp",
];

/// A key that is absent by default but still has an answer this build stands behind.
///
/// `provider.reasoning_effort` is the one: `ProviderConfig::default()` leaves it `None` on purpose
/// (`unset = do not send` is what keeps an undeclared backend from being handed a field it may
/// 400 on), while the two shipped profiles declare `medium` as their default (`#276`). So the key
/// has a default a person can read — the level a fresh install resolves — without the config struct
/// claiming every backend understands it.
fn absent_default(section: &str, key: &str) -> Option<toml::Value> {
    match (section, key) {
        ("provider", "reasoning_effort") => Some(toml::Value::String(
            crate::reasoning::SHIPPED_DEFAULT.into(),
        )),
        _ => None,
    }
}

/// A TOML value as one line: strings quoted and escaped, everything else as TOML writes it.
fn render(value: &toml::Value) -> String {
    match value {
        toml::Value::String(s) => toml::Value::String(s.clone()).to_string(),
        other => other.to_string(),
    }
}

impl Config {
    /// Every scalar key this build knows, defaults and current values included, sorted by path.
    ///
    /// Nested tables and arrays of tables are skipped: they are structures, not settings (see the
    /// module doc). Arrays of scalars are settings and are included.
    pub fn settings(&self) -> Vec<Setting> {
        let Ok(defaults) = toml::Value::try_from(Config::default()) else {
            return Vec::new();
        };
        let Ok(current) = toml::Value::try_from(self) else {
            return Vec::new();
        };
        let mut out = Vec::new();
        for (section, table) in defaults.as_table().into_iter().flatten() {
            let loaded = current.get(section).and_then(toml::Value::as_table);
            for (key, default) in table.as_table().into_iter().flatten() {
                if matches!(default, toml::Value::Table(_)) {
                    continue;
                }
                if default
                    .as_array()
                    .is_some_and(|items| items.iter().any(toml::Value::is_table))
                {
                    continue;
                }
                let value = loaded.and_then(|t| t.get(key)).cloned();
                out.push(Setting {
                    section: section.clone(),
                    key: key.clone(),
                    kind: Kind::of(default),
                    default: Some(default.clone()),
                    value,
                    secret: is_secret_key(key),
                    applies: applies_to(section),
                    about: "",
                    choices: &[],
                });
            }
        }
        for (section, key, kind) in ABSENT_BY_DEFAULT {
            let value = current
                .get(section)
                .and_then(toml::Value::as_table)
                .and_then(|t| t.get(*key))
                .cloned();
            out.push(Setting {
                section: (*section).to_string(),
                key: (*key).to_string(),
                kind: *kind,
                default: absent_default(section, key),
                value,
                secret: is_secret_key(key),
                applies: applies_to(section),
                about: "",
                choices: &[],
            });
        }
        out.sort_by_key(Setting::path);
        out.dedup_by(|a, b| a.path() == b.path());
        // The words come from the tables above, keyed by the path the row shows: one lookup, so a
        // row cannot be explained by one surface and blank in another.
        for setting in &mut out {
            let path = setting.path();
            setting.about = about(&path);
            setting.choices = choices(&path);
            if let Some(kind) = word_default(&path) {
                setting.kind = kind;
            }
        }
        out
    }

    /// The setting `path` names (`provider.model`), if this build has it.
    pub fn setting(&self, path: &str) -> Option<Setting> {
        self.settings()
            .into_iter()
            .find(|s| s.path() == path.trim())
    }
}

/// Parse one value as a person typed it.
///
/// TOML first — so `3`, `true`, `["a", "b"]` and `0.5` mean what they look like — and a bare word
/// that is not valid TOML is a **string**, so `config set provider.model gemma-4-12b` does what it
/// says instead of failing on a missing quote. That is the one ambiguity here, and it is settled
/// in the direction a person typing a value expects.
pub fn parse_value(raw: &str) -> toml::Value {
    let raw = raw.trim();
    if let Ok(value) = format!("v = {raw}").parse::<toml::Value>() {
        if let Some(inner) = value.get("v") {
            return inner.clone();
        }
    }
    toml::Value::String(raw.to_string())
}

/// Set `path` to `value` in this config text, returning the new text.
///
/// Refuses, with a reason, when the key is not one this build reads, when the value has the wrong
/// type for it, or when the edited text does not load back with that value. Nothing is written to
/// disk here: the caller decides where the text goes, which is what lets the same function serve
/// the CLI, the dashboard and the interface.
pub fn set_in_text(
    text: &str,
    path: &str,
    value: &toml::Value,
) -> std::result::Result<String, String> {
    let schema = Config::default();
    let Some(setting) = schema.setting(path) else {
        return Err(unknown_setting(&schema, path));
    };
    // `#545`: three spellings the catalogue documents and this function used to refuse, because it
    // compared the typed value against the type of the *stored* one. A whole number for a float key
    // is the same number (`context.compact_at 0` turns compaction off); `0` and `-1` for a turn
    // budget are how a person writes "no limit", which the file spells `unlimited`; and a list key
    // typed as `a,b` is a list. Normalise to the spelling the file will hold before the kind check
    // and before the readback, so both compare like with like.
    let normalised;
    let value = match (&setting.kind, value) {
        (Kind::Float, toml::Value::Integer(n)) => {
            normalised = toml::Value::Float(*n as f64);
            &normalised
        }
        (_, toml::Value::Integer(n)) if *n <= 0 && word_default(&setting.path()).is_some() => {
            normalised = toml::Value::String("unlimited".to_string());
            &normalised
        }
        (Kind::List, toml::Value::String(raw)) => {
            normalised = toml::Value::Array(
                raw.split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(|s| toml::Value::String(s.to_string()))
                    .collect(),
            );
            &normalised
        }
        // `agent.prompt_blocks` is `auto`, `off` or a list, so its catalogue value is a word and a
        // list never matched it: `a,b` was written as a string the loader then refused.
        (_, toml::Value::String(raw)) if takes_a_list(&setting.path()) && raw.contains(',') => {
            normalised = toml::Value::Array(
                raw.split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(|s| toml::Value::String(s.to_string()))
                    .collect(),
            );
            &normalised
        }
        _ => value,
    };
    let typed = Kind::of(value);
    // A number-spelled-as-a-word key takes either spelling: `40` and `unlimited` are the two things
    // a person types for a turn budget, and neither is a mistake.
    if typed != setting.kind
        && !(setting.kind == Kind::Integer && is_unlimited(value))
        && !(takes_a_list(&setting.path()) && typed == Kind::List)
    {
        return Err(format!(
            "`{}` holds {} — {} is {}",
            setting.path(),
            setting.kind,
            render(value),
            typed
        ));
    }
    let edited = super::toml_set_value(text, &setting.section, &setting.key, &render(value));
    let checked = super::parse_text(&edited).map_err(|e| {
        format!(
            "that would not load, so nothing was saved: {}",
            one_line(&e.to_string())
        )
    })?;
    // `parse_text` reads the file; it does not run the route checks `load` runs. So a
    // `vision.route` that names nothing was written happily and the *next* load failed (`#385`).
    // Only the keys that name a route are checked here: refusing an unrelated edit because the
    // file was already broken elsewhere would trap the person who is trying to fix it.
    if names_a_route(&setting) {
        checked.validate_routes().map_err(|e| {
            format!(
                "that would not load, so nothing was saved: {}",
                one_line(&e.to_string())
            )
        })?;
    }
    // `[context]` is the other block whose keys are checked at load — a share outside 0..=1, a
    // handoff too small to compile. Unchecked here, `config set context.compact_at 1.5` saved and
    // every later command died in `load_with_profile` (#540).
    if setting.section == "context" {
        checked.context.validate().map_err(|e| {
            format!(
                "that would not load, so nothing was saved: {}",
                one_line(&e.to_string())
            )
        })?;
    }
    match checked.setting(&setting.path()) {
        Some(after) if after.value.as_ref() == Some(value) => Ok(edited),
        // An empty value *is* absence (`empty_is_none`, `Dotenv::load`), so `key = ""` proves itself
        // by loading as "not set". Without this arm every key whose shipped spelling is `""` could
        // not be written at all — `config set … ""` and a migration adding `aux = ""` both fail on
        // their own correct output.
        Some(after) if is_empty_string(value) && after.value.is_none() => Ok(edited),
        Some(after) => Err(format!(
            "the file would read `{}` back as {}, not {}; nothing was saved",
            setting.path(),
            after.rendered(),
            render(value)
        )),
        None => Err(format!(
            "`{}` disappeared from the file when it was edited; nothing was saved",
            setting.path()
        )),
    }
}

/// Set a list-valued key from `items` — `plugins.enabled = ["a", "b"]`.
///
/// The same proof as [`set_in_text`], and the reason it exists as its own function: a caller that
/// has `Vec<String>` should not have to build a `toml::Value` to say so, and the CLI does not
/// otherwise depend on the `toml` crate.
pub fn set_list_in_text(
    text: &str,
    path: &str,
    items: &[String],
) -> std::result::Result<String, String> {
    let value = toml::Value::Array(items.iter().cloned().map(toml::Value::String).collect());
    set_in_text(text, path, &value)
}

/// One line per key: what it does, in words a person choosing it can use.
///
/// It lives here rather than in a doc comment because a doc comment is not a value at runtime, and
/// the window, `/settings` in the composer and `eclipse config keys` all have to say the same thing
/// (the rule the palette and the command table follow). A test asserts every key in
/// [`Config::settings`] has one, so a new key cannot ship unexplained.
pub fn about(path: &str) -> &'static str {
    const ABOUT: &[(&str, &str)] = &[
        // [agent]
        ("agent.context_file_max_chars", "Truncate one context file past this many characters, keeping its head and tail; 0 = no per-file cap"),
        ("agent.context_files_budget_chars", "Ceiling across every context file; whole files are dropped past it, broadest first"),
        ("agent.max_consecutive_malformed_tool_calls", "Stop the run after this many consecutive tool calls that could not be used"),
        ("agent.max_iterations", "How many model-and-tool round trips one turn may take"),
        ("agent.output_schema", "A JSON Schema every reply must satisfy, as a path or inline JSON"),
        ("agent.system_prompt", "The standing instructions every run starts with, added to the built-in prompt rather than replacing it"),
        ("agent.trace_content", "Include prompts, arguments and results in trace spans"),
        (
            "agent.prompt_blocks",
            "Standing prompt blocks after system_prompt: `auto` (per model family), a list of names, or `off`",
        ),
        // [cli]
        (
            "cli.approval",
            "What an `ask` policy does: `ask` prompts, `auto` never does, `smart` asks a cheap model first and escalates when it is unsure",
        ),
        ("cli.clear_on_exit", "What an interactive exit does to the screen: `screen`, `all` or `off`"),
        ("cli.color", "Colour on a terminal; unset means decide from the stream, and from `NO_COLOR`"),
        ("cli.history_size", "How many commands the REPL remembers for arrow-up"),
        ("cli.markdown", "Markdown in replies; unset means on when colour is on"),
        // [context]
        ("context.compact_at", "Share of the model's window at which a request is compacted, e.g. 0.85; 0 turns the threshold off"),
        ("context.handoff_chars", "Hard cap, in characters, on the compiled handoff that stands in for the dropped middle"),
        ("context.judge", "Ask one model one bounded question about why the dropped turns went the way they did"),
        ("context.judge_timeout_secs", "How long that one call may take before the deterministic handoff ships without it"),
        ("context.protect_last_n", "Turns kept verbatim at the tail; 0 is read as 1"),
        ("context.window_tokens", "The window to assume when the endpoint advertises none; 0 assumes nothing"),
        // [gateway]
        ("gateway.api_session_ttl_hours", "How long a session made by `POST /v1/chat/completions` is kept"),
        ("gateway.check_interval_hours", "How often the gateway runs the update check and logs what it found"),
        // [hooks]
        // An unlisted hook does not run at all (`hooks.rs`: it is drawn as "(off)"), which is the
        // opposite of what this sentence used to say — an operator who wrote
        // `order = ["recall-sessions"]` from it silently turned `redact-secrets` off (#537).
        ("hooks.order", "The hooks that run, and in what order, by name; one that is not listed does not run, and `[]` runs none"),
        // [plugins]
        ("plugins.dir", "Root of the shared plugin directory (default `<config_dir>/plugins`)"),
        ("plugins.enabled", "The plugins to load, by directory name; one that is not listed loads only as a wire profile"),
        ("plugins.mcp_timeout_secs", "Ceiling on one MCP call, for `[[mcp]]` entries that state none of their own"),
        // [provider]
        ("provider.api_key", "A key written into the file; prefer `api_key_env` or `ECLIPSE_API_KEY`, which keep it out of it"),
        ("provider.api_key_env", "Name of an environment variable holding the key"),
        ("provider.aux", "The route that does the agent's own housekeeping — the summary of trimmed turns — and never the user's work"),
        ("provider.base_url", "Base URL of an OpenAI-compatible API, up to the `/v1`"),
        ("provider.context_budget_tokens", "Soft cap on the conversation sent to the model, in estimated tokens (characters / 4, a rough heuristic)"),
        ("provider.delegate", "The route a `delegate` call's child agent runs on unless the call names one"),
        ("provider.fallback", "The routes tried in order when a request fails for a transient reason"),
        ("provider.max_retries", "Extra attempts after a request fails with 408, 429 or 5xx, or could not be sent (0 = never)"),
        ("provider.max_tokens", "Cap on the reply, in tokens"),
        ("provider.model", "The model every request asks for"),
        ("provider.parallel_tool_calls", "Ask for several tool calls in one reply"),
        ("provider.profile", "Wire profile: `openai` (default), `llamacpp`, or one a plugin declares"),
        ("provider.reasoning_effort", "How much the model thinks, on backends that have the knob (`low`, `medium`, `high` …), or `omit` to put no reasoning field on the wire at all"),
        ("provider.retry_after_send", "Also retry a request that failed after it went out — a dropped connection, or nothing for `timeout_secs`"),
        ("provider.retry_base_delay_ms", "How long the first retry waits; each further attempt doubles it"),
        ("provider.seed", "Ask for a reproducible sample, where the backend supports it"),
        ("provider.stop", "Up to four sequences the reply stops at"),
        ("provider.stream", "Ask for a token-by-token (SSE) reply"),
        ("provider.temperature", "Sampling temperature, unset leaves whatever the server defaults to"),
        ("provider.timeout_secs", "Ceiling on one request, from connect to last byte"),
        ("provider.tool_choice", "`auto`, `none`, `required`, or one tool's name"),
        ("provider.top_p", "Nucleus sampling: draw from the smallest set of tokens holding this much probability"),
        ("provider.vision", "Declare whether this route's model can see images (overrides the wire profile)"),
        // [attachments]
        (
            "attachments.dir",
            "Where attached pictures are stored; defaults to `<state_dir>/attachments`"
        ),
        (
            "attachments.max_total_bytes",
            "Ceiling for every picture kept on disk, in bytes; the oldest are pruned when an attach would exceed it, and only then is an attach refused (0 = no ceiling)"
        ),
        // [sessions]
        ("sessions.auto_prune", "Apply the retention limits when the CLI starts, before the first prompt"),
        ("sessions.autotitle", "Name sessions: a name derived from the opening message, plus at most one small-model call"),
        ("sessions.dir", "Where sessions are stored; defaults to `<state_dir>/sessions`"),
        ("sessions.lock_wait_secs", "How long a run waits for another process to release the same session; 0 fails on the first refusal"),
        ("sessions.retention_keep_count", "Default for `sessions prune --keep-count`: keep only the newest N; 0 = disabled"),
        ("sessions.retention_keep_days", "Default for `sessions prune --keep-days`: delete sessions idle longer than this; 0 = disabled"),
        // [skills]
        ("skills.index_budget_chars", "Ceiling for the skill index in the system prompt, in characters"),
        // [vision]
        ("vision.mode", "A picture goes to the turn's model (`native`), to a route that describes it (`text`), or wherever the model's declared vision allows (`auto`)"),
        ("vision.route", "The route that describes a picture, for `text` and for `auto`'s fallback; empty means there is none"),
        ("vision.allow_cloud", "Let a picture be described by a route that is not on this machine"),
        // [flares]
        ("flares.count", "Default number of jobs for `flares run -n`; a local run starts from it (default 3)"),
        ("flares.max_concurrent", "The most flares one run may have in flight, whatever the routes allow"),
        ("flares.max_iterations", "Per flare, when the job does not say: what `delegate` gives a child"),
        ("flares.total_iterations", "The run's own budget: what stops one wandering flare eating the others' turns"),
        ("flares.total_tokens", "Optional spend cap for the whole run, in tokens; unset = the budgets are the ceiling"),
        // [tools]
        ("tools.concurrency", "How many of one turn's tool calls run at the same time; 1 runs them in order"),
        ("tools.deferred", "Tools that stay callable but are not described in the request, so they cost no tokens until needed"),
        ("tools.delegate", "The `delegate` tool's policy: hand a job to a child agent"),
        ("tools.disabled", "Tools removed entirely, whatever their policy says"),
        ("tools.execute_code", "The `execute_code` tool: a short program run from a temporary file, with a bridge to the tools"),
        ("tools.fetch", "The `fetch` tool: one URL in, its text out"),
        ("tools.fetch_html", "`text` renders HTML responses as plain text; `raw` returns the source"),
        ("tools.fetch_timeout_secs", "Ceiling on one `fetch`"),
        ("tools.max_output_bytes", "Tool output is cut to this many bytes before the model sees it"),
        ("tools.memory", "The `memory` tool's policy: write a durable fact to MEMORY.md"),
        ("tools.patch", "The `patch` tool's policy: a targeted edit of a file that already exists"),
        ("tools.read_file", "The `read_file` tool"),
        ("tools.rewrite_guard_bytes", "Above this size, `write_file` needs `force` to clobber an existing file"),
        ("tools.script", "The `script` tool's policy: run a file from the scripts directory"),
        ("tools.search_files", "The `search_files` tool's policy: a read-only walk of the workspace"),
        ("tools.shell", "The `shell` tool: run a command on this machine"),
        ("tools.shell_allowlist", "If set, `shell` may only run these program names, without a shell"),
        ("tools.shell_ask", "Which `shell` commands ask first: `dangerous` asks only for the un-undoable ones"),
        ("tools.shell_isolate", "What a `shell` command can reach: `off`, `process` (private PID namespace) or `fs` (bubblewrap)"),
        ("tools.shell_isolate_hide", "Paths replaced by an empty directory in `fs` mode, so nothing in them can be read"),
        ("tools.shell_isolate_network", "Whether `fs` isolation keeps the network"),
        ("tools.shell_isolate_writable", "Extra paths bound read-write in `fs` mode, beyond the workspace and the scripts directory"),
        ("tools.shell_timeout_secs", "Ceiling on one `shell` command"),
        ("tools.tool_call", "Call a tool a search found, without it being described up front"),
        ("tools.tool_describe", "Ask for a deferred tool's full schema"),
        ("tools.tool_search", "The `tool_search` tool's policy: look for a deferred tool"),
        ("tools.workspace_root", "The file tools are confined to this directory"),
        ("tools.write_file", "The `write_file` tool"),
        // [update]
        ("update.check", "How often the update check asks: `daily`, `weekly` or `off`"),
        ("update.releases", "Where the newest release is asked for, instead of the public GitHub repository"),
        ("update.remote", "Where the latest commit is asked for, instead of the public GitHub repository"),
        ("update.track", "Which branch a source install follows: `release` is main, `develop` is the branch work lands on"),
        // [user]
        ("user.file", "The user model file, relative to the config directory unless absolute"),
        ("user.memory_budget_chars", "Ceiling for `MEMORY.md` in characters"),
        ("user.memory_file", "The agent's memory file, resolved the same way"),
        // [web]
        ("web.auth_token", "The dashboard's login secret, generated by `config init`"),
        ("web.default_profile", "The profile the dashboard serves when neither `--profile` nor `ECLIPSE_PROFILE` names one"),
        ("web.host", "The address the dashboard binds; loopback only"),
        ("web.port", "The port the dashboard listens on"),
        ("web.session_ttl_hours", "How long a browser stays signed in"),
    ];
    ABOUT
        .iter()
        .find(|(key, _)| *key == path)
        .map(|(_, about)| *about)
        .unwrap_or("")
}

/// The values a key accepts, when the set is closed — the words a control can offer.
///
/// Empty for a key that takes what it takes: a path, a URL, a number. A `select` is only ever built
/// from this list, so the page cannot invent an option the parser would then refuse.
/// Keys whose default is *spelled as a word* while the key itself is a number.
///
/// `agent.max_iterations` serialises `usize::MAX` as `"unlimited"` — right for `config show`, wrong
/// as a description of the type, and it made `config set agent.max_iterations 40` refuse a whole
/// number for being the wrong kind. The word stays legal input; the kind a control reads is the
/// number.
fn word_default(path: &str) -> Option<Kind> {
    match path {
        "agent.max_iterations" => Some(Kind::Integer),
        _ => None,
    }
}

/// The words [`word_default`]'s key accepts instead of a number.
const UNLIMITED: &[&str] = &[
    "unlimited",
    "none",
    "null",
    "inf",
    "infinite",
    "infinity",
    "∞",
];

fn is_unlimited(value: &toml::Value) -> bool {
    value
        .as_str()
        .is_some_and(|w| UNLIMITED.contains(&w.trim().to_ascii_lowercase().as_str()))
}

/// Keys that are a word *or* a list.
///
/// `agent.prompt_blocks` defaults to `auto` and also takes `["task-completion", …]`, so the kind
/// the catalogue reads — from the default — is a string, and a list typed for it compared unequal
/// and was refused (`#545`). The list is written as one; the two words stay legal.
fn takes_a_list(path: &str) -> bool {
    matches!(path, "agent.prompt_blocks")
}

pub fn choices(path: &str) -> &'static [&'static str] {
    const ANY: &[&str] = &["deny", "ask", "allow"];
    match path {
        // A tool's policy, which is the same three words for every tool.
        p if p.starts_with("tools.")
            && matches!(
                p.split_once('.').map(|(_, k)| k),
                Some(
                    "delegate"
                        | "execute_code"
                        | "fetch"
                        | "memory"
                        | "patch"
                        | "read_file"
                        | "script"
                        | "search_files"
                        | "shell"
                        | "tool_call"
                        | "tool_describe"
                        | "tool_search"
                        | "write_file"
                )
            ) =>
        {
            ANY
        }
        // Three values, so it gets a list like every other enumeration: without this the settings
        // form and `config set vision.mode <TAB>` offered nothing for a key that only accepts
        // these three words (`#424`).
        "vision.mode" => &["native", "text", "auto"],
        // `smart` shipped in #340 and was missing here, so the dashboard's select could not offer
        // the mode the build supports (#546).
        "cli.approval" => &["ask", "auto", "smart"],
        "cli.clear_on_exit" => &["screen", "all", "off"],
        "tools.fetch_html" => &["text", "raw"],
        "tools.shell_ask" => &["dangerous", "always"],
        "tools.shell_isolate" => &["off", "process", "fs"],
        "update.check" => &["daily", "weekly", "off"],
        "update.track" => &["release", "develop"],
        _ => &[],
    }
}

/// Whether this key names a provider route, in the shape the checks care about.
fn names_a_route(setting: &Setting) -> bool {
    names_a_route_path(&setting.path())
}

fn names_a_route_path(path: &str) -> bool {
    // `provider.fallback` names routes as surely as `provider.aux` does, and an unchecked write of
    // it broke every later load (#540).
    path.starts_with("provider.route")
        || matches!(
            path,
            "provider.aux" | "provider.delegate" | "provider.fallback" | "vision.route"
        )
}

/// Comment `path` out of this config text, so the file falls back to its default.
///
/// Commented rather than deleted: the line's neighbours explain it, and a person who unsets
/// `web.port` should still be able to see what the key is called.
pub fn unset_in_text(text: &str, path: &str) -> std::result::Result<String, String> {
    let schema = Config::default();
    let Some(setting) = schema.setting(path) else {
        return Err(unknown_setting(&schema, path));
    };
    let edited = super::toml_comment_out(text, &setting.section, &setting.key);
    let checked = super::parse_text(&edited).map_err(|e| {
        format!(
            "that would not load, so nothing was saved: {}",
            one_line(&e.to_string())
        )
    })?;
    match checked.setting(&setting.path()) {
        // "Falls back to its default" is checked against what a `Config::default()` holds for the
        // key, not against the catalogue's `default` column: `provider.reasoning_effort` reports
        // `medium` there (the level the shipped profiles resolve, `#276`) while the config struct
        // leaves the field absent on purpose, so the honest check for "the line is gone and the
        // resolver is in charge" is that the file now reads what a default file reads.
        Some(after) if after.value == setting.value => Ok(edited),
        Some(after) => Err(format!(
            "the file would still read `{}` as {}; nothing was saved",
            setting.path(),
            after.rendered()
        )),
        None => Err(format!(
            "`{}` disappeared from the file when it was edited; nothing was saved",
            setting.path()
        )),
    }
}

/// The refusal for a path this build does not have, naming what does exist and — the mistake that
/// started `config check` — the table that *does* read a key of that name.
fn unknown_setting(schema: &Config, path: &str) -> String {
    let path = path.trim();
    let (section, key) = path.split_once('.').unwrap_or(("", path));
    let settings = schema.settings();
    if let Some(elsewhere) = settings.iter().find(|s| s.key == key) {
        return format!(
            "`{path}` is not a setting: `{key}` is read under [{}]. Write `{}`.",
            elsewhere.section,
            elsewhere.path()
        );
    }
    let mut near: Vec<String> = settings
        .iter()
        .filter(|s| s.key.contains(key) || key.contains(&s.key) || s.section == section)
        .map(Setting::path)
        .take(8)
        .collect();
    if near.is_empty() {
        near = settings.iter().take(8).map(Setting::path).collect();
    }
    format!(
        "`{path}` is not a setting in this build. `eclipse config keys` lists all of them; \
         close to what you wrote: {}",
        near.join(", ")
    )
}

pub(super) fn one_line(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

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

    fn paths() -> Vec<String> {
        Config::default()
            .settings()
            .into_iter()
            .map(|s| s.path())
            .collect()
    }

    /// `#545`: three spellings the catalogue documents that `set_in_text` refused with a message
    /// about kinds, because it compared the typed value against the type of the stored one.
    #[test]
    fn the_three_spellings_the_catalogue_documents_are_written() {
        let text = crate::config::starter_config().unwrap();

        // `context.compact_at 0` turns compaction off. The key is a float and TOML has no way to
        // spell "zero, as a float" without a decimal point.
        let edited = set_in_text(&text, "context.compact_at", &parse_value("0"))
            .expect("a whole number is a number");
        assert!(
            crate::config::parse_text(&edited)
                .unwrap()
                .context
                .compact_at
                == 0.0,
            "the threshold reads back as off: {edited}"
        );

        // `0` and `-1` are how a person writes "no cap"; the file spells it `unlimited`.
        for raw in ["0", "-1"] {
            let edited = set_in_text(&text, "agent.max_iterations", &parse_value(raw))
                .unwrap_or_else(|e| panic!("`{raw}` is a turn budget: {e}"));
            assert!(
                edited.contains("max_iterations = \"unlimited\""),
                "`{raw}` should be stored as the word: {edited}"
            );
        }

        // A list key typed as `a,b` is a list, not a string that the loader then refuses.
        let edited = set_in_text(
            &text,
            "agent.prompt_blocks",
            &parse_value("task-completion,parallel-tool-calls"),
        )
        .expect("a comma list is a list");
        assert!(
            edited.contains("prompt_blocks = [\"task-completion\", \"parallel-tool-calls\"]"),
            "the list is written as one: {edited}"
        );
    }

    #[test]
    fn the_catalogue_is_derived_from_the_config_itself() {
        let paths = paths();
        assert!(paths.contains(&"provider.model".to_string()), "{paths:?}");
        assert!(paths.contains(&"tools.shell".to_string()), "{paths:?}");
        assert!(paths.contains(&"web.port".to_string()), "{paths:?}");
        // Structures are not settings.
        assert!(
            !paths.iter().any(|k| k.starts_with("provider.route")),
            "a route is a table to edit, not a value: {paths:?}"
        );
        assert!(
            paths.iter().all(|k| k.matches('.').count() == 1),
            "{paths:?}"
        );
        // Sorted, so three surfaces cannot list them in three orders.
        let mut sorted = paths.clone();
        sorted.sort();
        assert_eq!(paths, sorted);
    }

    /// The catalogue is derived from `Config::default()`, which omits every `Option` that is `None`.
    /// That is how ten provider keys, `web.auth_token`, `cli.color`, `update.remote` and the rest
    /// came to exist without being settable: `config set provider.temperature 0.5` answered
    /// "unknown setting" for a field the agent reads on every request.
    ///
    /// The assignments below are the checklist, and the compiler keeps it honest: a renamed or
    /// deleted field stops this test building, and a field nobody assigns simply does not appear in
    /// the serialised config, so the walk cannot claim it.
    #[test]
    fn every_field_a_default_config_omits_is_still_settable() {
        let mut c = Config::default();
        c.provider.api_key = Some("probe".into());
        c.provider.api_key_env = Some("PROBE_KEY".into());
        c.provider.aux = Some("mmnuc/small".into());
        c.provider.delegate = Some("mmnuc/small".into());
        c.provider.fallback = Some(vec!["local".into()]);
        c.provider.temperature = Some(0.5);
        c.provider.max_tokens = Some(1024);
        c.provider.profile = Some("openai".into());
        c.provider.top_p = Some(0.9);
        c.provider.seed = Some(7);
        c.provider.stop = Some(vec!["</s>".into()]);
        c.provider.reasoning_effort = Some("low".into());
        c.provider.parallel_tool_calls = Some(true);
        c.provider.vision = Some(true);
        c.provider.tool_choice = Some(crate::hooks::ToolChoice::Auto);
        c.provider.extra_body = Some(serde_json::json!({"chat_template_kwargs": {"x": 1}}));
        c.agent.output_schema = Some("{}".into());
        c.tools.workspace_root = Some(std::path::PathBuf::from("/w"));
        c.sessions.dir = Some(std::path::PathBuf::from("/s"));
        c.plugins.dir = Some(std::path::PathBuf::from("/p"));
        c.plugins.mcp_timeout_secs = Some(30);
        c.web.auth_token = Some("probe-token".into());
        c.web.default_profile = Some("work".into());
        c.cli.color = Some(false);
        c.cli.markdown = Some(true);
        c.update.remote = Some("https://mirror.internal/latest".into());
        c.update.releases = Some("https://mirror.internal/releases".into());

        let filled = toml::Value::try_from(&c).expect("a filled config serialises");
        let schema = Config::default();
        let mut checked = 0;
        for (section, table) in filled.as_table().expect("a table").iter() {
            let Some(table) = table.as_table() else {
                continue;
            };
            for key in table.keys() {
                let path = format!("{section}.{key}");
                if NOT_SETTINGS.contains(&path.as_str()) {
                    continue;
                }
                assert!(
                    schema.setting(&path).is_some(),
                    "`{path}` is a real field but not a setting: `config set {path} …` would refuse it"
                );
                checked += 1;
            }
        }
        assert!(
            checked > 60,
            "the walk has to see the whole catalogue, not a corner: {checked}"
        );
    }

    /// `agent.max_iterations` serialises its off value as the word `unlimited`, which made the
    /// catalogue call it a string and refuse `config set agent.max_iterations 40`. Both spellings
    /// are legal input, and the kind a control reads is the number.
    #[test]
    fn a_turn_budget_takes_a_number_and_the_word_for_no_cap() {
        let schema = Config::default();
        let setting = schema.setting("agent.max_iterations").expect("a setting");
        assert_eq!(setting.kind, Kind::Integer, "a number, not a word");

        let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
        let cfg = super::super::parse_text(&edited).unwrap();
        assert_eq!(cfg.agent.max_iterations, 40);

        let edited = set_in_text(
            "",
            "agent.max_iterations",
            &toml::Value::String("unlimited".into()),
        )
        .unwrap();
        let cfg = super::super::parse_text(&edited).unwrap();
        assert_eq!(cfg.agent.max_iterations, usize::MAX);

        // Something that is neither is still refused, with the field's own sentence.
        let refused = set_in_text(
            "",
            "agent.max_iterations",
            &toml::Value::String("lots".into()),
        )
        .unwrap_err();
        assert!(refused.contains("max_iterations"), "{refused}");
    }

    /// Every key has a line explaining it, and only a closed set has `choices` — the two things a
    /// settings window needs and cannot invent.
    #[test]
    fn every_key_is_explained_and_the_closed_sets_name_their_values() {
        let settings = Config::default().settings();
        assert!(
            settings.len() > 80,
            "the whole catalogue: {}",
            settings.len()
        );
        for s in &settings {
            assert!(
                !s.about.trim().is_empty(),
                "{} has no description — add it to `about`",
                s.path()
            );
            assert!(s.about.len() < 160, "{}: too long for a row", s.path());
            assert!(
                !s.about.ends_with('.'),
                "{}: no trailing full stop",
                s.path()
            );
        }
        // `#537`: the catalogue said a hook that is not named runs *after* the ones that are,
        // while the loader does not run it at all — so `order = ["recall-sessions"]` written from
        // that sentence silently turned `redact-secrets` off.
        assert!(
            about("hooks.order").contains("does not run"),
            "{}",
            about("hooks.order")
        );
        assert_eq!(choices("cli.approval"), &["ask", "auto", "smart"]);
        assert_eq!(choices("tools.read_file"), &["deny", "ask", "allow"]);
        assert!(choices("provider.model").is_empty());
    }

    /// The hand-written list earns its place: every entry must be a real field, settable, and
    /// readable back. An entry for a field that does not exist fails here rather than in the
    /// middle of somebody's config edit.
    #[test]
    fn every_key_that_is_absent_by_default_is_real_and_settable() {
        for (section, key, kind) in ABSENT_BY_DEFAULT {
            let path = format!("{section}.{key}");
            let sample = match kind {
                // The three keys that name a route are validated by the command that writes them
                // (`#385`), so the probe has to name a route that exists: `default` is the one
                // `[provider]` itself provides.
                Kind::Str if names_a_route_path(&path) => toml::Value::String("default".into()),
                Kind::Str => toml::Value::String("probe".into()),
                Kind::Integer => toml::Value::Integer(7),
                Kind::Float => toml::Value::Float(0.5),
                Kind::Bool => toml::Value::Boolean(true),
                // `provider.fallback` is a list *of route names*, and since `#540` the writer
                // checks it: a probe that named a route which does not exist would be refused by
                // the very check the entry is here to prove.
                Kind::List if names_a_route_path(&path) => {
                    toml::Value::Array(vec![toml::Value::String("default".into())])
                }
                Kind::List => toml::Value::Array(vec![toml::Value::String("probe".into())]),
                Kind::Datetime => continue,
            };
            let edited = set_in_text("", &path, &sample).unwrap_or_else(|e| panic!("{path}: {e}"));
            let cfg = super::super::parse_text(&edited).unwrap_or_else(|e| panic!("{path}: {e}"));
            assert_eq!(
                cfg.setting(&path).and_then(|s| s.value),
                Some(sample),
                "{path} did not read back — is it a real field?"
            );
        }
    }

    #[test]
    fn an_absent_key_reports_itself_as_unset_and_is_not_the_default() {
        let schema = Config::default();
        let key = schema
            .setting("provider.api_key")
            .expect("api_key is a setting");
        assert!(key.secret, "a key by that name is a secret");
        assert_eq!(
            key.rendered(),
            "«redacted»",
            "never printed, even when unset"
        );
        assert_eq!(key.value, None, "absent is not the empty string");
        let plain = schema
            .setting("provider.model")
            .expect("model is a setting");
        assert!(!plain.secret);
    }

    /// Found by running `config keys` on a real install: `window_tokens` was `«redacted»`
    /// because it contains "token", which hid a number a person has to be able to set.
    #[test]
    fn a_count_is_not_a_credential() {
        let schema = Config::default();
        let window = schema
            .setting("context.window_tokens")
            .expect("window_tokens is a setting");
        assert!(!window.secret, "a token count is not a token");
        assert_eq!(window.rendered(), "0", "and its value is readable");
        assert!(schema.setting("provider.api_key").unwrap().secret);
        assert!(
            !schema.setting("provider.api_key_env").unwrap().secret,
            "the name of a variable is not the variable"
        );
    }

    #[test]
    fn setting_a_key_edits_one_line_and_everything_else_survives() {
        let text = "# my provider\n[provider]\n# the name the endpoint serves\nmodel = \"old\"\n\n[web]\nport = 8787\n";
        let edited =
            set_in_text(text, "provider.model", &toml::Value::String("new".into())).unwrap();
        assert!(edited.contains("model = \"new\""), "{edited}");
        assert!(
            edited.contains("# my provider") && edited.contains("# the name"),
            "{edited}"
        );
        assert!(edited.contains("port = 8787"), "{edited}");
        assert!(!edited.contains("\"old\""), "{edited}");
    }

    #[test]
    fn a_typed_value_is_written_as_toml_and_read_back() {
        let text = "[web]\nport = 8787\n";
        let edited = set_in_text(text, "web.port", &toml::Value::Integer(9000)).unwrap();
        assert!(edited.contains("port = 9000"), "{edited}");
        let cfg = super::super::parse_text(&edited).unwrap();
        assert_eq!(cfg.web.port, 9000);
    }

    #[test]
    fn a_value_of_the_wrong_shape_is_refused_with_the_shape_it_wants() {
        let text = "[web]\nport = 8787\n";
        let err = set_in_text(text, "web.port", &toml::Value::String("nine".into())).unwrap_err();
        assert!(err.contains("`web.port` holds an integer"), "{err}");
        assert!(err.contains("\"nine\" is a string"), "{err}");

        let err =
            set_in_text(text, "web.session_ttl_hours", &toml::Value::Boolean(true)).unwrap_err();
        assert!(err.contains("an integer"), "{err}");
    }

    #[test]
    fn a_key_this_build_does_not_read_is_refused_and_the_right_table_is_named() {
        let text = "[web]\n";
        let err = set_in_text(text, "web.model", &toml::Value::String("m".into())).unwrap_err();
        assert!(err.contains("`model` is read under [provider]"), "{err}");
        assert!(err.contains("provider.model"), "{err}");

        let err = set_in_text(text, "provider.modl", &toml::Value::String("m".into())).unwrap_err();
        assert!(err.contains("is not a setting"), "{err}");
        assert!(err.contains("config keys"), "where to look: {err}");
    }

    /// `#540`: the keys checked at load are the keys that have to be checked after an edit, or
    /// `config set` writes a file every later command dies on.
    #[test]
    fn a_fallback_naming_a_route_that_does_not_exist_is_refused() {
        let text = "[provider]\nbase_url = \"http://127.0.0.1:8080/v1\"\nmodel = \"m\"\n";
        let err = set_in_text(
            text,
            "provider.fallback",
            &toml::Value::Array(vec![toml::Value::String("ghost".into())]),
        )
        .unwrap_err();
        assert!(err.contains("ghost"), "{err}");
        assert!(err.contains("nothing was saved"), "{err}");
    }

    #[test]
    fn a_context_share_outside_the_window_is_refused() {
        let err = set_in_text("", "context.compact_at", &toml::Value::Float(1.5)).unwrap_err();
        assert!(err.contains("context.compact_at"), "{err}");
        assert!(err.contains("nothing was saved"), "{err}");
        let err = set_in_text("", "context.handoff_chars", &toml::Value::Integer(50)).unwrap_err();
        assert!(err.contains("context.handoff_chars"), "{err}");
    }

    #[test]
    fn a_key_the_config_does_not_have_yet_is_inserted_under_its_section() {
        let text = "[provider]\nbase_url = \"http://x/v1\"\n";
        let edited = set_in_text(
            text,
            "provider.api_key_env",
            &toml::Value::String("MY_KEY".into()),
        )
        .unwrap();
        assert!(edited.contains("api_key_env = \"MY_KEY\""), "{edited}");
        let cfg = super::super::parse_text(&edited).unwrap();
        assert_eq!(cfg.provider.api_key_env.as_deref(), Some("MY_KEY"));
    }

    #[test]
    fn unsetting_a_key_comments_it_out_and_the_default_comes_back() {
        let text = "[web]\nport = 9000\n";
        let edited = unset_in_text(text, "web.port").unwrap();
        assert!(
            edited.contains("# port = 9000"),
            "the line is kept as documentation: {edited}"
        );
        let cfg = super::super::parse_text(&edited).unwrap();
        assert_eq!(cfg.web.port, Config::default().web.port);
    }

    /// `#276`: on a fresh install `config keys` reports `provider.reasoning_effort` as `medium`
    /// both as the value and as the default — the file says it, and the resolver would supply the
    /// same answer if the line were deleted — while `ProviderConfig::default()` still leaves the
    /// field off so an undeclared backend is handed nothing.
    #[test]
    fn the_reasoning_key_reports_the_shipped_default_as_value_and_default() {
        let fresh = super::super::parse_text(&super::super::starter_config().unwrap())
            .expect("the starter");
        let row = fresh
            .setting("provider.reasoning_effort")
            .expect("the key is in the catalogue");
        assert_eq!(
            row.rendered(),
            format!("\"{}\"", crate::reasoning::SHIPPED_DEFAULT),
            "a fresh install has the level written down"
        );
        assert!(
            row.is_default(),
            "and the value is the default, so `config keys` marks it (default)"
        );

        // A file that predates the change: no line, and the default is still the answer.
        let older = Config::default();
        let row = older
            .setting("provider.reasoning_effort")
            .expect("the key is in the catalogue");
        assert_eq!(
            row.default,
            Some(toml::Value::String(
                crate::reasoning::SHIPPED_DEFAULT.into()
            )),
            "the resolver's answer is reportable even with no line in the file"
        );
        assert_eq!(row.value, None, "and the file genuinely sets nothing");
        assert_eq!(
            older.provider.reasoning_effort, None,
            "the config struct still sends nothing to a backend that declares no default"
        );
    }

    /// `#278`: the sentinel is a value of a key that already exists, so the catalogue takes it
    /// without knowing the word — which is the whole reason it is spelled there and not as a
    /// second `reasoning = "off"` key with a precedence rule of its own.
    #[test]
    fn the_reasoning_key_takes_the_omit_sentinel_as_a_value() {
        let cfg = super::super::parse_text(
            "[provider]\nbase_url = \"http://h/v1\"\nmodel = \"m\"\nreasoning_effort = \"omit\"\n",
        )
        .expect("the sentinel loads");
        assert_eq!(cfg.provider.reasoning_effort.as_deref(), Some("omit"));
        let row = cfg
            .setting("provider.reasoning_effort")
            .expect("the key is in the catalogue");
        assert_eq!(row.rendered(), "\"omit\"");
        assert!(
            !row.is_default(),
            "an operator's choice, not the shipped default"
        );
    }

    #[test]
    fn a_bare_word_is_a_string_and_toml_literals_keep_their_type() {
        assert_eq!(
            parse_value("gemma-4-12b"),
            toml::Value::String("gemma-4-12b".into())
        );
        assert_eq!(parse_value("3"), toml::Value::Integer(3));
        assert_eq!(parse_value("true"), toml::Value::Boolean(true));
        assert_eq!(parse_value("0.5"), toml::Value::Float(0.5));
        assert_eq!(
            parse_value(r#"["a", "b"]"#),
            toml::Value::Array(vec![
                toml::Value::String("a".into()),
                toml::Value::String("b".into())
            ])
        );
        assert_eq!(parse_value(""), toml::Value::String(String::new()));
    }

    /// `#424`: a three-value enumeration offers its values, like every other one.
    #[test]
    fn vision_mode_offers_its_three_words() {
        assert_eq!(choices("vision.mode"), &["native", "text", "auto"]);
        // The catalogue and the choices agree: a value the form cannot offer is a value nobody
        // can pick, and a choice the config refuses is a form that writes a broken file.
        for word in choices("vision.mode") {
            assert!(
                Config::default().setting("vision.mode").is_some(),
                "the key exists"
            );
            assert!(
                crate::config::Config::from_toml_str(&format!("[vision]\nmode = \"{word}\"\n"))
                    .is_ok(),
                "{word} is a value the config accepts"
            );
        }
    }

    /// `#385`: a key that names a route is checked by the command that writes it. It used to be
    /// written, and the *next* load failed — with the valid routes in the error, which is a fine
    /// place to read them but not after the file has already been saved.
    #[test]
    fn a_route_typo_is_refused_by_the_command_that_writes_it() {
        let err =
            set_in_text("", "vision.route", &toml::Value::String("sigth".into())).unwrap_err();
        assert!(
            err.contains("names `sigth`") && err.contains("Routes that exist"),
            "{err}"
        );
        // A route that exists is written.
        assert!(set_in_text("", "vision.route", &toml::Value::String("default".into())).is_ok());
        // And a key that names no route is not held hostage by an unrelated broken one.
        let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
        assert!(edited.contains("max_iterations = 40"));
    }

    /// `#403`: the gateway reads its intervals once, at startup, so a change to one is not "next
    /// run" — the separate process has to come up again.
    #[test]
    fn a_gateway_key_says_restart_instead_of_next_run() {
        let schema = Config::default();
        for path in [
            "gateway.check_interval_hours",
            "gateway.api_session_ttl_hours",
            "web.port",
        ] {
            let s = schema
                .setting(path)
                .unwrap_or_else(|| panic!("{path} exists"));
            assert_eq!(
                s.applies,
                Applies::RestartProcess,
                "{path} is read once by a process"
            );
        }
        let s = schema.setting("agent.max_iterations").expect("a setting");
        assert_eq!(s.applies, Applies::NextRun, "the agent is rebuilt per run");
        assert_eq!(
            Applies::RestartProcess.as_str(),
            "restart the background process"
        );
    }
}