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