magi/config.rs
1//! Run configuration: the agent roster, the shape of the graph, and the
2//! blindness / verification policy.
3//!
4//! Discovery order (first hit wins):
5//!
6//! 1. `--config <path>`
7//! 2. `<repo>/magi.toml`
8//! 3. `<repo>/.magi/config.toml`
9//! 4. `<config_dir>/magi/config.toml`
10//! 5. built-in defaults, with the agent roster derived from the agent CLIs
11//! actually installed on this machine
12use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15use anyhow::{Context as _, Result, bail};
16use serde::{Deserialize, Serialize};
17
18/// Which CLI drives an agent.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
20#[serde(rename_all = "lowercase")]
21pub enum AgentKind {
22 /// Anthropic Claude Code (`claude -p`).
23 Claude,
24 /// opencode (`opencode run`).
25 Opencode,
26 /// Antigravity CLI (`agy -p`). Gemini CLI is deliberately absent: Google
27 /// retired the standalone client for individual accounts in favour of this
28 /// one, so an adapter for it would be dead code on a live machine.
29 Antigravity,
30 /// OpenAI Codex CLI (`codex exec`). The one roster member with a real
31 /// read-only mode: `--sandbox read-only` is enforced by the CLI, not by
32 /// the prompt.
33 Codex,
34 /// Arbitrary command. The escape hatch, and what the test suite drives.
35 Command,
36}
37
38impl AgentKind {
39 /// Executable that must be on `PATH` for this kind, if any.
40 pub fn program(self) -> Option<&'static str> {
41 match self {
42 Self::Claude => Some("claude"),
43 Self::Opencode => Some("opencode"),
44 Self::Antigravity => Some("agy"),
45 Self::Codex => Some("codex"),
46 Self::Command => None,
47 }
48 }
49
50 /// Lowercase name as written in the config file.
51 pub fn as_str(self) -> &'static str {
52 match self {
53 Self::Claude => "claude",
54 Self::Opencode => "opencode",
55 Self::Antigravity => "antigravity",
56 Self::Codex => "codex",
57 Self::Command => "command",
58 }
59 }
60}
61
62/// How the prompt reaches the agent process.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
64#[serde(rename_all = "lowercase")]
65pub enum Delivery {
66 /// Piped on stdin.
67 Stdin,
68 /// Passed as a positional argument. Beware OS command-line limits.
69 Argv,
70 /// Written to a file; the agent is told to read it. No length limit.
71 File,
72}
73
74/// One addressable agent in the roster.
75#[derive(Debug, Clone, Deserialize, Serialize)]
76#[serde(deny_unknown_fields)]
77pub struct AgentSpec {
78 /// Stable identifier used by `[roles]` and by the stats tables.
79 pub id: String,
80 /// Which CLI to drive.
81 pub kind: AgentKind,
82 /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
83 #[serde(default)]
84 pub model: Option<String>,
85 /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
86 /// `{label}`, `{session}` placeholders.
87 #[serde(default)]
88 pub command: Vec<String>,
89 /// Extra arguments appended to the built command line.
90 #[serde(default)]
91 pub extra_args: Vec<String>,
92 /// Extra environment variables for the child process.
93 #[serde(default)]
94 pub env: BTreeMap<String, String>,
95 /// Override the per-kind prompt delivery default.
96 #[serde(default)]
97 pub prompt_delivery: Option<Delivery>,
98}
99
100impl AgentSpec {
101 /// Default prompt delivery for this agent.
102 ///
103 /// `opencode` and `agy` take the prompt as an argument, which on Windows
104 /// caps out around 32 KiB — well under a judging prompt carrying three
105 /// patches — so both get a file instead.
106 pub fn delivery(&self) -> Delivery {
107 self.prompt_delivery.unwrap_or(match self.kind {
108 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
109 // `codex exec -` reads the prompt from stdin, so the whole
110 // instruction arrives without an argv length limit and without a
111 // tool round-trip to open a file.
112 AgentKind::Codex => Delivery::Stdin,
113 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
114 })
115 }
116
117 /// Human-facing label, e.g. `opus (claude:opus)`.
118 pub fn display(&self) -> String {
119 match &self.model {
120 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
121 None => format!("{} ({})", self.id, self.kind.as_str()),
122 }
123 }
124}
125
126/// Explicit role assignment. Empty lists are filled in by
127/// [`Config::resolve_roles`] by rotating the roster.
128#[derive(Debug, Clone, Default, Deserialize, Serialize)]
129#[serde(deny_unknown_fields, default)]
130pub struct Roles {
131 /// Agents that implement the task, one worktree each.
132 pub implementers: Vec<String>,
133 /// Agents that rank the candidates blind.
134 pub judges: Vec<String>,
135 /// Agents that review the winning patch.
136 pub reviewers: Vec<String>,
137 /// Agent that applies review findings. Defaults to the winner's author.
138 pub fixer: Option<String>,
139 /// Agent that runs the `magi plan` interview and the browser conversation.
140 ///
141 /// Unset picks a `claude` seat, else the first runnable agent in roster
142 /// order - which is roster *order*, not a judgement about who interviews
143 /// well. Naming one here is worth it because the interview is the one node
144 /// a human sits through: the model that asks good questions is not
145 /// necessarily the one that writes the best patch, and on a phone there is
146 /// no `--agent` to type.
147 pub planner: Option<String>,
148}
149
150/// Graph shape and limits.
151#[derive(Debug, Clone, Deserialize, Serialize)]
152#[serde(deny_unknown_fields, default)]
153pub struct Graph {
154 /// Parallel implementations of the same task. **One by default.**
155 ///
156 /// Competition is the thing magi is for, and it is still here - it is just
157 /// no longer what every task buys without being asked. Three days and 13
158 /// runs on this repository, which is the workload these numbers are drawn
159 /// from:
160 ///
161 /// - **0 of 13** competed runs reached a merge. Everything that landed in
162 /// that window went through `magi review` - the cheap half, no
163 /// competition - and passed on the first try.
164 /// - The judges' first choices **split 73% of the time** (8 of 11
165 /// tallies). Candidates that close together make the ranking a weak
166 /// signal for what it costs to produce.
167 /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
168 /// review 28min, **verify 5min** - and verify is the node that caught a
169 /// defect every reviewer had passed as clean. The cheapest step is the
170 /// one that earns its place every time.
171 ///
172 /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
173 /// single-seat default would have shipped the worse implementation in
174 /// roughly a quarter of them. That is exactly why this is a *default* and
175 /// not a removal - `magi run --candidates N` and a per-task seat count are
176 /// how a task that deserves a competition gets one.
177 ///
178 /// A single-candidate run needs no special case: `Runner::review`'s doc
179 /// records that `execute` already degrades to implement -> review -> gate
180 /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
181 /// no two first choices to reconcile and `vote` returns early.
182 pub candidates: usize,
183 /// Independent judges.
184 pub judges: usize,
185 /// Deliberation rounds when the judges' first choices disagree.
186 pub deliberate_rounds: usize,
187 /// Reviewers per review round.
188 pub reviewers: usize,
189 /// Maximum review+fix rounds before the run is declared blocked.
190 pub review_rounds: usize,
191 /// Maximum agent processes running at once.
192 pub max_parallel: usize,
193 /// Language for the prose the agents write (`en` / `ja` / any language name).
194 pub language: String,
195 /// Keep one CLI conversation per seat, so a judge remembers its own
196 /// argument across deliberation rounds and the fixer remembers its own
197 /// implementation across review rounds.
198 ///
199 /// Sessions are scoped to a *seat*, never to an agent id: the same model
200 /// sitting as implementer and as judge gets two unrelated conversations,
201 /// which is what keeps blind judging blind.
202 pub sessions: bool,
203 /// Per-node timeouts, seconds.
204 pub timeout_implement: u64,
205 /// Per-node timeouts, seconds.
206 pub timeout_judge: u64,
207 /// Per-node timeouts, seconds.
208 pub timeout_review: u64,
209 /// Per-node timeouts, seconds.
210 pub timeout_fix: u64,
211 /// Retries for an agent invocation that fails or returns nothing usable.
212 pub retries: usize,
213 /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
214 pub worktree_root: Option<PathBuf>,
215 /// After the pull request is open, keep going: watch its checks and
216 /// reviews, run a fix round when they are unhappy, and ask to merge.
217 ///
218 /// On, because stopping at an open pull request left the operator doing
219 /// the watching by hand - six times in the session this was built in - and
220 /// that is the work the loop exists to take. It only engages for
221 /// `merge = "pr"`; every other merge mode ends the run as before.
222 ///
223 /// Turning this on does **not** hand magi the merge button:
224 /// [`Graph::land_approval`] is on too, and nothing merges without an
225 /// explicit answer. Setting both to their non-defaults is the only way to
226 /// get an unattended merge, and it has to be chosen twice.
227 pub land: bool,
228 /// Land rounds - watch, fix, push - before the run is left for a human.
229 pub land_rounds: usize,
230 /// Ask the owner before merging, showing what is about to land.
231 ///
232 /// On, and it is what makes `land` safe to have on: the question carries a
233 /// rendered panel - the diffstat, the patch, the checks, the review
234 /// comments that were addressed, and the subject the squash will use - so
235 /// the decision is made on evidence rather than on trust, from wherever
236 /// the operator happens to be.
237 ///
238 /// Silence is a hold. An unanswered approval never merges, and neither
239 /// does any answer other than the word `merge`.
240 pub land_approval: bool,
241 /// How long to wait for an owner to answer a question before the run is
242 /// abandoned, seconds. A parked run costs nothing, so this is generous;
243 /// it exists so a forgotten question cannot pin a worktree forever.
244 pub answer_timeout: u64,
245}
246
247impl Default for Graph {
248 fn default() -> Self {
249 Self {
250 candidates: 1,
251 judges: 3,
252 deliberate_rounds: 1,
253 reviewers: 2,
254 review_rounds: 6,
255 max_parallel: 4,
256 language: "en".to_owned(),
257 sessions: true,
258 timeout_implement: 3600,
259 timeout_judge: 1200,
260 timeout_review: 1200,
261 timeout_fix: 1800,
262 retries: 1,
263 worktree_root: None,
264 land: true,
265 land_rounds: 4,
266 land_approval: true,
267 answer_timeout: 86_400,
268 }
269 }
270}
271
272/// What to do when vendor-identifying text is found in material shown to judges.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
274#[serde(rename_all = "lowercase")]
275pub enum LeakPolicy {
276 /// Record the leak, show the patch unmodified.
277 Warn,
278 /// Replace the token with `[REDACTED]` in the presented patch.
279 Redact,
280 /// Abort the run.
281 Fail,
282}
283
284/// Blindness policy.
285///
286/// Commit messages and candidate summaries are *always* stripped of
287/// attribution trailers and redacted — that is where signatures actually
288/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
289/// redaction would corrupt the artifact under judgement.
290#[derive(Debug, Clone, Deserialize, Serialize)]
291#[serde(deny_unknown_fields, default)]
292pub struct Blind {
293 /// Install a per-worktree `commit-msg` hook that deletes attribution
294 /// trailers before they can land in a candidate's history.
295 pub commit_msg_hook: bool,
296 /// Literal, case-insensitive substrings. A line containing any of them is
297 /// dropped from commit messages and summaries; the `commit-msg` hook is
298 /// generated from the same list.
299 pub strip_lines: Vec<String>,
300 /// Case-insensitive substrings that identify a vendor or model.
301 pub vendor_tokens: Vec<String>,
302 /// Policy for vendor tokens found in the patch body.
303 pub on_leak: LeakPolicy,
304 /// Seed for label assignment and per-judge presentation order. Derived from
305 /// the run id when unset; set it to make a run reproducible.
306 pub seed: Option<u64>,
307}
308
309impl Default for Blind {
310 fn default() -> Self {
311 Self {
312 commit_msg_hook: true,
313 strip_lines: [
314 "Co-Authored-By:",
315 "Signed-off-by:",
316 "Assisted-by:",
317 "Generated-by:",
318 "Generated with",
319 "\u{1f916}",
320 ]
321 .iter()
322 .map(|s| (*s).to_owned())
323 .collect(),
324 vendor_tokens: [
325 "claude",
326 "anthropic",
327 "codex",
328 "openai",
329 "chatgpt",
330 "gemini",
331 "grok",
332 "xai",
333 "copilot",
334 "opencode",
335 "qoder",
336 "cursor",
337 "\u{1f916}",
338 ]
339 .iter()
340 .map(|s| (*s).to_owned())
341 .collect(),
342 on_leak: LeakPolicy::Warn,
343 seed: None,
344 }
345 }
346}
347
348/// Shell commands that gate the winner.
349#[derive(Debug, Clone, Default, Deserialize, Serialize)]
350#[serde(deny_unknown_fields, default)]
351pub struct Verify {
352 /// Run in the winner's worktree once per review round. Its output is fed
353 /// back to the fixer. This is the "real machine" leg of the review.
354 pub e2e: Vec<String>,
355 /// Final gate. Must all exit 0 before a merge is attempted.
356 pub gate: Vec<String>,
357 /// Shell used to run the commands above. Defaults to `sh -c`, or
358 /// `cmd /C` when `sh` is not on `PATH`.
359 pub shell: Option<Vec<String>>,
360}
361
362impl Verify {
363 /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
364 /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
365 /// this reads back. One rendering is enough - they all set the same
366 /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
367 /// command is checked before the gate because the e2e rebuilds the crate.
368 pub fn cache_dir(&self) -> Option<PathBuf> {
369 self.e2e
370 .iter()
371 .chain(self.gate.iter())
372 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
373 }
374}
375
376/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
377///
378/// The numbers below come from one incident, not from theory: a machine with
379/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
380/// Three multi-gigabyte classes of junk accumulated side by side - per-run
381/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
382/// each verify round and each implementation wave recompiles the derived
383/// section of the project into, and the outputs of runs that were removed but
384/// whose folders nobody deleted.
385#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
386#[serde(deny_unknown_fields, default)]
387pub struct Disk {
388 /// Free space, in bytes, below which no new run may start: the daemon and
389 /// the `magi run` gate answer with "the disk is full" instead of letting
390 /// the graph fill it the rest of the way. `0` turns the gate off.
391 ///
392 /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
393 /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
394 /// competition triggers and small enough that a 1 TB disk with 100 GB free
395 /// is nowhere near the threshold.
396 pub min_free_bytes: u64,
397 /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
398 /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
399 /// worktrees removed. `0` turns the janitor off.
400 ///
401 /// Default true.
402 pub auto_fold: bool,
403 /// How old a finished run must be before the janitor folds it, seconds.
404 ///
405 /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
406 /// run that `Ready` a week ago is worktrees holding a compile each. Six
407 /// hours is long enough that nobody loses an answer in the gap between
408 /// reading the report and starting from it, and short enough that a backlog
409 /// cannot pile up across two nights.
410 pub fold_grace_secs: u64,
411 /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
412 /// verify commands), in bytes. When the janitor runs and the cache is over
413 /// it, files are dropped oldest-first until it is not. `0` turns pruning
414 /// off - the cache then only ever grows, which is the operator's call.
415 ///
416 /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
417 /// shared cache on top of ~16 GB in the primary target directory and 6.7-
418 /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
419 /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
420 /// pruning only costs the rebuild of the dropped files, not of the world)
421 /// without letting one addled cache swallow the machine.
422 pub cache_limit_bytes: u64,
423}
424
425impl Default for Disk {
426 fn default() -> Self {
427 Self {
428 min_free_bytes: 8 * 1024 * 1024 * 1024,
429 auto_fold: true,
430 fold_grace_secs: 6 * 60 * 60,
431 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
432 }
433 }
434}
435
436/// What to do with the winning branch.
437#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
438#[serde(rename_all = "lowercase")]
439pub enum MergeMode {
440 /// Leave the branch alone and print the merge command.
441 None,
442 /// `git merge --no-ff` into the base branch in the primary worktree.
443 Local,
444 /// Push the branch and open a PR with `gh pr create`.
445 Pr,
446}
447
448/// Merge policy.
449#[derive(Debug, Clone, Deserialize, Serialize)]
450#[serde(deny_unknown_fields, default)]
451pub struct Merge {
452 /// Default is [`MergeMode::None`]: magi never touches your base branch
453 /// unless you ask it to.
454 pub mode: MergeMode,
455 /// Base branch. Defaults to the branch checked out when the run started.
456 pub base: Option<String>,
457 /// Remote for `mode = "pr"`.
458 pub remote: String,
459}
460
461impl Default for Merge {
462 fn default() -> Self {
463 Self {
464 mode: MergeMode::None,
465 base: None,
466 remote: "origin".to_owned(),
467 }
468 }
469}
470
471/// How magi keeps itself current.
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
473#[serde(rename_all = "lowercase")]
474pub enum UpdateMode {
475 /// Never check.
476 Off,
477 /// Check in the background and print a one-line banner when a newer
478 /// release exists.
479 Notify,
480 /// Check and install silently.
481 Install,
482}
483
484/// Self-update policy.
485#[derive(Debug, Clone, Deserialize, Serialize)]
486#[serde(deny_unknown_fields, default)]
487pub struct Update {
488 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
489 pub mode: UpdateMode,
490 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
491 pub interval: Option<String>,
492}
493
494impl Default for Update {
495 fn default() -> Self {
496 Self {
497 mode: UpdateMode::Notify,
498 interval: None,
499 }
500 }
501}
502
503/// Top-level configuration.
504#[derive(Debug, Clone, Default, Deserialize, Serialize)]
505#[serde(deny_unknown_fields, default)]
506pub struct Config {
507 /// Agent roster.
508 pub agents: Vec<AgentSpec>,
509 /// Role assignment.
510 pub roles: Roles,
511 /// Graph shape.
512 pub graph: Graph,
513 /// Blindness policy.
514 pub blind: Blind,
515 /// Verification commands.
516 pub verify: Verify,
517 /// Disk hygiene.
518 pub disk: Disk,
519 /// Merge policy.
520 pub merge: Merge,
521 /// Self-update policy.
522 pub update: Update,
523 /// Project-specific text appended to the node prompts.
524 pub prompts: Prompts,
525 /// How the operator is told a run is waiting on them.
526 pub notify: Notify,
527 /// Local repositories the plan surface can start or derive a conversation
528 /// against.
529 pub repos: Repos,
530}
531
532/// Where `magi plan` and the browser interview look for a repository other
533/// than the one they were started against.
534///
535/// `roots` is one of the array keys [`array_merge_policy`] marks as
536/// append-across-layers: which checkouts exist in general is a *machine*
537/// fact in the same way the agent roster is - a repository's own `magi.toml`
538/// cannot state where its siblings live before magi has resolved which
539/// repository to read that file from in the first place - but a repository
540/// that genuinely has an extra root worth scanning is not forced to choose
541/// between an error and losing the machine's roots outright. Both layers'
542/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
543/// are still refused.
544#[derive(Debug, Clone, Deserialize, Serialize)]
545#[serde(deny_unknown_fields, default)]
546pub struct Repos {
547 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
548 /// with a `.git` directory. Empty by default - nothing is scanned unless
549 /// asked to be.
550 pub roots: Vec<PathBuf>,
551 /// How long a scan is trusted before the next request re-scans it,
552 /// seconds. `0` means never trust it: scan on every request. Defaults to
553 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
554 /// the same reason - a checkout does not usually appear or vanish inside
555 /// a session, so there is little to gain from scanning more often than
556 /// that, and an explicit refresh exists for the moment one does.
557 pub scan_ttl: u64,
558}
559
560impl Default for Repos {
561 fn default() -> Self {
562 Self {
563 roots: Vec::new(),
564 scan_ttl: 86_400,
565 }
566 }
567}
568
569/// Project-specific text appended to each node's prompt.
570///
571/// **Additive by construction.** These fields cannot replace magi's prompts,
572/// only extend them, and that restriction is the whole design. The built-in
573/// prompts carry the invariants the competition rests on: a judging prompt
574/// names no authors, every structured answer must arrive as one fenced `json`
575/// block, and a judge is told not to speculate about who wrote what. A config
576/// that could overwrite them would let a typo silently un-blind the panel or
577/// break the parser, and the symptom would be "the judges got worse" rather
578/// than an error.
579///
580/// Repository-wide context belongs in `AGENTS.md`, which every agent already
581/// reads from the checkout. Use these fields for the things a *magi node*
582/// needs to know and a repository file cannot say - for instance that
583/// reviewers here should ignore formatting because a hook owns it.
584#[derive(Debug, Clone, Default, Deserialize, Serialize)]
585#[serde(deny_unknown_fields, default)]
586pub struct Prompts {
587 /// Appended to every node's prompt.
588 pub all: String,
589 /// Appended for implementers.
590 pub implement: String,
591 /// Appended for judges, both ranking and voting.
592 pub judge: String,
593 /// Appended for reviewers.
594 pub review: String,
595 /// Appended for the fixer.
596 pub fix: String,
597}
598
599impl Prompts {
600 /// The overlay for one node, or `None` when nothing is configured.
601 ///
602 /// `node` is the graph's own node name, so a new node gets no overlay
603 /// rather than the wrong one.
604 pub fn overlay(&self, node: &str) -> Option<String> {
605 let specific = match node {
606 "implement" => &self.implement,
607 "judge" | "vote" | "deliberate" => &self.judge,
608 "review" => &self.review,
609 "fix" => &self.fix,
610 _ => "",
611 };
612 let mut parts: Vec<&str> = Vec::new();
613 for p in [self.all.trim(), specific.trim()] {
614 if !p.is_empty() {
615 parts.push(p);
616 }
617 }
618 if parts.is_empty() {
619 return None;
620 }
621 Some(parts.join("\n\n"))
622 }
623}
624
625/// How the operator is told that a run is waiting on them.
626///
627/// A command rather than a built-in integration: magi is one binary with no
628/// network dependencies, and every operator's notification path is different -
629/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
630/// Shelling out keeps all of them possible and none of them magi's problem.
631#[derive(Debug, Clone, Default, Deserialize, Serialize)]
632#[serde(deny_unknown_fields, default)]
633pub struct Notify {
634 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
635 /// Empty means no notification - the web UI is then the only surface.
636 pub command: Vec<String>,
637}
638
639/// Roles resolved to concrete agent specs for one run.
640#[derive(Debug, Clone)]
641pub struct ResolvedRoles {
642 /// One per candidate.
643 pub implementers: Vec<AgentSpec>,
644 /// One per judge.
645 pub judges: Vec<AgentSpec>,
646 /// One per reviewer slot.
647 pub reviewers: Vec<AgentSpec>,
648 /// Explicit fixer, if configured.
649 pub fixer: Option<AgentSpec>,
650}
651
652/// Every array-valued key in a config table, as a dotted path.
653///
654/// Dotted so the error names `roles.implementers` rather than `implementers`:
655/// an operator with three config files needs to know which key, not just that
656/// there was one. `vars` is skipped because it is teravars' own input, merged
657/// on purpose and never deserialised into `Config`.
658fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
659 let mut out = Vec::new();
660 for (k, v) in table {
661 if prefix.is_empty() && k == "vars" {
662 continue;
663 }
664 let path = if prefix.is_empty() {
665 k.clone()
666 } else {
667 format!("{prefix}.{k}")
668 };
669 match v {
670 toml::Value::Array(_) => out.push(path),
671 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
672 _ => {}
673 }
674 }
675 out
676}
677
678/// How an array key behaves when two config layers both declare it.
679#[derive(Debug, Clone, Copy, PartialEq, Eq)]
680enum ArrayMerge {
681 /// Two layers may both declare it; the composed value is the
682 /// low-to-high-priority concatenation teravars already produces (see
683 /// [`Config::load_layers`]'s doc for why that order and no dedup).
684 Append,
685 /// Two layers declaring it is refused; see
686 /// [`Config::refuse_split_arrays`].
687 Replace,
688}
689
690/// The single place that decides, for a dotted array key (as returned by
691/// [`array_keys`]), whether declaring it in two config layers is a
692/// concatenation the operator asked for or a silent accident.
693///
694/// Kept as one match so the whole policy is visible in one place - the same
695/// reason `claude_quota` and `dropped_stream` close their own classification
696/// in one spot elsewhere in this codebase. Anything not listed defaults to
697/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
698/// reasoned about yet, and a new array key added later has to be added here
699/// deliberately to become appendable.
700///
701/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
702/// gate. Concatenating two of them is exactly the checks both layers
703/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
704/// live in a shared layer while a repository's own layer adds its own
705/// command, instead of every repository copying the shared command into
706/// its own file.
707/// - `repos.roots` — a set of directories to scan for checkouts. A
708/// repository adding its own root on top of the machine's is additive by
709/// nature, not a replacement of where the machine looks; see
710/// [`Repos::roots`].
711///
712/// Left on the refuse side, and why:
713/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
714/// list of *seats*, not a set. A machine's two implementers plus a
715/// repository's one is three seats nobody asked for and nobody is paying
716/// for on purpose.
717/// - `notify.command` — an argv. Concatenating two argvs does not produce a
718/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
719/// - `blind.strip_lines` — technically safe to concatenate (each entry is
720/// matched as an independent substring, so a longer list only strips
721/// *more*), but left on the refuse side anyway: the same list also drives
722/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
723/// and a silent three-layer merge is exactly the kind of surprise
724/// `refuse_split_arrays` exists to catch rather than to reason about
725/// case-by-case. A repository that wants one more stripped phrase restates
726/// the whole list; that restatement is visible in review, an accidental
727/// concatenation would not be.
728fn array_merge_policy(key: &str) -> ArrayMerge {
729 match key {
730 "verify.e2e" | "verify.gate" | "repos.roots" => ArrayMerge::Append,
731 _ => ArrayMerge::Replace,
732 }
733}
734
735impl Config {
736 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
737 /// and the `include = [...]` directive.
738 pub fn load(path: &Path) -> Result<Self> {
739 Self::load_layers(&[path.to_path_buf()])
740 }
741
742 /// The Tera render context shared by every layer: `system.*` (from
743 /// teravars), `env` (magi's own addition - a config that names a shared
744 /// build-cache directory or a machine-specific path needs
745 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
746 /// derived from the last (highest-priority) path's parent directory.
747 ///
748 /// Factored out so [`Config::array_provenance`] can re-render a single
749 /// layer under the exact same context [`Config::load_layers`] uses for
750 /// the joint render, rather than drifting from it by accident.
751 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
752 let mut ctx = teravars::system_context();
753 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
754 ctx.insert("env", &env);
755 if let Some(last) = paths.last()
756 && let Some(dir) = last.parent()
757 {
758 ctx.insert("repo", &dir.to_string_lossy());
759 ctx.insert(
760 "repo_name",
761 &dir.file_name().unwrap_or_default().to_string_lossy(),
762 );
763 }
764 ctx
765 }
766
767 /// Load and deep-merge a stack of config files, later files winning.
768 ///
769 /// This is why the config is TOML-through-teravars rather than plain serde:
770 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
771 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
772 /// there). Picking one file and ignoring the other would force every repo
773 /// to restate the roster.
774 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
775 let mut engine = teravars::Engine::default();
776 let ctx = Self::render_ctx(paths);
777 if paths.len() > 1 {
778 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
779 }
780 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
781 format!(
782 "rendering config via teravars: {}",
783 paths
784 .iter()
785 .map(|p| p.display().to_string())
786 .collect::<Vec<_>>()
787 .join(", ")
788 )
789 })?;
790 let mut table = merged.config;
791 // `[vars]` is teravars' own input, already resolved into the render
792 // context; `deny_unknown_fields` must not trip over it.
793 table.remove("vars");
794 toml::Value::Table(table)
795 .try_into()
796 .context("deserializing magi config")
797 }
798
799 /// Refuse an array that two layers both declare, unless
800 /// [`array_merge_policy`] says that key is meant to accumulate.
801 ///
802 /// teravars **appends** arrays when it merges layers, and that is wrong for
803 /// most arrays magi has: `implementers` is an ordered list of seats,
804 /// `notify.command` is an argv. Concatenating two of them yields something
805 /// nobody wrote - three implementers out of a machine's two and a
806 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
807 ///
808 /// Replacing instead would be the right merge rule for those keys, but the
809 /// rule lives in teravars, which several other projects depend on;
810 /// changing it there is a decision for that crate, not something to fake
811 /// here by re-reading the files with different semantics and hoping the
812 /// two paths agree.
813 ///
814 /// So magi refuses the ambiguity rather than resolving it silently, for
815 /// every array key except the short, deliberate list
816 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
817 /// concatenation teravars already produces *is* what both files say, so
818 /// there is nothing to refuse. The cost of guessing wrong on the refused
819 /// keys is a roster the operator did not ask for and is paying for by the
820 /// token; the append keys carry no such risk because every element runs
821 /// (or every directory is scanned) regardless of order.
822 fn refuse_split_arrays(
823 paths: &[PathBuf],
824 engine: &mut teravars::Engine,
825 ctx: &teravars::Context,
826 ) -> Result<()> {
827 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
828 for path in paths {
829 let one = teravars::load_merged([path], engine, ctx)
830 .with_context(|| format!("rendering {}", path.display()))?;
831 for key in array_keys(&one.config, "") {
832 if array_merge_policy(&key) == ArrayMerge::Append {
833 continue;
834 }
835 if let Some(first) = seen.get(&key) {
836 bail!(
837 "`{key}` is an array declared in two config layers:\n \
838 {}\n {}\nteravars appends arrays when it merges, so \
839 magi would run the concatenation of both - which is \
840 not what either file says. Declare `{key}` in exactly \
841 one of them.",
842 first.display(),
843 path.display()
844 );
845 }
846 seen.insert(key, path.clone());
847 }
848 }
849 Ok(())
850 }
851
852 /// Which layers contributed to a composed, appendable array key (e.g.
853 /// `"verify.gate"`), in the same low-to-high-priority order
854 /// [`Config::load_layers`] concatenates them in. Layers that do not
855 /// declare `key` at all are omitted.
856 ///
857 /// This is a **display aid for `magi doctor` only.** The command list
858 /// that actually runs always comes from the one joint
859 /// [`teravars::load_merged`] call in `load_layers`, never from this
860 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
861 /// about is two merge paths that might disagree, so this function must
862 /// never become a second source of the *composed* value, only of which
863 /// file wrote which line in it.
864 ///
865 /// Re-rendering each layer alone can, in principle, resolve a
866 /// `{{ vars.x }}` differently than the joint render would, if `x` is
867 /// defined in one layer and referenced in another - the same caveat
868 /// `refuse_split_arrays`'s structural, key-only check already lives with.
869 /// None of magi's own gate commands cross that line, and a doctor listing
870 /// is read by a human who can compare it against the joint one printed
871 /// alongside it, so this is judged worth the simplicity of not
872 /// threading provenance through the real load path.
873 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
874 let mut engine = teravars::Engine::default();
875 let ctx = Self::render_ctx(paths);
876 let mut out = Vec::new();
877 for path in paths {
878 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
879 continue;
880 };
881 let mut cur = &one.config;
882 let mut found = None;
883 let parts: Vec<&str> = key.split('.').collect();
884 for (i, part) in parts.iter().enumerate() {
885 match cur.get(*part) {
886 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
887 found = Some(a);
888 break;
889 }
890 Some(toml::Value::Table(t)) => cur = t,
891 _ => break,
892 }
893 }
894 let Some(values) = found else { continue };
895 let strings: Vec<String> = values
896 .iter()
897 .filter_map(|v| v.as_str().map(str::to_owned))
898 .collect();
899 if !strings.is_empty() {
900 out.push((path.clone(), strings));
901 }
902 }
903 out
904 }
905
906 /// Render a composed command list for `magi doctor`: the joined command
907 /// line the run actually uses, plus - only when more than one layer
908 /// contributed - which layer wrote which line.
909 ///
910 /// A single contributing layer (the common case today) stays the plain
911 /// one-line summary magi has always printed, `empty` included: that
912 /// honest "(none — ...)" is what caught a real gate-composition gap
913 /// before this array could compose at all, and composition should not
914 /// make the common case noisier.
915 pub fn describe_composed(
916 paths: &[PathBuf],
917 commands: &[String],
918 key: &str,
919 empty: &str,
920 ) -> String {
921 if commands.is_empty() {
922 return empty.to_owned();
923 }
924 let joined = commands.join(" && ");
925 let provenance = Self::array_provenance(paths, key);
926 if provenance.len() <= 1 {
927 return joined;
928 }
929 let mut out = joined;
930 for (path, cmds) in &provenance {
931 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
932 }
933 out
934 }
935
936 /// Resolve the config for `repo`, honouring an explicit `--config` path.
937 ///
938 /// Returns the config and the layers it came from, empty for built-in
939 /// defaults.
940 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
941 if let Some(p) = explicit {
942 let paths = vec![p.to_path_buf()];
943 return Ok((Self::load_layers(&paths)?, paths));
944 }
945 let paths = Self::layers(repo);
946 if paths.is_empty() {
947 return Ok((Self::autodetected(), paths));
948 }
949 Ok((Self::load_layers(&paths)?, paths))
950 }
951 /// Environment variable that relocates the machine-wide config layer.
952 ///
953 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
954 /// of the one under [`dirs::config_dir`]; set it to the empty string and
955 /// magi reads no machine layer at all.
956 ///
957 /// This exists because the machine layer is otherwise unavoidable, and a
958 /// test that builds a config fixture is not asking for the operator's
959 /// preferences to be merged into it. Adding `[repos] roots` to the real
960 /// machine config on a development box turned two passing tests red -
961 /// `repos_list_returns_name_and_path_for_every_configured_root` and
962 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
963 /// declare `[repos] roots` of their own, which [`Config::layers`] then
964 /// found in two layers and [`Config::refuse_split_arrays`] correctly
965 /// refused. CI never saw it: a runner has no machine config, so the suite
966 /// was green there and red only where somebody actually uses magi.
967 ///
968 /// An operator gets the same escape hatch for free: a second machine
969 /// config, or none, without moving files about.
970 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
971
972 /// Every config layer that applies to `repo`, in increasing precedence.
973 ///
974 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
975 /// which is nothing at all in a test build.
976 pub fn layers(repo: &Path) -> Vec<PathBuf> {
977 let mut paths = Vec::new();
978 paths.extend(Self::machine_layer());
979 paths.push(repo.join(".magi").join("config.toml"));
980 paths.push(repo.join("magi.toml"));
981 paths.retain(|p| p.is_file());
982 paths
983 }
984
985 /// The machine-wide layer's path, when there is one.
986 ///
987 /// **A test build has none unless it names one.** A fixture is a complete
988 /// statement of the config under test, and the operator's own preferences
989 /// have no business being merged into it - least of all silently, on one
990 /// machine, in a suite that is green everywhere else.
991 #[cfg(test)]
992 fn machine_layer() -> Option<PathBuf> {
993 std::env::var(Self::CONFIG_DIR_ENV)
994 .ok()
995 .filter(|dir| !dir.trim().is_empty())
996 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
997 }
998
999 /// The machine-wide layer's path, when there is one.
1000 #[cfg(not(test))]
1001 fn machine_layer() -> Option<PathBuf> {
1002 match std::env::var(Self::CONFIG_DIR_ENV) {
1003 // Named, and empty on purpose: no machine layer.
1004 Ok(dir) if dir.trim().is_empty() => None,
1005 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1006 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1007 }
1008 }
1009
1010 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1011 pub fn autodetected() -> Self {
1012 let mut cfg = Self::default();
1013 for (kind, id, model) in [
1014 (AgentKind::Claude, "opus", Some("opus")),
1015 (AgentKind::Claude, "sonnet", Some("sonnet")),
1016 (AgentKind::Antigravity, "antigravity", None),
1017 (AgentKind::Opencode, "opencode", None),
1018 (AgentKind::Codex, "codex", None),
1019 ] {
1020 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1021 cfg.agents.push(AgentSpec {
1022 id: id.to_owned(),
1023 kind,
1024 model: model.map(str::to_owned),
1025 command: Vec::new(),
1026 extra_args: Vec::new(),
1027 env: BTreeMap::new(),
1028 prompt_delivery: None,
1029 });
1030 }
1031 }
1032 cfg
1033 }
1034
1035 /// The shared build cache the verify commands and the agents both build
1036 /// into, when the config declares one. See [`Verify::cache_dir`].
1037 pub fn cache_dir(&self) -> Option<PathBuf> {
1038 self.verify.cache_dir()
1039 }
1040
1041 /// Look an agent up by id.
1042 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1043 self.agents
1044 .iter()
1045 .find(|a| a.id == id)
1046 .with_context(|| format!("no agent with id `{id}` in the roster"))
1047 }
1048
1049 /// Fill the roles out to the configured widths.
1050 ///
1051 /// An empty role list rotates through the whole roster, so a three-agent
1052 /// roster with `candidates = 3` gives one implementation per agent, and
1053 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1054 /// author of candidate *i* whenever the roster has more than one agent.
1055 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1056 if self.agents.is_empty() {
1057 bail!(
1058 "agent roster is empty: no agent CLI found on PATH and no \
1059 [[agents]] in the config. Run `magi init` to write a starter \
1060 magi.toml."
1061 );
1062 }
1063 let pick = |ids: &[String], count: usize, offset: usize| -> Result<Vec<AgentSpec>> {
1064 let mut out = Vec::with_capacity(count);
1065 for i in 0..count {
1066 let spec = if ids.is_empty() {
1067 self.agents[(i + offset) % self.agents.len()].clone()
1068 } else {
1069 self.agent(&ids[i % ids.len()])?.clone()
1070 };
1071 out.push(spec);
1072 }
1073 Ok(out)
1074 };
1075 Ok(ResolvedRoles {
1076 implementers: pick(&self.roles.implementers, self.graph.candidates, 0)?,
1077 judges: pick(&self.roles.judges, self.graph.judges, 1)?,
1078 reviewers: pick(&self.roles.reviewers, self.graph.reviewers, 0)?,
1079 fixer: self
1080 .roles
1081 .fixer
1082 .as_deref()
1083 .map(|f| self.agent(f).cloned())
1084 .transpose()?,
1085 })
1086 }
1087
1088 /// Shell prefix for [`Verify`] commands.
1089 pub fn shell(&self) -> Vec<String> {
1090 if let Some(s) = &self.verify.shell {
1091 return s.clone();
1092 }
1093 if which("sh") {
1094 vec!["sh".to_owned(), "-c".to_owned()]
1095 } else {
1096 vec!["cmd".to_owned(), "/C".to_owned()]
1097 }
1098 }
1099
1100 /// Starter config, as written by `magi init`.
1101 pub fn starter_toml() -> String {
1102 let detected = Self::autodetected();
1103 let mut s = String::from(
1104 "# magi — blind multi-agent implementation competition.\n\
1105 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
1106 # -> blind judging -> deliberation -> private final vote\n\
1107 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
1108 #\n\
1109 # Rendered by teravars: a `[vars]` table, env\n\
1110 # and system lookups, and `include = [...]` all work. Tera\n\
1111 # braces are live everywhere in this file, but comments are\n\
1112 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
1113 # may quote `{{ ... }}` freely.\n\
1114 #\n\
1115 # Layers deep-merge in increasing\n\
1116 # precedence, so the roster can live once per machine in\n\
1117 # <config_dir>/magi/config.toml and each repo only states its own\n\
1118 # gate:\n\
1119 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
1120 [vars]\n\
1121 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
1122 # Single quotes inside the braces: teravars renders the raw file\n\
1123 # text, so TOML's own \\\" escaping never reaches Tera.\n\
1124 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
1125 );
1126 if detected.agents.is_empty() {
1127 s.push_str(
1128 "# No agent CLI was found on PATH. Fill this in by hand.\n\
1129 # kind = claude | opencode | antigravity | codex | command\n\
1130 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
1131 );
1132 } else {
1133 for a in &detected.agents {
1134 s.push_str("[[agents]]\n");
1135 s.push_str(&format!("id = {:?}\n", a.id));
1136 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
1137 if let Some(m) = &a.model {
1138 s.push_str(&format!("model = {m:?}\n"));
1139 }
1140 s.push('\n');
1141 }
1142 }
1143 s.push_str(
1144 "# Leave a role list empty to rotate through the roster.\n\
1145 [roles]\n\
1146 implementers = []\n\
1147 judges = []\n\
1148 reviewers = []\n\n\
1149 [graph]\n\
1150 candidates = 3\n\
1151 judges = 3\n\
1152 deliberate_rounds = 1\n\
1153 reviewers = 2\n\
1154 review_rounds = 6\n\
1155 max_parallel = 4\n\
1156 language = \"en\"\n\
1157 # One CLI conversation per seat: judges keep their own argument\n\
1158 # across deliberation, the fixer keeps its implementation context.\n\
1159 sessions = true\n\n\
1160 [verify]\n\
1161 # Run once per review round in the winner's worktree; failures are\n\
1162 # fed back to the fixer.\n\
1163 e2e = []\n\
1164 # Final gate. Every command must exit 0 before a merge.\n\
1165 gate = []\n\n\
1166 [merge]\n\
1167 # none | local | pr\n\
1168 mode = \"none\"\n\n\
1169 [update]\n\
1170 # off | notify | install — checked in the background, throttled.\n\
1171 mode = \"notify\"\n\
1172 # interval = \"24h\"\n",
1173 );
1174 s
1175 }
1176}
1177
1178/// Is `program` on `PATH`?
1179pub fn which(program: &str) -> bool {
1180 let Some(paths) = std::env::var_os("PATH") else {
1181 return false;
1182 };
1183 let exts: Vec<String> = std::env::var("PATHEXT")
1184 .map(|v| v.split(';').map(|e| e.to_lowercase()).collect())
1185 .unwrap_or_default();
1186 std::env::split_paths(&paths).any(|dir| {
1187 let direct = dir.join(program);
1188 if direct.is_file() {
1189 return true;
1190 }
1191 exts.iter().any(|ext| {
1192 let mut name = program.to_owned();
1193 name.push_str(ext);
1194 dir.join(name).is_file()
1195 })
1196 })
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201 use super::*;
1202
1203 fn spec(id: &str) -> AgentSpec {
1204 AgentSpec {
1205 id: id.to_owned(),
1206 kind: AgentKind::Command,
1207 model: None,
1208 command: vec!["true".to_owned()],
1209 extra_args: Vec::new(),
1210 env: BTreeMap::new(),
1211 prompt_delivery: None,
1212 }
1213 }
1214
1215 #[test]
1216 fn empty_roles_rotate_judges_off_their_own_candidate() {
1217 // Three seats, said out loud: this is a test about *rotation*, and it
1218 // has nothing to say about how many candidates a task buys by default.
1219 let cfg = Config {
1220 agents: vec![spec("a"), spec("b"), spec("c")],
1221 graph: Graph {
1222 candidates: 3,
1223 ..Graph::default()
1224 },
1225 ..Config::default()
1226 };
1227 let roles = cfg.resolve_roles().unwrap();
1228 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
1229 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
1230 assert_eq!(impls, ["a", "b", "c"]);
1231 assert_eq!(judges, ["b", "c", "a"]);
1232 for (i, j) in judges.iter().enumerate() {
1233 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
1234 }
1235 }
1236
1237 #[test]
1238 fn single_agent_roster_fills_every_seat() {
1239 let cfg = Config {
1240 agents: vec![spec("solo")],
1241 graph: Graph {
1242 candidates: 3,
1243 ..Graph::default()
1244 },
1245 ..Config::default()
1246 };
1247 let roles = cfg.resolve_roles().unwrap();
1248 assert_eq!(roles.implementers.len(), 3);
1249 assert!(roles.judges.iter().all(|a| a.id == "solo"));
1250 }
1251
1252 #[test]
1253 fn explicit_roles_win() {
1254 let cfg = Config {
1255 agents: vec![spec("a"), spec("b")],
1256 roles: Roles {
1257 implementers: vec!["b".to_owned()],
1258 judges: vec!["a".to_owned()],
1259 reviewers: Vec::new(),
1260 fixer: Some("a".to_owned()),
1261 ..Roles::default()
1262 },
1263 ..Config::default()
1264 };
1265 let roles = cfg.resolve_roles().unwrap();
1266 assert!(roles.implementers.iter().all(|a| a.id == "b"));
1267 assert!(roles.judges.iter().all(|a| a.id == "a"));
1268 assert_eq!(roles.fixer.unwrap().id, "a");
1269 }
1270
1271 #[test]
1272 fn unknown_agent_id_is_an_error() {
1273 let cfg = Config {
1274 agents: vec![spec("a")],
1275 roles: Roles {
1276 judges: vec!["nope".to_owned()],
1277 ..Roles::default()
1278 },
1279 ..Config::default()
1280 };
1281 assert!(cfg.resolve_roles().is_err());
1282 }
1283
1284 #[test]
1285 fn empty_roster_is_an_error() {
1286 assert!(Config::default().resolve_roles().is_err());
1287 }
1288
1289 #[test]
1290 fn repos_default_to_no_roots_and_a_day_of_trust() {
1291 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
1292 assert_eq!(Config::default().repos.scan_ttl, 86_400);
1293 }
1294
1295 #[test]
1296 fn a_config_file_with_no_repos_table_still_loads() {
1297 let dir = tempfile::tempdir().unwrap();
1298 let path = dir.path().join("magi.toml");
1299 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
1300 let cfg = Config::load(&path).expect("must load without [repos]");
1301 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
1302 assert_eq!(cfg.repos.scan_ttl, 86_400);
1303 }
1304
1305 /// A fixture is the whole config under test.
1306 ///
1307 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
1308 /// a machine where somebody had written `<config_dir>/magi/config.toml`
1309 /// the suite silently loaded it as the lowest layer. Adding `[repos]
1310 /// roots` there turned two web tests red - their fixtures declare
1311 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
1312 /// array key spread across two layers. CI stayed green throughout,
1313 /// because a runner has no such file: the suite failed only where magi is
1314 /// actually used.
1315 ///
1316 /// So a test build has no machine layer unless it asks for one, and this
1317 /// is that promise. Written against a real file at the real location so
1318 /// it fails if `machine_layer` starts reading it again.
1319 #[test]
1320 fn a_test_build_does_not_read_the_operators_machine_config() {
1321 let repo = tempfile::tempdir().unwrap();
1322 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
1323
1324 let layers = Config::layers(repo.path());
1325 assert_eq!(
1326 layers,
1327 vec![repo.path().join("magi.toml")],
1328 "only the fixture's own file may be a layer"
1329 );
1330 if let Some(real) = dirs::config_dir() {
1331 let machine = real.join("magi").join("config.toml");
1332 assert!(
1333 !layers.contains(&machine),
1334 "the operator's {} must not be a layer in a test build",
1335 machine.display()
1336 );
1337 }
1338 }
1339
1340 #[test]
1341 fn starter_toml_loads_through_teravars() {
1342 let dir = tempfile::tempdir().unwrap();
1343 let path = dir.path().join("magi.toml");
1344 std::fs::write(&path, Config::starter_toml()).unwrap();
1345 let parsed = Config::load(&path).expect("starter config must load");
1346 assert_eq!(parsed.graph.candidates, 3);
1347 assert_eq!(parsed.merge.mode, MergeMode::None);
1348 assert!(parsed.graph.sessions);
1349 assert_eq!(parsed.update.mode, UpdateMode::Notify);
1350 }
1351
1352 #[test]
1353 fn later_layers_win_and_vars_render() {
1354 let dir = tempfile::tempdir().unwrap();
1355 let machine = dir.path().join("machine.toml");
1356 let project = dir.path().join("magi.toml");
1357 // The machine layer owns the roster...
1358 std::fs::write(
1359 &machine,
1360 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
1361 [graph]\ncandidates = 3\nmax_parallel = 8\n",
1362 )
1363 .unwrap();
1364 // ...and the project layer only states what is repo-specific, plus a
1365 // `[vars]` value interpolated into a command.
1366 std::fs::write(
1367 &project,
1368 "[vars]\ncache = \"/shared\"\n\n\
1369 [graph]\ncandidates = 2\n\n\
1370 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
1371 )
1372 .unwrap();
1373
1374 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
1375 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
1376 assert_eq!(cfg.graph.candidates, 2, "project layer wins");
1377 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
1378 assert_eq!(
1379 cfg.verify.gate,
1380 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
1381 );
1382 // The rendered command is where the cache path is read back from.
1383 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
1384 }
1385
1386 #[test]
1387 fn the_disk_defaults_are_the_measurements_made_up_front() {
1388 let cfg = Config::default();
1389 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
1390 assert!(cfg.disk.auto_fold);
1391 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
1392 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
1393 }
1394
1395 #[test]
1396 fn an_unset_disk_section_is_the_safe_default() {
1397 let dir = tempfile::tempdir().unwrap();
1398 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
1399 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
1400 assert_eq!(cfg.disk, Disk::default());
1401 }
1402
1403 #[test]
1404 fn env_is_available_to_templates_with_a_default() {
1405 let dir = tempfile::tempdir().unwrap();
1406 let path = dir.path().join("magi.toml");
1407 // teravars ships no `env`; magi adds it, and the `default` filter has
1408 // to cover the unset case or every machine would need the variable.
1409 //
1410 // Deliberately no named variable: `env` is keyed by the exact spelling
1411 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
1412 // test asserting `env.PATH` passes on one runner and fails on another.
1413 // The map's non-emptiness is the platform-neutral claim.
1414 std::fs::write(
1415 &path,
1416 "[verify]\n\
1417 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
1418 \"populated={{ env | length > 0 }}\"]\n",
1419 )
1420 .unwrap();
1421 let cfg = Config::load(&path).expect("env lookup must render");
1422 assert_eq!(cfg.verify.gate[0], "cache=fallback");
1423 assert_eq!(cfg.verify.gate[1], "populated=true");
1424 }
1425
1426 #[test]
1427 fn a_broken_template_names_the_file() {
1428 let dir = tempfile::tempdir().unwrap();
1429 let path = dir.path().join("magi.toml");
1430 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
1431 let err = Config::load(&path).expect_err("must not silently ignore");
1432 assert!(err.to_string().contains("teravars"), "{err}");
1433 }
1434
1435 #[test]
1436 fn tera_syntax_in_comments_is_inert() {
1437 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
1438 // comment may quote template syntax without rendering. Before 0.2.2 this
1439 // load failed: the commented-out braces reached the template parser.
1440 let dir = tempfile::tempdir().unwrap();
1441 let path = dir.path().join("magi.toml");
1442 std::fs::write(
1443 &path,
1444 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
1445 [graph]\ncandidates = 2\n",
1446 )
1447 .unwrap();
1448 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
1449 assert_eq!(cfg.graph.candidates, 2);
1450 }
1451
1452 #[test]
1453 fn opencode_defaults_to_file_delivery() {
1454 let mut s = spec("oc");
1455 s.kind = AgentKind::Opencode;
1456 assert_eq!(s.delivery(), Delivery::File);
1457 s.prompt_delivery = Some(Delivery::Argv);
1458 assert_eq!(s.delivery(), Delivery::Argv);
1459 }
1460 #[test]
1461 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
1462 // Both default on, and that pair is the safety property: `land` takes
1463 // over the watching an operator was doing by hand, `land_approval`
1464 // keeps the irreversible step a human decision. An unattended merge
1465 // needs BOTH flipped, which has to be chosen deliberately twice.
1466 let g = Graph::default();
1467 assert!(
1468 g.land,
1469 "stopping at an open PR left the watching to a human"
1470 );
1471 assert!(
1472 g.land_approval,
1473 "on-by-default land is only defensible while this is also on"
1474 );
1475 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
1476 }
1477 #[test]
1478 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
1479 // teravars appends arrays. For an ordered list of seats, or an argv,
1480 // the concatenation is something neither file says - and the operator
1481 // pays for the extra seats by the token.
1482 let dir = tempfile::tempdir().unwrap();
1483 let machine = dir.path().join("machine.toml");
1484 let repo = dir.path().join("magi.toml");
1485 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
1486 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
1487
1488 let err = Config::load_layers(&[machine.clone(), repo.clone()])
1489 .expect_err("two layers naming one array must not merge silently")
1490 .to_string();
1491 assert!(err.contains("roles.implementers"), "{err}");
1492 // Both files are named: the fix is to delete one of them, and the
1493 // operator has to know which two to choose between.
1494 assert!(err.contains("machine.toml"), "{err}");
1495 assert!(err.contains("magi.toml"), "{err}");
1496 }
1497
1498 #[test]
1499 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
1500 // The split the layering exists for: state a preference machine-wide,
1501 // let the repository own its own lists.
1502 let dir = tempfile::tempdir().unwrap();
1503 let machine = dir.path().join("machine.toml");
1504 let repo = dir.path().join("magi.toml");
1505 std::fs::write(&machine, "[roles]\nplanner = \"opus\"\n").unwrap();
1506 std::fs::write(
1507 &repo,
1508 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
1509 [roles]\nimplementers = [\"oc\"]\n",
1510 )
1511 .unwrap();
1512
1513 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
1514 assert_eq!(cfg.roles.planner.as_deref(), Some("opus"));
1515 assert_eq!(cfg.roles.implementers, ["oc"]);
1516 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
1517 }
1518
1519 #[test]
1520 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
1521 // The `editorconfig-checker` distribution problem: a shared layer
1522 // wants to add a gate command without erasing the repository's own.
1523 let dir = tempfile::tempdir().unwrap();
1524 let machine = dir.path().join("machine.toml");
1525 let repo = dir.path().join("magi.toml");
1526 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
1527 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
1528
1529 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1530 assert_eq!(
1531 cfg.verify.gate,
1532 [
1533 "editorconfig-checker".to_owned(),
1534 "cargo make check".to_owned()
1535 ],
1536 "low-priority (machine) command first, high-priority (repo) command after"
1537 );
1538 }
1539
1540 #[test]
1541 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
1542 let dir = tempfile::tempdir().unwrap();
1543 let machine = dir.path().join("machine.toml");
1544 let repo = dir.path().join("magi.toml");
1545 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
1546 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
1547
1548 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1549 assert_eq!(
1550 cfg.verify.e2e,
1551 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
1552 );
1553 }
1554
1555 #[test]
1556 fn two_layers_declaring_repos_roots_are_both_scanned() {
1557 let dir = tempfile::tempdir().unwrap();
1558 let machine = dir.path().join("machine.toml");
1559 let repo = dir.path().join("magi.toml");
1560 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
1561 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
1562
1563 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1564 assert_eq!(
1565 cfg.repos.roots,
1566 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
1567 );
1568 }
1569
1570 #[test]
1571 fn duplicate_gate_commands_across_layers_both_run() {
1572 // Dropping the duplicate would be a silent surprise; the operator
1573 // sees a slower gate, never a missing one.
1574 let dir = tempfile::tempdir().unwrap();
1575 let machine = dir.path().join("machine.toml");
1576 let repo = dir.path().join("magi.toml");
1577 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
1578 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
1579
1580 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
1581 assert_eq!(
1582 cfg.verify.gate,
1583 ["same-command".to_owned(), "same-command".to_owned()]
1584 );
1585 }
1586
1587 #[test]
1588 fn notify_command_is_still_refused_across_two_layers() {
1589 // An argv, not a set: concatenating two of them is not a program.
1590 let dir = tempfile::tempdir().unwrap();
1591 let machine = dir.path().join("machine.toml");
1592 let repo = dir.path().join("magi.toml");
1593 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
1594 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
1595
1596 let err = Config::load_layers(&[machine.clone(), repo.clone()])
1597 .expect_err("an argv split across layers must not concatenate")
1598 .to_string();
1599 assert!(err.contains("notify.command"), "{err}");
1600 assert!(err.contains("machine.toml"), "{err}");
1601 assert!(err.contains("magi.toml"), "{err}");
1602 }
1603
1604 #[test]
1605 fn one_layer_declaring_verify_gate_runs_unchanged() {
1606 // The classification must not change behaviour for the configuration
1607 // this very repository has today: exactly one layer names the gate.
1608 let dir = tempfile::tempdir().unwrap();
1609 let path = dir.path().join("magi.toml");
1610 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
1611
1612 let cfg = Config::load(&path).expect("single layer must still load");
1613 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
1614 }
1615
1616 #[test]
1617 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
1618 let dir = tempfile::tempdir().unwrap();
1619 let machine = dir.path().join("machine.toml");
1620 let repo = dir.path().join("magi.toml");
1621 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
1622 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
1623 let paths = vec![machine.clone(), repo.clone()];
1624
1625 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
1626 let described =
1627 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
1628 assert!(described.contains("editorconfig-checker && cargo make check"));
1629 assert!(
1630 described.contains(&machine.display().to_string()),
1631 "{described}"
1632 );
1633 assert!(
1634 described.contains(&repo.display().to_string()),
1635 "{described}"
1636 );
1637
1638 // A single contributing layer stays the plain one-line summary.
1639 let single = vec![repo.clone()];
1640 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
1641 let solo_described =
1642 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
1643 assert_eq!(solo_described, "cargo make check");
1644 }
1645}