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