Skip to main content

speccoder_runtime/
settings.rs

1//! `speccoder.toml` as settings: a catalogue of every key — its
2//! type, default and meaning — the values a project sets, and edits that
3//! keep the file's comments and are checked by every parser before they are
4//! written. speccoder reads committed configuration only, so a change is
5//! offered as a commit of exactly this file.
6
7use std::path::{Path, PathBuf};
8
9use serde_json::{Value, json};
10use speccoder_core::{
11    CommandData, CommandResult, CommandStatus, ConfigChange, ConfigKey, ConfigReport,
12    ConfigSection, ConfigTable,
13};
14
15use crate::git::Git;
16use crate::verify::config::FILE;
17
18/// What a key holds.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub enum Kind {
21    /// `true` or `false`.
22    Bool,
23    /// A whole number in a range.
24    Int(i64, i64),
25    /// A number in a range.
26    Num(f64, f64),
27    /// Text.
28    Str,
29    /// One of these.
30    Choice(&'static [&'static str]),
31    /// `30m`, `12h`, `7d`.
32    Duration,
33    /// A program and its arguments.
34    Argv,
35    /// A list of programs with arguments.
36    ArgvList,
37    /// A list of strings.
38    StrList,
39}
40
41impl Kind {
42    const fn name(self) -> &'static str {
43        match self {
44            Self::Bool => "bool",
45            Self::Int(..) => "integer",
46            Self::Num(..) => "number",
47            Self::Str => "string",
48            Self::Choice(_) => "choice",
49            Self::Duration => "duration",
50            Self::Argv => "argv",
51            Self::ArgvList => "argv_list",
52            Self::StrList => "string_list",
53        }
54    }
55}
56
57/// One key of the catalogue.
58#[derive(Debug, Clone, Copy)]
59pub struct Key {
60    /// The key, dotted below a sub-table (`sigstore.identity`).
61    pub key: &'static str,
62    /// What it holds.
63    pub kind: Kind,
64    /// Its default as JSON, when it has one.
65    pub default: Option<&'static str>,
66    /// The section is refused without it.
67    pub required: bool,
68    /// What it does.
69    pub about: &'static str,
70}
71
72/// One section of the catalogue.
73#[derive(Debug, Clone, Copy)]
74pub struct Section {
75    /// The table name.
76    pub name: &'static str,
77    /// For people.
78    pub title: &'static str,
79    /// What it decides.
80    pub about: &'static str,
81    /// `[name.<table>]` sections.
82    pub named: bool,
83    /// Its keys.
84    pub keys: &'static [Key],
85}
86
87const fn k(
88    key: &'static str,
89    kind: Kind,
90    default: Option<&'static str>,
91    about: &'static str,
92) -> Key {
93    Key {
94        key,
95        kind,
96        default,
97        required: false,
98        about,
99    }
100}
101
102const fn req(key: &'static str, kind: Kind, about: &'static str) -> Key {
103    Key {
104        key,
105        kind,
106        default: None,
107        required: true,
108        about,
109    }
110}
111
112/// The spec formats, by the names `[spec] format` takes — from the format
113/// model, not spelled here.
114const FORMATS: &[&str] = &[
115    speccoder_core::spec::FormatKind::ALL[0].name(),
116    speccoder_core::spec::FormatKind::ALL[1].name(),
117    speccoder_core::spec::FormatKind::ALL[2].name(),
118];
119
120const PRICE: Kind = Kind::Num(0.0, 100_000.0);
121
122/// Every key of `speccoder.toml`, in the reference's order. A test holds it
123/// to the parsers and to the configuration reference.
124pub const CATALOGUE: &[Section] = &[
125    Section {
126        name: "model",
127        title: "Model",
128        about: "The model that makes the attempts. The key comes from ANTHROPIC_API_KEY or OPENAI_API_KEY — never from this file.",
129        named: false,
130        keys: &[
131            req(
132                "provider",
133                Kind::Choice(&["anthropic", "openai", "openai-compatible"]),
134                "Who serves the model; openai-compatible covers Ollama, vLLM, llama.cpp, LM Studio and others",
135            ),
136            req(
137                "model",
138                Kind::Str,
139                "The model, for example claude-sonnet-5-5",
140            ),
141            k(
142                "reasoning_summary",
143                Kind::Bool,
144                Some("true"),
145                "Show the model's summary of its reasoning (a claim, not evidence)",
146            ),
147            k(
148                "max_output_tokens",
149                Kind::Int(1, 1_000_000),
150                Some("4096"),
151                "Output tokens per model turn",
152            ),
153            k(
154                "max_run_tokens",
155                Kind::Int(1, 100_000_000),
156                Some("200000"),
157                "Tokens per attempt",
158            ),
159            k(
160                "cache_ttl",
161                Kind::Choice(&["5m", "1h"]),
162                Some("\"5m\""),
163                "Anthropic's prompt-cache lifetime",
164            ),
165            k(
166                "base_url",
167                Kind::Str,
168                None,
169                "The server, required for openai-compatible (e.g. http://localhost:11434/v1)",
170            ),
171            k(
172                "api_key_env",
173                Kind::Str,
174                None,
175                "openai-compatible only: the variable holding the server's key",
176            ),
177            k(
178                "structured",
179                Kind::Choice(&["native", "tool"]),
180                Some("\"native\""),
181                "openai-compatible only: native structured output, or a forced tool call",
182            ),
183            k(
184                "price_input_per_mtok",
185                PRICE,
186                None,
187                "USD per million input tokens, for cost reports",
188            ),
189            k(
190                "price_output_per_mtok",
191                PRICE,
192                None,
193                "USD per million output tokens",
194            ),
195            k(
196                "price_cache_read_per_mtok",
197                PRICE,
198                None,
199                "USD per million tokens read from the cache",
200            ),
201            k(
202                "price_cache_write_per_mtok",
203                PRICE,
204                None,
205                "USD per million tokens written to the five-minute cache",
206            ),
207            k(
208                "price_cache_write_1h_per_mtok",
209                PRICE,
210                None,
211                "USD per million tokens written to the one-hour cache",
212            ),
213        ],
214    },
215    Section {
216        name: "checks",
217        title: "Checks",
218        about: "The commands that decide whether nothing regressed. Each check's command up to its first option is also something the model may run.",
219        named: true,
220        keys: &[
221            req(
222                "argv",
223                Kind::Argv,
224                "Program and arguments, run without a shell",
225            ),
226            k(
227                "cwd",
228                Kind::Str,
229                Some("\".\""),
230                "Working directory, relative to the project root",
231            ),
232            k(
233                "when_exists",
234                Kind::Str,
235                None,
236                "Run only if this path exists; otherwise skipped, never passed",
237            ),
238            k(
239                "tier",
240                Kind::Choice(&["fast", "full"]),
241                Some("\"fast\""),
242                "fast judges every task; full runs once after the feature's last task",
243            ),
244            k(
245                "timeout_secs",
246                Kind::Int(1, 86_400),
247                Some("600"),
248                "Deadline for the whole process group",
249            ),
250            k(
251                "junit",
252                Kind::Str,
253                None,
254                "A JUnit XML report the check writes, for per-test results",
255            ),
256        ],
257    },
258    Section {
259        name: "budget",
260        title: "Budget",
261        about: "How much an attempt may do, and how often a task is tried.",
262        named: false,
263        keys: &[
264            k(
265                "max_turns",
266                Kind::Int(1, 1000),
267                Some("30"),
268                "Model turns per attempt",
269            ),
270            k(
271                "max_tool_calls",
272                Kind::Int(1, 10_000),
273                Some("100"),
274                "Tool calls per attempt",
275            ),
276            k(
277                "max_attempts",
278                Kind::Int(1, 20),
279                Some("2"),
280                "Attempts per task run; a failed verdict is retried with the verifier's facts",
281            ),
282            k(
283                "best_of",
284                Kind::Int(1, 10),
285                Some("1"),
286                "Independent samples per task, the best by evidence kept",
287            ),
288        ],
289    },
290    Section {
291        name: "commands",
292        title: "Commands",
293        about: "What the model may run without asking, besides the checks. `allow` is exact; a prefix in `allow_prefix` runs whatever follows it, so it is saved only from a preview of what it would newly allow.",
294        named: false,
295        keys: &[
296            k(
297                "allow",
298                Kind::ArgvList,
299                Some("[]"),
300                "Exact commands that run without asking, e.g. [\"cargo\", \"check\"]; nothing after them",
301            ),
302            k(
303                "allow_prefix",
304                Kind::ArgvList,
305                Some("[]"),
306                "Command prefixes (two elements or more) whose every extension runs without asking; saved only from the coverage preview",
307            ),
308        ],
309    },
310    Section {
311        name: "approvals",
312        title: "Approvals",
313        about: "How long a call waits for a person, and how often a run may ask.",
314        named: false,
315        keys: &[
316            k(
317                "wait",
318                Kind::Duration,
319                Some("\"7d\""),
320                "How long a call waits before it is denied as expired (m, h or d)",
321            ),
322            k(
323                "budget",
324                Kind::Int(0, 100),
325                Some("12"),
326                "Prompts a run shows you; further calls wait together in Needs You",
327            ),
328        ],
329    },
330    Section {
331        name: "tests",
332        title: "Tests",
333        about: "What the model may do with tests that existed before an attempt.",
334        named: false,
335        keys: &[k(
336            "frozen",
337            Kind::Choice(&["ask", "additions"]),
338            Some("\"ask\""),
339            "ask before any change, or allow new lines without asking",
340        )],
341    },
342    Section {
343        name: "spec",
344        title: "Spec format",
345        about: "Which spec format the project uses; detected when unset.",
346        named: false,
347        keys: &[k(
348            "format",
349            Kind::Choice(FORMATS),
350            None,
351            "The spec format; --format and SPECCODER_FORMAT override it",
352        )],
353    },
354    Section {
355        name: "context",
356        title: "Instructions",
357        about: "The repository's instructions for agents, given to every attempt.",
358        named: false,
359        keys: &[k(
360            "instructions",
361            Kind::StrList,
362            Some("[\"AGENTS.md\"]"),
363            "File names read per directory, the first that exists; none to read none",
364        )],
365    },
366    Section {
367        name: "acceptance",
368        title: "Acceptance",
369        about: "Tests derived from the spec, and how strong they are.",
370        named: false,
371        keys: &[
372            k(
373                "generate",
374                Kind::Bool,
375                Some("true"),
376                "Derive acceptance tests from the spec before each attempt",
377            ),
378            k(
379                "held_out",
380                Kind::Bool,
381                Some("true"),
382                "Also write held-out tests the implementer never sees; verified needs them to pass",
383            ),
384            k(
385                "strength",
386                Kind::Bool,
387                Some("true"),
388                "Measure the acceptance strength of every verified task",
389            ),
390            k(
391                "min_strength",
392                Kind::Num(0.0, 1.0),
393                None,
394                "Below it the set is strengthened once, then the task stops for you",
395            ),
396            k(
397                "near_miss",
398                Kind::Int(0, 3),
399                Some("2"),
400                "Wrong variants to try",
401            ),
402            k(
403                "permitted",
404                Kind::Int(0, 2),
405                Some("1"),
406                "Spec-permitted alternatives to try; 0 turns the over-strict check off",
407            ),
408            k(
409                "strength_timeout_secs",
410                Kind::Int(1, 86_400),
411                Some("900"),
412                "Budget for the whole strength measurement",
413            ),
414        ],
415    },
416    Section {
417        name: "bug",
418        title: "Bug fixes",
419        about: "`speccoder bug`: how hard reproduce tries before the bug goes to you as cannot reproduce. A project setting only: a value in your user config is ignored.",
420        named: false,
421        keys: &[
422            k(
423                "reproduce_tries",
424                Kind::Int(1, 5),
425                Some("3"),
426                "Tries of the reproduction author before cannot reproduce (a rejection counts as one)",
427            ),
428            k(
429                "test",
430                Kind::Argv,
431                None,
432                "How one named test (`--test PATH::NAME`) runs, `{file}` and `{name}` filled in; default: the toolchain's own runner",
433            ),
434        ],
435    },
436    Section {
437        name: "converge",
438        title: "Convergence",
439        about: "How often a feature may be brought back to its spec.",
440        named: false,
441        keys: &[k(
442            "max_rounds",
443            Kind::Int(1, 20),
444            Some("3"),
445            "Convergence phases a feature may get",
446        )],
447    },
448    Section {
449        name: "review",
450        title: "Spec review",
451        about: "Whether a run waits for every requirement to be approved, and how tests are written at review.",
452        named: false,
453        keys: &[
454            k(
455                "required",
456                Kind::Bool,
457                Some("false"),
458                "A run waits until every requirement is approved on its current wording",
459            ),
460            k(
461                "oracle_samples",
462                Kind::Int(1, 2),
463                Some("2"),
464                "Independent author calls Write Tests makes; two are compared for ambiguity",
465            ),
466        ],
467    },
468    Section {
469        name: "monitor",
470        title: "Gaming monitor",
471        about: "A second model that reviews every passing attempt for gaming.",
472        named: false,
473        keys: &[k(
474            "enabled",
475            Kind::Bool,
476            Some("false"),
477            "Review every passing attempt",
478        )],
479    },
480    Section {
481        name: "git",
482        title: "Git",
483        about: "How passed tasks are recorded.",
484        named: false,
485        keys: &[k(
486            "commit",
487            Kind::Choice(&["per-task", "none"]),
488            Some("\"per-task\""),
489            "Commit each passed task, or leave changes uncommitted",
490        )],
491    },
492    Section {
493        name: "format",
494        title: "Formatter",
495        about: "A formatter run after each attempt; its changes are part of the attempt and audited.",
496        named: false,
497        keys: &[k(
498            "argv",
499            Kind::Argv,
500            None,
501            "The formatter, e.g. [\"cargo\", \"fmt\"]",
502        )],
503    },
504    Section {
505        name: "sandbox",
506        title: "Sandbox",
507        about: "Where commands the model runs may write and connect.",
508        named: false,
509        keys: &[
510            k(
511                "mode",
512                Kind::Choice(&["auto", "required", "off"]),
513                Some("\"auto\""),
514                "auto sandboxes where the OS can; required refuses to run unsandboxed",
515            ),
516            k(
517                "network",
518                Kind::Choice(&["off", "loopback", "on"]),
519                Some("\"loopback\""),
520                "Network for commands; loopback lets local test servers work",
521            ),
522            k(
523                "network_allow",
524                Kind::ArgvList,
525                Some("[]"),
526                "Exact commands that get the network, e.g. [\"cargo\", \"fetch\"]",
527            ),
528            k(
529                "network_allow_prefix",
530                Kind::ArgvList,
531                Some("[]"),
532                "Prefixes (two elements or more) whose extensions get the network; saved only from the coverage preview",
533            ),
534            k(
535                "writable",
536                Kind::StrList,
537                Some("[]"),
538                "Extra writable paths (~ is your home), e.g. ~/.m2",
539            ),
540        ],
541    },
542    Section {
543        name: "attest",
544        title: "Attestations",
545        about: "Signed statements of every tick, as git notes.",
546        named: false,
547        keys: &[
548            k(
549                "enabled",
550                Kind::Bool,
551                Some("true"),
552                "Write the statements on each tick commit",
553            ),
554            k(
555                "signer",
556                Kind::Choice(&["git", "sigstore", "none"]),
557                Some("\"git\""),
558                "Your git signing key, keyless sigstore, or unsigned",
559            ),
560            k(
561                "sign_at",
562                Kind::Choice(&["tick", "later"]),
563                Some("\"tick\""),
564                "Sign at each tick, or later with speccoder attest sign",
565            ),
566            k(
567                "sigstore.identity",
568                Kind::Str,
569                None,
570                "The identity you sign with, suggested to reviewers",
571            ),
572            k("sigstore.issuer", Kind::Str, None, "Its OIDC issuer"),
573        ],
574    },
575    Section {
576        name: "mutation",
577        title: "Mutation testing",
578        about: "Mutants run against the suite after a passing verdict.",
579        named: false,
580        keys: &[
581            req(
582                "tool",
583                Kind::Choice(&["cargo-mutants", "command"]),
584                "cargo-mutants, or command for any tool writing the mutation-testing report",
585            ),
586            k(
587                "argv",
588                Kind::Argv,
589                None,
590                "For command: the program; may use {diff}, {out}, {files}, {files_csv}",
591            ),
592            k("report", Kind::Str, None, "For command: the report file"),
593            k(
594                "mode",
595                Kind::Choice(&["report", "require"]),
596                Some("\"report\""),
597                "report records; require fails the verdict when mutants survive",
598            ),
599            k(
600                "timeout_secs",
601                Kind::Int(1, 86_400),
602                Some("900"),
603                "Limit for the whole mutation run",
604            ),
605            k(
606                "suite",
607                Kind::Bool,
608                Some("true"),
609                "Run mutants against the whole suite; false uses them for strength only",
610            ),
611            k(
612                "acceptance_argv",
613                Kind::Argv,
614                None,
615                "For command: runs the mutants against the acceptance tests alone",
616            ),
617        ],
618    },
619    Section {
620        name: "executor",
621        title: "Executor",
622        about: "Who makes the attempts: speccoder's own loop or an external agent.",
623        named: false,
624        keys: &[
625            Key {
626                key: "kind",
627                kind: Kind::Choice(&["native", "claude", "codex", "command"]),
628                default: None,
629                // Without [executor] speccoder's own loop runs; with it, the
630                // section must say which.
631                required: true,
632                about: "native, Claude Code, Codex, or any command",
633            },
634            k("model", Kind::Str, None, "The agent's model"),
635            k(
636                "timeout_secs",
637                Kind::Int(1, 86_400),
638                Some("1800"),
639                "How long one attempt may take",
640            ),
641            k(
642                "argv",
643                Kind::Argv,
644                None,
645                "For command: the program, which reads the task on stdin",
646            ),
647        ],
648    },
649    Section {
650        name: "mcp",
651        title: "MCP servers",
652        about: "Stdio MCP servers started in the worktree for each task; their tools appear as mcp__<server>__<tool>.",
653        named: true,
654        keys: &[
655            req("command", Kind::Argv, "The server's program and arguments"),
656            k(
657                "allow",
658                Kind::StrList,
659                Some("[]"),
660                "Tools called without approval",
661            ),
662            k("deny", Kind::StrList, Some("[]"), "Tools never offered"),
663        ],
664    },
665];
666
667/// Whether every parser accepts `text` — the same ones every command uses.
668///
669/// # Errors
670///
671/// The first parser's complaint.
672pub fn validate(text: &str) -> Result<(), String> {
673    crate::verify::config::parse(text)?;
674    crate::substrate::model_config::parse(text)?;
675    crate::substrate::run_config::parse(text)?;
676    crate::sandbox::parse(text)?;
677    crate::mcp::parse(text)?;
678    crate::mutation::parse(text)?;
679    crate::external::parse(text)?;
680    crate::format::parse_config(text)?;
681    Ok(())
682}
683
684/// The directory holding the configuration: the nearest with one, else the
685/// repository's top level, else `root`.
686fn home(root: &Path) -> PathBuf {
687    // Where the file is, else where `init` would write it (the spec
688    // project's root, which in a nested project is not the repository's).
689    crate::verify::find_config(root).unwrap_or_else(|| crate::init::root_of(root))
690}
691
692fn lookup<'a>(table: &'a toml::Table, path: &[&str]) -> Option<&'a toml::Value> {
693    let (last, parents) = path.split_last()?;
694    let mut t = table;
695    for p in parents {
696        t = t.get(*p)?.as_table()?;
697    }
698    t.get(*last)
699}
700
701fn key_view(k: &Key, value: Option<Value>) -> ConfigKey {
702    let (min, max) = match k.kind {
703        #[allow(clippy::cast_precision_loss)]
704        Kind::Int(a, b) => (Some(a as f64), Some(b as f64)),
705        Kind::Num(a, b) => (Some(a), Some(b)),
706        _ => (None, None),
707    };
708    ConfigKey {
709        key: k.key.to_owned(),
710        kind: k.kind.name().to_owned(),
711        about: k.about.to_owned(),
712        default: k.default.and_then(|d| serde_json::from_str(d).ok()),
713        value,
714        choices: match k.kind {
715            Kind::Choice(c) => c.iter().map(|s| (*s).to_owned()).collect(),
716            _ => Vec::new(),
717        },
718        min,
719        max,
720        required: k.required,
721    }
722}
723
724fn json_of(v: &toml::Value) -> Value {
725    serde_json::to_value(v).unwrap_or(Value::Null)
726}
727
728/// The configuration as settings: every key, set or default.
729#[must_use]
730pub fn read(root: &Path) -> ConfigReport {
731    let dir = home(root);
732    let path = dir.join(FILE);
733    let text = std::fs::read_to_string(&path).ok();
734    let table: toml::Table = text
735        .as_deref()
736        .and_then(|t| toml::from_str(t).ok())
737        .unwrap_or_default();
738    let sections = CATALOGUE
739        .iter()
740        .map(|s| {
741            if s.named {
742                let tables = table
743                    .get(s.name)
744                    .and_then(toml::Value::as_table)
745                    .map(|named| {
746                        named
747                            .iter()
748                            .map(|(name, t)| ConfigTable {
749                                name: name.clone(),
750                                keys: s
751                                    .keys
752                                    .iter()
753                                    .map(|k| {
754                                        let v =
755                                            t.as_table().and_then(|t| t.get(k.key)).map(json_of);
756                                        key_view(k, v)
757                                    })
758                                    .collect(),
759                            })
760                            .collect()
761                    })
762                    .unwrap_or_default();
763                ConfigSection {
764                    name: s.name.to_owned(),
765                    title: s.title.to_owned(),
766                    about: s.about.to_owned(),
767                    named: true,
768                    keys: s.keys.iter().map(|k| key_view(k, None)).collect(),
769                    tables,
770                }
771            } else {
772                ConfigSection {
773                    name: s.name.to_owned(),
774                    title: s.title.to_owned(),
775                    about: s.about.to_owned(),
776                    named: false,
777                    keys: s
778                        .keys
779                        .iter()
780                        .map(|k| {
781                            let mut path = vec![s.name];
782                            path.extend(k.key.split('.'));
783                            key_view(k, lookup(&table, &path).map(json_of))
784                        })
785                        .collect(),
786                    tables: Vec::new(),
787                }
788            }
789        })
790        .collect();
791    let error = text.as_deref().and_then(|t| validate(t).err());
792    let (committed, diff) = state(&dir, text.is_some());
793    ConfigReport {
794        file: FILE.to_owned(),
795        exists: text.is_some(),
796        committed,
797        valid: text.is_some() && error.is_none(),
798        error,
799        sections,
800        diff,
801    }
802}
803
804/// Whether the file on disk is the committed one, and the change if not.
805fn state(dir: &Path, exists: bool) -> (bool, Option<String>) {
806    let g = Git::at(dir);
807    let tracked = g
808        .succeeds(&["ls-files", "--error-unmatch", "--", FILE])
809        .unwrap_or(false);
810    if !tracked {
811        let diff = exists.then(|| {
812            std::fs::read_to_string(dir.join(FILE))
813                .unwrap_or_default()
814                .lines()
815                .map(|l| format!("+{l}"))
816                .collect::<Vec<_>>()
817                .join("\n")
818        });
819        return (
820            false,
821            diff.map(|d| {
822                format!("diff --git a/{FILE} b/{FILE}\nnew file mode 100644\n@@ -0,0 +1 @@\n{d}\n")
823            }),
824        );
825    }
826    let clean = g
827        .succeeds(&["diff", "--quiet", "HEAD", "--", FILE])
828        .unwrap_or(false);
829    if clean {
830        return (true, None);
831    }
832    let diff = g
833        .run(&["diff", "--no-color", "HEAD", "--", FILE])
834        .map(|b| String::from_utf8_lossy(&b).into_owned())
835        .ok();
836    (false, diff)
837}
838
839/// Where a dotted key lives: the table path and the leaf, with its catalogue
840/// entry.
841struct Place {
842    tables: Vec<String>,
843    leaf: String,
844    key: &'static Key,
845}
846
847fn place(dotted: &str) -> Result<Place, String> {
848    let parts: Vec<&str> = dotted.split('.').collect();
849    let Some(section) = parts
850        .first()
851        .and_then(|s| CATALOGUE.iter().find(|c| c.name == *s))
852    else {
853        if parts.first() == Some(&"ui") {
854            return Err("[ui] is a person's setting, not the project's: it belongs in ~/.config/speccoder/config.toml".to_owned());
855        }
856        return Err(format!(
857            "unknown section in `{dotted}` (known: {})",
858            CATALOGUE
859                .iter()
860                .map(|c| c.name)
861                .collect::<Vec<_>>()
862                .join(", ")
863        ));
864    };
865    let (tables, rest): (Vec<String>, &[&str]) = if section.named {
866        let Some(name) = parts.get(1) else {
867            return Err(format!(
868                "`{dotted}`: name the table, e.g. {}.<name>.<key>",
869                section.name
870            ));
871        };
872        if name.is_empty()
873            || !name
874                .chars()
875                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
876        {
877            return Err(format!(
878                "`{name}`: a table name is lowercase letters, digits, - and _"
879            ));
880        }
881        (
882            vec![section.name.to_owned(), (*name).to_owned()],
883            &parts[2..],
884        )
885    } else {
886        (vec![section.name.to_owned()], &parts[1..])
887    };
888    let wanted = rest.join(".");
889    let key = section
890        .keys
891        .iter()
892        .find(|k| k.key == wanted)
893        .ok_or_else(|| {
894            format!(
895                "unknown key `{dotted}` (in [{}]: {})",
896                section.name,
897                section
898                    .keys
899                    .iter()
900                    .map(|k| k.key)
901                    .collect::<Vec<_>>()
902                    .join(", ")
903            )
904        })?;
905    let mut tables = tables;
906    let mut leaf = wanted.clone();
907    if let Some((sub, last)) = wanted.rsplit_once('.') {
908        tables.extend(sub.split('.').map(str::to_owned));
909        leaf = last.to_owned();
910    }
911    Ok(Place { tables, leaf, key })
912}
913
914/// Checks `value` against `kind` before any parser sees it, for a message
915/// that names the key.
916fn check(dotted: &str, kind: Kind, value: &Value) -> Result<(), String> {
917    let strings = |v: &Value| v.as_array().is_some_and(|a| a.iter().all(Value::is_string));
918    let ok = match kind {
919        Kind::Bool => value.is_boolean(),
920        Kind::Int(a, b) => value.as_i64().is_some_and(|n| (a..=b).contains(&n)),
921        Kind::Num(a, b) => value.as_f64().is_some_and(|n| n >= a && n <= b),
922        Kind::Str => value.as_str().is_some_and(|s| !s.is_empty()),
923        Kind::Choice(c) => value.as_str().is_some_and(|s| c.contains(&s)),
924        Kind::Duration => value.as_str().is_some_and(|s| {
925            // The unit is the last character, which may be more than a byte.
926            let (n, u) = s.split_at(s.char_indices().last().map_or(0, |(i, _)| i));
927            n.parse::<u64>().is_ok_and(|n| n > 0) && ["m", "h", "d"].contains(&u)
928        }),
929        Kind::Argv => strings(value) && value.as_array().is_some_and(|a| !a.is_empty()),
930        Kind::ArgvList => value.as_array().is_some_and(|a| {
931            a.iter()
932                .all(|x| strings(x) && x.as_array().is_some_and(|i| !i.is_empty()))
933        }),
934        Kind::StrList => strings(value),
935    };
936    if ok {
937        return Ok(());
938    }
939    let want = match kind {
940        Kind::Bool => "true or false".to_owned(),
941        Kind::Int(a, b) => format!("a whole number from {a} to {b}"),
942        Kind::Num(a, b) => format!("a number from {a} to {b}"),
943        Kind::Str => "text".to_owned(),
944        Kind::Choice(c) => format!("one of {}", c.join(", ")),
945        Kind::Duration => "a duration like 30m, 12h or 7d".to_owned(),
946        Kind::Argv => "a program and its arguments, e.g. [\"cargo\", \"fmt\"]".to_owned(),
947        Kind::ArgvList => {
948            "a list of programs with arguments, e.g. [[\"cargo\", \"check\"]]".to_owned()
949        }
950        Kind::StrList => "a list of strings".to_owned(),
951    };
952    Err(format!("`{dotted}` = {value}: expected {want}"))
953}
954
955fn toml_value(v: &Value) -> Option<toml_edit::Value> {
956    Some(match v {
957        Value::Bool(b) => toml_edit::Value::from(*b),
958        Value::Number(n) => match n.as_i64() {
959            Some(i) => toml_edit::Value::from(i),
960            None => toml_edit::Value::from(n.as_f64()?),
961        },
962        Value::String(s) => toml_edit::Value::from(s.as_str()),
963        Value::Array(a) => {
964            let mut arr = toml_edit::Array::new();
965            for x in a {
966                arr.push(toml_value(x)?);
967            }
968            toml_edit::Value::Array(arr)
969        }
970        Value::Null | Value::Object(_) => return None,
971    })
972}
973
974/// The table at `path` — a `[table]` or an inline `{ … }` — made when
975/// missing and `create`; `None` when missing and not. The containers of
976/// named tables (`[checks]`, `[mcp]`) are implicit: no header of their own.
977fn table_mut<'a>(
978    doc: &'a mut toml_edit::DocumentMut,
979    path: &[String],
980    create: bool,
981) -> Result<Option<&'a mut dyn toml_edit::TableLike>, String> {
982    let mut t: &mut dyn toml_edit::TableLike = doc.as_table_mut();
983    let mut inline = false;
984    for (i, p) in path.iter().enumerate() {
985        if t.get(p).is_none() {
986            if !create {
987                return Ok(None);
988            }
989            let fresh = if inline {
990                // Inside an inline table, what is made is inline too.
991                toml_edit::Item::Value(toml_edit::Value::InlineTable(toml_edit::InlineTable::new()))
992            } else {
993                let mut table = toml_edit::Table::new();
994                let container = i == 0 && CATALOGUE.iter().any(|c| c.named && c.name == p);
995                table.set_implicit(container || i + 1 < path.len());
996                toml_edit::Item::Table(table)
997            };
998            t.insert(p, fresh);
999        }
1000        let Some(item) = t.get_mut(p) else {
1001            return Err(format!("`{}` could not be made", path[..=i].join(".")));
1002        };
1003        inline = inline || item.is_inline_table();
1004        t = item
1005            .as_table_like_mut()
1006            .ok_or_else(|| format!("`{}` is not a table", path[..=i].join(".")))?;
1007    }
1008    Ok(Some(t))
1009}
1010
1011/// Removes empty tables (or inline tables) left behind by an unset,
1012/// innermost first.
1013fn prune(doc: &mut toml_edit::DocumentMut, path: &[String]) {
1014    for depth in (1..=path.len()).rev() {
1015        let (parent, last) = (&path[..depth - 1], &path[depth - 1]);
1016        let Ok(Some(t)) = table_mut(doc, parent, false) else {
1017            return;
1018        };
1019        let empty = t
1020            .get(last)
1021            .and_then(toml_edit::Item::as_table_like)
1022            .is_some_and(toml_edit::TableLike::is_empty);
1023        if empty {
1024            t.remove(last);
1025        }
1026    }
1027}
1028
1029/// The new text with `changes` applied, or why not.
1030///
1031/// # Errors
1032///
1033/// An unknown key, a value of the wrong kind, or a result a parser refuses.
1034pub fn edit(text: &str, changes: &[ConfigChange]) -> Result<String, String> {
1035    let mut doc: toml_edit::DocumentMut = text
1036        .parse()
1037        .map_err(|e: toml_edit::TomlError| e.to_string())?;
1038    for c in changes {
1039        let at = place(&c.key)?;
1040        match (&c.value, &c.append) {
1041            (Some(v), None) => {
1042                check(&c.key, at.key.kind, v)?;
1043                let value = toml_value(v)
1044                    .ok_or_else(|| format!("`{}`: a value TOML cannot hold", c.key))?;
1045                let t = table_mut(&mut doc, &at.tables, true)?
1046                    .ok_or_else(|| format!("`{}` could not be made", c.key))?;
1047                match t.get_mut(&at.leaf).and_then(toml_edit::Item::as_value_mut) {
1048                    // Keep the key's own comment and spacing.
1049                    Some(old) => {
1050                        let decor = old.decor().clone();
1051                        *old = value;
1052                        *old.decor_mut() = decor;
1053                    }
1054                    None => {
1055                        t.insert(&at.leaf, toml_edit::value(value));
1056                    }
1057                }
1058            }
1059            (None, Some(item)) => {
1060                if !matches!(at.key.kind, Kind::ArgvList | Kind::StrList) {
1061                    return Err(format!("`{}` is not a list", c.key));
1062                }
1063                // The list as it is now, read back through the parser.
1064                let now: toml::Table = toml::from_str(&doc.to_string()).unwrap_or_default();
1065                let mut path: Vec<&str> = at.tables.iter().map(String::as_str).collect();
1066                path.push(&at.leaf);
1067                let mut list: Vec<Value> = lookup(&now, &path)
1068                    .map(json_of)
1069                    .and_then(|v| v.as_array().cloned())
1070                    .unwrap_or_default();
1071                if !list.contains(item) {
1072                    list.push(item.clone());
1073                }
1074                let all = Value::Array(list);
1075                check(&c.key, at.key.kind, &all)?;
1076                let value = toml_value(&all)
1077                    .ok_or_else(|| format!("`{}`: a value TOML cannot hold", c.key))?;
1078                table_mut(&mut doc, &at.tables, true)?
1079                    .ok_or_else(|| format!("`{}` could not be made", c.key))?
1080                    .insert(&at.leaf, toml_edit::value(value));
1081            }
1082            (None, None) => {
1083                // Missing is already unset; anything else in the way is an error.
1084                if let Some(t) = table_mut(&mut doc, &at.tables, false)? {
1085                    t.remove(&at.leaf);
1086                }
1087                prune(&mut doc, &at.tables);
1088            }
1089            (Some(_), Some(_)) => {
1090                return Err(format!(
1091                    "`{}`: set a value or append to it, not both",
1092                    c.key
1093                ));
1094            }
1095        }
1096    }
1097    let out = doc.to_string();
1098    validate(&out)?;
1099    Ok(out)
1100}
1101
1102/// `speccoder config`: the settings.
1103#[must_use]
1104pub fn show(root: &Path) -> CommandResult {
1105    let report = read(root);
1106    let message = match (&report.exists, &report.error, report.committed) {
1107        (false, _, _) => "no speccoder.toml yet: every key has its default".to_owned(),
1108        (true, Some(e), _) => format!("speccoder.toml has an error: {e}"),
1109        (true, None, false) => {
1110            "speccoder.toml has changes that are not committed (not in force yet)".to_owned()
1111        }
1112        (true, None, true) => "speccoder.toml".to_owned(),
1113    };
1114    let result = CommandResult::new("config", CommandStatus::Ok, &message);
1115    let result = if report.committed || !report.exists {
1116        result
1117    } else {
1118        result.with_next(vec![speccoder_core::next::NextStep {
1119            command: "speccoder config commit".to_owned(),
1120            why: "speccoder reads committed configuration only".to_owned(),
1121        }])
1122    };
1123    result.with_data(CommandData::Config(Box::new(report)))
1124}
1125
1126/// The keys only a coverage preview's confirmation writes.
1127pub const PREFIX_KEYS: [&str; 2] = ["commands.allow_prefix", "sandbox.network_allow_prefix"];
1128
1129/// `speccoder config set|unset`, and the page's save: applies `changes` to
1130/// the file, all or nothing. A prefix key is refused: it is saved only as
1131/// the confirmation of its coverage preview (`WidenPolicy`); removing an
1132/// entry (`unset`) narrows and is allowed.
1133#[must_use]
1134pub fn apply(root: &Path, changes: &[ConfigChange]) -> CommandResult {
1135    if let Some(c) = changes.iter().find(|c| {
1136        PREFIX_KEYS.contains(&c.key.as_str()) && (c.value.is_some() || c.append.is_some())
1137    }) {
1138        // Setting the list to fewer entries than it has narrows it.
1139        let narrows = c.value.as_ref().is_some_and(|v| {
1140            let now = read(root);
1141            let current = now
1142                .sections
1143                .iter()
1144                .flat_map(|s| {
1145                    s.keys
1146                        .iter()
1147                        .map(move |k| (format!("{}.{}", s.name, k.key), k))
1148                })
1149                .find(|(name, _)| *name == c.key)
1150                .and_then(|(_, k)| k.value.clone())
1151                .and_then(|v| v.as_array().cloned())
1152                .unwrap_or_default();
1153            v.as_array()
1154                .is_some_and(|new| new.iter().all(|e| current.contains(e)))
1155        });
1156        if !narrows {
1157            return CommandResult::new(
1158                "config",
1159                CommandStatus::UsageError,
1160                &format!(
1161                    "`{}` is saved only from its coverage preview: `speccoder config coverage {} <argv…>`, then confirm",
1162                    c.key, c.key
1163                ),
1164            )
1165            .with_code("CONFIG-INVALID");
1166        }
1167    }
1168    apply_confirmed(root, changes)
1169}
1170
1171/// [`apply`] without the prefix guard: for the confirmation of a coverage
1172/// preview and for Always Allow's exact entry, which their actions checked.
1173#[must_use]
1174pub(crate) fn apply_confirmed(root: &Path, changes: &[ConfigChange]) -> CommandResult {
1175    let dir = home(root);
1176    let path = dir.join(FILE);
1177    let text = std::fs::read_to_string(&path).unwrap_or_default();
1178    match edit(&text, changes) {
1179        Err(e) => CommandResult::new("config", CommandStatus::ConfigError, &e)
1180            .with_code("CONFIG-INVALID")
1181            .with_fix(vec![format!(
1182                "speccoder config get {}",
1183                changes.first().map_or("", |c| c.key.as_str())
1184            )]),
1185        Ok(out) if out == text => show(root),
1186        Ok(out) => match std::fs::write(&path, out) {
1187            Ok(()) => {
1188                let keys: Vec<&str> = changes.iter().map(|c| c.key.as_str()).collect();
1189                let r = show(root);
1190                CommandResult::new(
1191                    "config",
1192                    CommandStatus::Ok,
1193                    &format!("changed {} — commit it to put it in force", keys.join(", ")),
1194                )
1195                .with_next(vec![speccoder_core::next::NextStep {
1196                    command: "speccoder config commit".to_owned(),
1197                    why: "speccoder reads committed configuration only".to_owned(),
1198                }])
1199                .with_data(
1200                    r.data()
1201                        .cloned()
1202                        .unwrap_or(CommandData::Config(Box::new(read(root)))),
1203                )
1204            }
1205            Err(e) => CommandResult::new(
1206                "config",
1207                CommandStatus::Error,
1208                &format!("{}: {e}", path.display()),
1209            ),
1210        },
1211    }
1212}
1213
1214/// `speccoder config commit`: commits exactly `speccoder.toml`, nothing else
1215/// staged, once every parser accepts it.
1216#[must_use]
1217pub fn commit(root: &Path) -> CommandResult {
1218    let dir = home(root);
1219    let text = match std::fs::read_to_string(dir.join(FILE)) {
1220        Ok(t) => t,
1221        Err(_) => {
1222            return CommandResult::new(
1223                "config",
1224                CommandStatus::ConfigError,
1225                "there is no speccoder.toml to commit",
1226            )
1227            .with_code("CONFIG-MISSING");
1228        }
1229    };
1230    if let Err(e) = validate(&text) {
1231        return CommandResult::new("config", CommandStatus::ConfigError, &e)
1232            .with_code("CONFIG-INVALID");
1233    }
1234    let (committed, _) = state(&dir, true);
1235    if committed {
1236        return CommandResult::new(
1237            "config",
1238            CommandStatus::Ok,
1239            "speccoder.toml is committed; nothing to do",
1240        );
1241    }
1242    // Which sections changed, for the message.
1243    let g = Git::at(&dir);
1244    let before: toml::Table = g
1245        .run(&["show", &format!("HEAD:./{FILE}")])
1246        .ok()
1247        .and_then(|b| toml::from_str(&String::from_utf8_lossy(&b)).ok())
1248        .unwrap_or_default();
1249    let after: toml::Table = toml::from_str(&text).unwrap_or_default();
1250    let mut changed: Vec<&str> = CATALOGUE
1251        .iter()
1252        .map(|s| s.name)
1253        .filter(|s| before.get(*s) != after.get(*s))
1254        .collect();
1255    changed.dedup();
1256    let message = if changed.is_empty() {
1257        "speccoder: configuration".to_owned()
1258    } else {
1259        format!("speccoder: configuration ({})", changed.join(", "))
1260    };
1261    match g
1262        .run(&["add", "--", FILE])
1263        .and_then(|_| g.run(&["commit", "-q", "-m", &message, "--", FILE]))
1264    {
1265        Ok(_) => {
1266            let id = g
1267                .line(&["rev-parse", "--short", "HEAD"])
1268                .unwrap_or_default();
1269            CommandResult::new(
1270                "config",
1271                CommandStatus::Ok,
1272                &format!("committed speccoder.toml as {id} \"{message}\""),
1273            )
1274            .with_data(CommandData::Config(Box::new(read(root))))
1275        }
1276        Err(e) => CommandResult::new(
1277            "config",
1278            CommandStatus::GitPrecondition,
1279            &format!("commit failed: {}", e.0),
1280        ),
1281    }
1282}
1283
1284/// A value for `key` from the words of `config set KEY WORDS…`: JSON when it
1285/// parses as the key's kind, else words read by the kind (`cargo fmt` for an
1286/// argv, `40` for a number, `on`/`off` for a switch).
1287///
1288/// # Errors
1289///
1290/// An unknown key, or words that are no value of its kind.
1291pub fn value_of(key: &str, words: &[String]) -> Result<Value, String> {
1292    let at = place(key)?;
1293    let joined = words.join(" ");
1294    if let Ok(v) = serde_json::from_str::<Value>(&joined)
1295        && check(key, at.key.kind, &v).is_ok()
1296    {
1297        return Ok(v);
1298    }
1299    let v = match at.key.kind {
1300        Kind::Bool => match joined.as_str() {
1301            "true" | "on" | "yes" => json!(true),
1302            "false" | "off" | "no" => json!(false),
1303            _ => json!(joined),
1304        },
1305        Kind::Int(..) => joined
1306            .parse::<i64>()
1307            .map_or_else(|_| json!(joined), |n| json!(n)),
1308        Kind::Num(..) => joined
1309            .parse::<f64>()
1310            .map_or_else(|_| json!(joined), |n| json!(n)),
1311        Kind::Argv | Kind::StrList => json!(words),
1312        Kind::ArgvList => json!([words]),
1313        Kind::Str | Kind::Choice(_) | Kind::Duration => json!(joined),
1314    };
1315    check(key, at.key.kind, &v).map(|()| v)
1316}
1317
1318#[cfg(test)]
1319mod tests {
1320    use super::*;
1321
1322    /// A value of `kind` the parsers accept, for the drift test.
1323    fn sample(k: &Key) -> Value {
1324        if let Some(d) = k.default
1325            && let Ok(v) = serde_json::from_str::<Value>(d)
1326        {
1327            return v;
1328        }
1329        match k.kind {
1330            Kind::Bool => json!(true),
1331            Kind::Int(a, _) => json!(a.max(1)),
1332            Kind::Num(a, b) => json!(f64::midpoint(a, b).min(1.0)),
1333            Kind::Str => json!("x"),
1334            Kind::Choice(c) => json!(c[0]),
1335            Kind::Duration => json!("7d"),
1336            Kind::Argv => json!(["true"]),
1337            Kind::ArgvList => json!([["cargo", "check"]]),
1338            Kind::StrList => json!(["x"]),
1339        }
1340    }
1341
1342    /// The smallest configuration that holds `section` with `key` set.
1343    fn with(section: &Section, key: &Key) -> Vec<ConfigChange> {
1344        let prefix = if section.named {
1345            format!("{}.t", section.name)
1346        } else {
1347            section.name.to_owned()
1348        };
1349        let mut changes: Vec<ConfigChange> = section
1350            .keys
1351            .iter()
1352            .filter(|r| r.required && r.key != key.key)
1353            .map(|r| ConfigChange {
1354                key: format!("{prefix}.{}", r.key),
1355                value: Some(sample(r)),
1356                append: None,
1357            })
1358            .collect();
1359        changes.push(ConfigChange {
1360            key: format!("{prefix}.{}", key.key),
1361            value: Some(sample(key)),
1362            append: None,
1363        });
1364        // `argv`, `report` and `acceptance_argv` belong to a command tool,
1365        // which needs its program and report; the rest to cargo-mutants.
1366        if section.name == "mutation" {
1367            let set = |key: &str, value: Value| ConfigChange {
1368                key: key.into(),
1369                value: Some(value),
1370                append: None,
1371            };
1372            if ["argv", "report", "acceptance_argv"].contains(&key.key) {
1373                changes.retain(|c| c.key != "mutation.tool");
1374                changes.insert(0, set("mutation.tool", json!("command")));
1375                for (k, v) in [
1376                    ("mutation.argv", json!(["mutants", "{out}"])),
1377                    ("mutation.report", json!("report.json")),
1378                ] {
1379                    if !changes.iter().any(|c| c.key == k) {
1380                        changes.insert(1, set(k, v));
1381                    }
1382                }
1383            } else {
1384                changes.retain(|c| c.key != "mutation.tool" || key.key == "tool");
1385                if key.key != "tool" {
1386                    changes.insert(0, set("mutation.tool", json!("cargo-mutants")));
1387                }
1388            }
1389        }
1390        if section.name == "executor" && key.key == "argv" {
1391            changes.retain(|c| c.key != "executor.kind");
1392            changes.insert(
1393                0,
1394                ConfigChange {
1395                    key: "executor.kind".into(),
1396                    value: Some(json!("command")),
1397                    append: None,
1398                },
1399            );
1400        }
1401        if section.name == "model" && key.key == "base_url" {
1402            changes.push(ConfigChange {
1403                key: "model.provider".into(),
1404                value: Some(json!("openai-compatible")),
1405                append: None,
1406            });
1407        }
1408        changes
1409    }
1410
1411    #[test]
1412    fn every_catalogued_key_is_accepted_by_the_parsers() {
1413        for s in CATALOGUE {
1414            for k in s.keys {
1415                let changes = with(s, k);
1416                edit("", &changes).unwrap_or_else(|e| panic!("[{}] {}: {e}", s.name, k.key));
1417            }
1418        }
1419    }
1420
1421    #[test]
1422    fn every_key_in_the_reference_is_catalogued() {
1423        let doc = std::fs::read_to_string(
1424            Path::new(env!("CARGO_MANIFEST_DIR")).join("../../site/content/docs/configuration.md"),
1425        )
1426        .unwrap_or_default();
1427        assert!(!doc.is_empty(), "the configuration reference is missing");
1428        let mut section: Option<String> = None;
1429        let mut missing = Vec::new();
1430        for line in doc.lines() {
1431            if line.starts_with("## ") {
1432                // `## \`[model]\`` sets the section; a heading naming several
1433                // (or none) leaves rows to name their own.
1434                let names: Vec<&str> = line.split('`').skip(1).step_by(2).collect();
1435                section = (names.len() == 1).then(|| {
1436                    names[0]
1437                        .trim_matches(['[', ']'])
1438                        .split('.')
1439                        .next()
1440                        .unwrap_or("")
1441                        .to_owned()
1442                });
1443                if line.contains("Your settings") {
1444                    break;
1445                }
1446                continue;
1447            }
1448            let Some(cell) = line.strip_prefix("| ").and_then(|l| l.split(" |").next()) else {
1449                continue;
1450            };
1451            if cell.starts_with("Key") || cell.starts_with("---") {
1452                continue;
1453            }
1454            let mut prefix = section.clone().map(|s| vec![s]).unwrap_or_default();
1455            for token in cell.split('`').skip(1).step_by(2) {
1456                let key = match token.strip_prefix('[').and_then(|t| t.split_once("] ")) {
1457                    Some((table, key)) => {
1458                        prefix = table.split('.').map(str::to_owned).collect();
1459                        key.to_owned()
1460                    }
1461                    None => token.to_owned(),
1462                };
1463                let mut path = prefix.clone();
1464                if CATALOGUE
1465                    .iter()
1466                    .any(|c| c.named && Some(&c.name.to_owned()) == prefix.first())
1467                {
1468                    path.insert(1, "t".to_owned());
1469                }
1470                path.push(key);
1471                let dotted = path.join(".");
1472                if place(&dotted).is_err() {
1473                    missing.push(dotted);
1474                }
1475            }
1476        }
1477        assert!(
1478            missing.is_empty(),
1479            "documented but not catalogued: {missing:?}"
1480        );
1481    }
1482
1483    #[test]
1484    fn an_edit_keeps_comments_and_refuses_what_a_parser_refuses() {
1485        let text = "# The project's checks.\n[checks.test]\nargv = [\"cargo\", \"test\"] # all of them\n\n# How much an attempt may do.\n[budget]\nmax_turns = 30 # plenty\n";
1486        let out = edit(
1487            text,
1488            &[ConfigChange {
1489                key: "budget.max_turns".into(),
1490                value: Some(json!(40)),
1491                append: None,
1492            }],
1493        )
1494        .unwrap();
1495        assert!(out.contains("# The project's checks."), "{out}");
1496        assert!(out.contains("# How much an attempt may do."), "{out}");
1497        assert!(out.contains("max_turns = 40 # plenty"), "{out}");
1498        assert!(
1499            out.contains("argv = [\"cargo\", \"test\"] # all of them"),
1500            "{out}"
1501        );
1502        // Out of range, unknown, the wrong kind: nothing is written.
1503        for (key, value) in [
1504            ("budget.max_turns", json!(0)),
1505            ("budget.max_turn", json!(3)),
1506            ("sandbox.mode", json!("maybe")),
1507            ("ui.theme", json!("dark")),
1508        ] {
1509            assert!(
1510                edit(
1511                    text,
1512                    &[ConfigChange {
1513                        key: key.into(),
1514                        value: Some(value),
1515                        append: None
1516                    }]
1517                )
1518                .is_err(),
1519                "{key}"
1520            );
1521        }
1522        // Unset removes the key and an emptied table.
1523        let out = edit(
1524            text,
1525            &[ConfigChange {
1526                key: "budget.max_turns".into(),
1527                value: None,
1528                append: None,
1529            }],
1530        )
1531        .unwrap();
1532        assert!(!out.contains("[budget]"), "{out}");
1533        // Append adds once.
1534        let allow = ConfigChange {
1535            key: "commands.allow".into(),
1536            value: None,
1537            append: Some(json!(["cargo", "fetch"])),
1538        };
1539        let once = edit(text, std::slice::from_ref(&allow)).unwrap();
1540        let twice = edit(&once, &[allow]).unwrap();
1541        assert_eq!(once, twice);
1542        assert!(once.contains("allow = [[\"cargo\", \"fetch\"]]"), "{once}");
1543        // A named table is made under an implicit container.
1544        let out = edit(
1545            "",
1546            &[ConfigChange {
1547                key: "checks.lint.argv".into(),
1548                value: Some(json!(["cargo", "clippy"])),
1549                append: None,
1550            }],
1551        )
1552        .unwrap();
1553        assert!(
1554            out.contains("[checks.lint]") && !out.contains("[checks]\n"),
1555            "{out}"
1556        );
1557    }
1558
1559    /// A unit of more than one byte is refused, never a panic (it aborted
1560    /// the web host).
1561    #[test]
1562    fn a_multibyte_unit_is_refused_not_a_panic() {
1563        let w = |s: &str| vec![s.to_owned()];
1564        for bad in ["7д", "1€", "д", "€"] {
1565            assert!(value_of("approvals.wait", &w(bad)).is_err(), "{bad}");
1566        }
1567        assert!(crate::substrate::run_config::parse("[approvals]\nwait = \"7д\"\n").is_err());
1568    }
1569
1570    /// Inline tables are tables: a key in one is set and unset like any.
1571    #[test]
1572    fn inline_tables_are_edited_not_skipped() {
1573        let text = "[attest]\nsigstore = { identity = \"a@b\", issuer = \"https://x\" }\n\n[checks]\nlint = { argv = [\"cargo\", \"clippy\"] }\n";
1574        let unset = |k: &str| ConfigChange {
1575            key: k.into(),
1576            value: None,
1577            append: None,
1578        };
1579        let set = |k: &str, v: Value| ConfigChange {
1580            key: k.into(),
1581            value: Some(v),
1582            append: None,
1583        };
1584        let out =
1585            edit(text, &[unset("attest.sigstore.identity")]).unwrap_or_else(|e| panic!("{e}"));
1586        assert!(!out.contains("a@b") && out.contains("issuer"), "{out}");
1587        let out =
1588            edit(text, &[set("checks.lint.tier", json!("full"))]).unwrap_or_else(|e| panic!("{e}"));
1589        assert!(out.contains("tier = \"full\""), "{out}");
1590        let out = edit(
1591            text,
1592            &[
1593                unset("attest.sigstore.identity"),
1594                unset("attest.sigstore.issuer"),
1595            ],
1596        )
1597        .unwrap_or_else(|e| panic!("{e}"));
1598        assert!(!out.contains("sigstore"), "{out}");
1599    }
1600
1601    #[test]
1602    fn words_become_values_of_the_key_s_kind() {
1603        let w = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1604        assert_eq!(value_of("budget.max_turns", &w("40")).unwrap(), json!(40));
1605        assert_eq!(value_of("monitor.enabled", &w("on")).unwrap(), json!(true));
1606        assert_eq!(
1607            value_of("format.argv", &w("cargo fmt")).unwrap(),
1608            json!(["cargo", "fmt"])
1609        );
1610        assert_eq!(
1611            value_of("commands.allow", &w("cargo check")).unwrap(),
1612            json!([["cargo", "check"]])
1613        );
1614        assert_eq!(value_of("approvals.wait", &w("2d")).unwrap(), json!("2d"));
1615        assert!(value_of("budget.max_turns", &w("lots")).is_err());
1616    }
1617}