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 /// oh-my-pi (`omp -p --mode=json`). Another CLI with no read-only mode of
35 /// its own - `--auto-approve` gates reads and writes together - so a
36 /// read-only seat rests on the prompt and on the worktree discipline the
37 /// other non-codex seats already rely on. It is also the roster member that
38 /// reaches DeepSeek, whose models ship in `omp`'s own catalog.
39 Omp,
40 /// Arbitrary command. The escape hatch, and what the test suite drives.
41 Command,
42}
43
44impl AgentKind {
45 /// Executable that must be on `PATH` for this kind, if any.
46 pub fn program(self) -> Option<&'static str> {
47 match self {
48 Self::Claude => Some("claude"),
49 Self::Opencode => Some("opencode"),
50 Self::Antigravity => Some("agy"),
51 Self::Codex => Some("codex"),
52 Self::Omp => Some("omp"),
53 Self::Command => None,
54 }
55 }
56
57 /// Lowercase name as written in the config file.
58 pub fn as_str(self) -> &'static str {
59 match self {
60 Self::Claude => "claude",
61 Self::Opencode => "opencode",
62 Self::Antigravity => "antigravity",
63 Self::Codex => "codex",
64 Self::Omp => "omp",
65 Self::Command => "command",
66 }
67 }
68
69 /// Every kind the roster can name, in display order.
70 ///
71 /// This is what `magi doctor` lists, and it has to be one list rather than
72 /// the same set typed out again wherever a kind is enumerated. The last
73 /// time it was typed out twice, `omp` was added as a roster member and the
74 /// doctor output went on saying the machine had four CLIs - which reads as
75 /// "that agent is not installed" to the person the command exists for.
76 pub const ALL: [Self; 6] = [
77 Self::Claude,
78 Self::Opencode,
79 Self::Antigravity,
80 Self::Codex,
81 Self::Omp,
82 Self::Command,
83 ];
84}
85
86/// How the prompt reaches the agent process.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
88#[serde(rename_all = "lowercase")]
89pub enum Delivery {
90 /// Piped on stdin.
91 Stdin,
92 /// Passed as a positional argument. Beware OS command-line limits.
93 Argv,
94 /// Written to a file; the agent is told to read it. No length limit.
95 File,
96}
97
98/// One addressable agent in the roster.
99#[derive(Debug, Clone, Deserialize, Serialize)]
100#[serde(deny_unknown_fields)]
101pub struct AgentSpec {
102 /// Stable identifier used by `[roles]` and by the stats tables.
103 pub id: String,
104 /// Which CLI to drive.
105 pub kind: AgentKind,
106 /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
107 #[serde(default)]
108 pub model: Option<String>,
109 /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
110 /// `{label}`, `{session}` placeholders.
111 #[serde(default)]
112 pub command: Vec<String>,
113 /// Extra arguments appended to the built command line.
114 #[serde(default)]
115 pub extra_args: Vec<String>,
116 /// Extra environment variables for the child process.
117 #[serde(default)]
118 pub env: BTreeMap<String, String>,
119 /// Override the per-kind prompt delivery default.
120 #[serde(default)]
121 pub prompt_delivery: Option<Delivery>,
122}
123
124impl AgentSpec {
125 /// Default prompt delivery for this agent.
126 ///
127 /// `opencode` and `agy` take the prompt as an argument, which on Windows
128 /// caps out around 32 KiB — well under a judging prompt carrying three
129 /// patches — so both get a file instead.
130 pub fn delivery(&self) -> Delivery {
131 self.prompt_delivery.unwrap_or(match self.kind {
132 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
133 // `codex exec -` reads the prompt from stdin, so the whole
134 // instruction arrives without an argv length limit and without a
135 // tool round-trip to open a file.
136 AgentKind::Codex => Delivery::Stdin,
137 // `omp -p` reads the prompt from stdin too, and a judging prompt
138 // carrying three patches is well past the Windows argv cap, so this
139 // is the only delivery that works for every node.
140 AgentKind::Omp => Delivery::Stdin,
141 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
142 })
143 }
144
145 /// Human-facing label, e.g. `opus (claude:opus)`.
146 pub fn display(&self) -> String {
147 match &self.model {
148 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
149 None => format!("{} ({})", self.id, self.kind.as_str()),
150 }
151 }
152}
153
154/// Explicit role assignment. Empty lists are filled in by
155/// [`Config::resolve_roles`] by rotating the roster.
156#[derive(Debug, Clone, Default, Deserialize, Serialize)]
157#[serde(deny_unknown_fields, default)]
158pub struct Roles {
159 /// Agents that implement the task, one worktree each.
160 pub implementers: Vec<String>,
161 /// Agents that rank the candidates blind.
162 pub judges: Vec<String>,
163 /// Agents that review the winning patch.
164 pub reviewers: Vec<String>,
165 /// Agent that applies review findings. Defaults to the winner's author.
166 pub fixer: Option<String>,
167 /// Agent that answers the standing chat's turns (`src/talk.rs`).
168 ///
169 /// Unset picks a `claude` seat, else the first runnable agent in roster
170 /// order (see [`crate::agent::pick`]) - which is roster *order*, not a
171 /// judgement about who converses well. Naming one here matters once an
172 /// agent is also sitting as a judge: the chat is opened far more often
173 /// than any single competition, and every open competes with that judge
174 /// seat for the same account's concurrency. A timeout on an ordinary chat
175 /// turn traced to exactly this - `opus` triple-booked as chatter and judge
176 /// - is what this field exists to let an operator break apart.
177 pub chatter: Option<String>,
178 /// Agent that arranges the queue between polls: `crate::conduct`'s single
179 /// seat, called once per cycle to decide a runnable task's `blocked_by`
180 /// and how a stalled or finished task recovers.
181 ///
182 /// The same precedent as [`Self::chatter`] for a seat that stands alone
183 /// rather than rotating through the roster - resolved through
184 /// [`crate::agent::pick`], so unset falls back to its own default order
185 /// (a claude seat, else the first runnable agent) rather than reusing a
186 /// judge or reviewer seat that the conductor's own poll-cycle cadence
187 /// would otherwise compete with for the same account's concurrency.
188 pub conductor: Option<String>,
189 /// Seats for the design-deliberation stage `graph::Runner::advise` runs
190 /// before `implement`: independent, read-only design proposals gathered
191 /// once a run has a settled task instruction and before any implementer
192 /// touches the repository.
193 ///
194 /// Empty falls back to `judges` rather than to the whole roster: a panel
195 /// trusted to rank patches independently is exactly the panel worth
196 /// asking to sketch a design independently, and an operator who has
197 /// already thought about judge diversity gets advisor diversity for free
198 /// instead of a fourth roster to maintain.
199 pub advisors: Vec<String>,
200 /// Agent that blends [`Self::advisors`]' proposals into the one design
201 /// brief `graph::Runner::synthesize_brief` carries into every
202 /// implementer's prompt.
203 ///
204 /// The same precedent as [`Self::chatter`] and [`Self::conductor`] for a
205 /// seat that stands alone rather than rotating through the roster -
206 /// resolved through [`crate::agent::pick`], so unset falls back to its
207 /// own default order (a claude seat, else the first runnable agent in
208 /// roster order) - exactly today's behavior, unchanged by leaving this
209 /// field out.
210 pub synthesizer: Option<String>,
211}
212
213/// Graph shape and limits.
214#[derive(Debug, Clone, Deserialize, Serialize)]
215#[serde(deny_unknown_fields, default)]
216pub struct Graph {
217 /// Parallel implementations of the same task. **One by default.**
218 ///
219 /// Competition is the thing magi is for, and it is still here - it is just
220 /// no longer what every task buys without being asked. Three days and 13
221 /// runs on this repository, which is the workload these numbers are drawn
222 /// from:
223 ///
224 /// - **0 of 13** competed runs reached a merge. Everything that landed in
225 /// that window went through `magi review` - the cheap half, no
226 /// competition - and passed on the first try.
227 /// - The judges' first choices **split 73% of the time** (8 of 11
228 /// tallies). Candidates that close together make the ranking a weak
229 /// signal for what it costs to produce.
230 /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
231 /// review 28min, **verify 5min** - and verify is the node that caught a
232 /// defect every reviewer had passed as clean. The cheapest step is the
233 /// one that earns its place every time.
234 ///
235 /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
236 /// single-seat default would have shipped the worse implementation in
237 /// roughly a quarter of them. That is exactly why this is a *default* and
238 /// not a removal - `magi run --candidates N` and a per-task seat count are
239 /// how a task that deserves a competition gets one.
240 ///
241 /// A single-candidate run needs no special case: `Runner::review`'s doc
242 /// records that `execute` already degrades to implement -> review -> gate
243 /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
244 /// no two first choices to reconcile and `vote` returns early.
245 pub candidates: usize,
246 /// Independent judges.
247 pub judges: usize,
248 /// Deliberation rounds when the judges' first choices disagree.
249 pub deliberate_rounds: usize,
250 /// Reviewers per review round. **Three by default** - the smallest panel
251 /// a lens cycle (see [`crate::prompt::Lens`]) covers exactly once, so the
252 /// default panel reads the patch for spec compliance, regressions, and
253 /// simplicity without repeating an angle. Review is also the one stage
254 /// [`Self::candidates`]'s doc describes as running on every task
255 /// regardless of competition, which is what makes a panel worth its cost
256 /// here even though `candidates` itself defaults to one.
257 pub reviewers: usize,
258 /// Maximum review+fix rounds before the run is declared blocked.
259 pub review_rounds: usize,
260 /// Fix rounds a failing `verify.gate` gets before the run is blocked. The
261 /// fixer is handed the gate's own output; `0` keeps the old behaviour of
262 /// blocking on the first red gate. Independent of [`Self::review_rounds`]
263 /// so a run that spent its review budget can still repair a one-line gate
264 /// failure.
265 pub gate_fix_rounds: usize,
266 /// Maximum agent processes running at once.
267 pub max_parallel: usize,
268 /// Language for the prose the agents write (`en` / `ja` / any language name).
269 pub language: String,
270 /// Keep one CLI conversation per seat, so a judge remembers its own
271 /// argument across deliberation rounds and the fixer remembers its own
272 /// implementation across review rounds.
273 ///
274 /// Sessions are scoped to a *seat*, never to an agent id: the same model
275 /// sitting as implementer and as judge gets two unrelated conversations,
276 /// which is what keeps blind judging blind.
277 pub sessions: bool,
278 /// Per-node timeouts, seconds.
279 pub timeout_implement: u64,
280 /// Per-node timeouts, seconds.
281 pub timeout_judge: u64,
282 /// Per-node timeouts, seconds.
283 pub timeout_review: u64,
284 /// Timeout for `verify.e2e` and `verify.gate`, seconds. Separate from
285 /// [`Self::timeout_review`] so shrinking a reviewer's budget cannot
286 /// silently shrink a real-machine command's budget too — the two used to
287 /// share `timeout_review`, and turning a slow reviewer down cut the
288 /// timeout `cargo test --all-targets` runs under along with it. When
289 /// omitted, preserves legacy configurations by using
290 /// [`Self::timeout_review`]. Set an explicit value to make verification
291 /// independent of later review-seat budget changes.
292 pub timeout_verify: Option<u64>,
293 /// Per-node timeouts, seconds.
294 pub timeout_fix: u64,
295 /// Wall-clock limit for one turn of [`crate::talk`]'s standing
296 /// conversation, seconds.
297 ///
298 /// An hour: the operator is not watching this turn resolve in real time,
299 /// so the budget can match what the work - reading files, running
300 /// commands, checking their output - actually needs rather than what a
301 /// person waiting on a phone can tolerate.
302 pub timeout_talk: u64,
303 /// Retries for an agent invocation that fails or returns nothing usable.
304 pub retries: usize,
305 /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
306 pub worktree_root: Option<PathBuf>,
307 /// After the pull request is open, keep going: watch its checks and
308 /// reviews, run a fix round when they are unhappy, and ask to merge.
309 ///
310 /// On, because stopping at an open pull request left the operator doing
311 /// the watching by hand - six times in the session this was built in - and
312 /// that is the work the loop exists to take. It only engages for
313 /// `merge = "pr"`; every other merge mode ends the run as before.
314 ///
315 /// Turning this on does **not** hand magi the merge button:
316 /// [`Graph::land_approval`] is on too, and nothing merges without an
317 /// explicit answer. Setting both to their non-defaults is the only way to
318 /// get an unattended merge, and it has to be chosen twice.
319 pub land: bool,
320 /// Land rounds - watch, fix, push - before the run is left for a human.
321 pub land_rounds: usize,
322 /// Ask the owner before merging, showing what is about to land.
323 ///
324 /// On, and it is what makes `land` safe to have on: the question carries a
325 /// rendered panel - the diffstat, the patch, the checks, the review
326 /// comments that were addressed, and the subject the squash will use - so
327 /// the decision is made on evidence rather than on trust, from wherever
328 /// the operator happens to be.
329 ///
330 /// Silence is a hold. An unanswered approval never merges, and neither
331 /// does any answer other than the word `merge`.
332 pub land_approval: bool,
333 /// How long to wait for an owner to answer a question before the run is
334 /// abandoned, seconds. A parked run costs nothing, so this is generous;
335 /// it exists so a forgotten question cannot pin a worktree forever.
336 pub answer_timeout: u64,
337 /// What a round does when one or more reviewer seats never answered
338 /// (timeout, crash, unparsable output).
339 pub incomplete_review: IncompleteReviewPolicy,
340 /// Run `verify.e2e` on every round, even one that already has blocking
341 /// findings and another round left to try.
342 ///
343 /// Off by default: a round with a blocking finding and rounds still left
344 /// is going back to the fixer regardless of what `verify.e2e` says, so
345 /// running it first only spends the round's slowest step (minutes, on a
346 /// Rust repo's `cargo test --all-targets`) on a head about to be
347 /// rewritten anyway. `verify.e2e` still runs once a round has no
348 /// blocking findings left (a round cannot go `clean` without it) and the
349 /// final `verify.gate` always runs on the actual tree that would land —
350 /// deferring is about *when* e2e runs mid-loop, never about skipping it.
351 ///
352 /// Set this to restore the old every-round diagnostic behaviour: e2e
353 /// output from a round that still has blocking findings is occasionally
354 /// useful on its own (a runtime failure a reviewer's panel would not
355 /// have caught by reading), and this is the way back to seeing it every
356 /// round instead of only once the panel has nothing left to flag.
357 pub e2e_every_round: bool,
358 /// Run the design-deliberation stage before `implement`: independent
359 /// advisor seats each sketch a design, and (when at least one produced a
360 /// usable proposal) a synthesis blends them into a brief carried in the
361 /// implementer's prompt. See `graph::Runner::advise`.
362 ///
363 /// On by default. A design sketch is a few paragraphs an agent can write
364 /// without touching the repository, where a full implementation is a
365 /// tool loop that re-reads the codebase on every turn - so three
366 /// sketches, gathered once before `implement` starts, cost a fraction of
367 /// a fourth candidate and buy back a form of the same disagreement
368 /// [`Self::candidates`]'s doc describes moving away from being the
369 /// default, on every run rather than only the ones an operator remembers
370 /// to ask for with `--candidates`.
371 pub advise: bool,
372 /// How many independent design proposals the deliberation stage gathers.
373 /// **Three by default** - the same number [`Self::candidates`]'s doc
374 /// names as the point where a fourth judge's first choice stopped
375 /// changing the tally.
376 pub advisors: usize,
377}
378
379impl Default for Graph {
380 fn default() -> Self {
381 Self {
382 candidates: 1,
383 judges: 3,
384 deliberate_rounds: 1,
385 reviewers: 3,
386 review_rounds: 6,
387 gate_fix_rounds: 1,
388 max_parallel: 4,
389 language: "en".to_owned(),
390 sessions: true,
391 timeout_implement: 3600,
392 timeout_judge: 1200,
393 timeout_review: 1200,
394 timeout_verify: None,
395 timeout_fix: 1800,
396 timeout_talk: 3600,
397 retries: 1,
398 worktree_root: None,
399 land: true,
400 land_rounds: 4,
401 land_approval: true,
402 answer_timeout: 86_400,
403 incomplete_review: IncompleteReviewPolicy::Block,
404 e2e_every_round: false,
405 advise: true,
406 advisors: 3,
407 }
408 }
409}
410
411impl Graph {
412 /// Effective machine-command budget. Older configuration files had only
413 /// `timeout_review`, which also governed verification, so absence is a
414 /// compatibility fallback rather than a new 1200-second default.
415 pub fn verify_timeout(&self) -> u64 {
416 self.timeout_verify.unwrap_or(self.timeout_review)
417 }
418}
419
420/// What a review round does when a reviewer seat never answered.
421///
422/// A round where half the panel timed out is not evidence of a clean patch —
423/// it is evidence of nothing. The default refuses to call that clean; `warn`
424/// exists for an operator who would rather keep a flaky seat from stalling
425/// every run, and accepts that the gap is on them to read in the report.
426#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
427#[serde(rename_all = "lowercase")]
428pub enum IncompleteReviewPolicy {
429 /// A round with a missing seat is never `clean`: with nothing raised to
430 /// fix, the round is re-reviewed instead of gating; with the max rounds
431 /// exhausted, the run is left `Blocked` rather than declared ready.
432 Block,
433 /// A round with a missing seat can still gate as clean, once every seat
434 /// that *did* answer raised nothing blocking and verification is green.
435 /// The record keeps the gap visible (`magi show`, `magi stats`) even
436 /// though the run does not wait on it.
437 Warn,
438}
439
440/// What to do when vendor-identifying text is found in material shown to judges.
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
442#[serde(rename_all = "lowercase")]
443pub enum LeakPolicy {
444 /// Record the leak, show the patch unmodified.
445 Warn,
446 /// Replace the token with `[REDACTED]` in the presented patch.
447 Redact,
448 /// Abort the run.
449 Fail,
450}
451
452/// Blindness policy.
453///
454/// Commit messages and candidate summaries are *always* stripped of
455/// attribution trailers and redacted — that is where signatures actually
456/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
457/// redaction would corrupt the artifact under judgement.
458#[derive(Debug, Clone, Deserialize, Serialize)]
459#[serde(deny_unknown_fields, default)]
460pub struct Blind {
461 /// Install a per-worktree `commit-msg` hook that deletes attribution
462 /// trailers before they can land in a candidate's history.
463 pub commit_msg_hook: bool,
464 /// Literal, case-insensitive substrings. A line containing any of them is
465 /// dropped from commit messages and summaries; the `commit-msg` hook is
466 /// generated from the same list.
467 pub strip_lines: Vec<String>,
468 /// Case-insensitive substrings that identify a vendor or model.
469 pub vendor_tokens: Vec<String>,
470 /// Policy for vendor tokens found in the patch body.
471 pub on_leak: LeakPolicy,
472 /// Seed for label assignment and per-judge presentation order. Derived from
473 /// the run id when unset; set it to make a run reproducible.
474 pub seed: Option<u64>,
475}
476
477impl Default for Blind {
478 fn default() -> Self {
479 Self {
480 commit_msg_hook: true,
481 strip_lines: [
482 "Co-Authored-By:",
483 "Signed-off-by:",
484 "Assisted-by:",
485 "Generated-by:",
486 "Generated with",
487 "\u{1f916}",
488 ]
489 .iter()
490 .map(|s| (*s).to_owned())
491 .collect(),
492 vendor_tokens: [
493 "claude",
494 "anthropic",
495 "codex",
496 "openai",
497 "chatgpt",
498 "gemini",
499 "grok",
500 "xai",
501 "copilot",
502 "opencode",
503 "qoder",
504 "cursor",
505 "\u{1f916}",
506 ]
507 .iter()
508 .map(|s| (*s).to_owned())
509 .collect(),
510 on_leak: LeakPolicy::Warn,
511 seed: None,
512 }
513 }
514}
515
516/// Shell commands that gate the winner.
517#[derive(Debug, Clone, Default, Deserialize, Serialize)]
518#[serde(deny_unknown_fields, default)]
519pub struct Verify {
520 /// Run in the winner's worktree once per review round. Its output is fed
521 /// back to the fixer. This is the "real machine" leg of the review.
522 pub e2e: Vec<String>,
523 /// Final gate. Must all exit 0 before a merge is attempted.
524 pub gate: Vec<String>,
525 /// Mechanical fixers (formatters) run in the winner's worktree just before
526 /// `gate`, after review is clean. Anything they change is committed as one
527 /// neutral-identity commit so the gate and the PR see it. A command that
528 /// fails or times out is a warning, never a failed run: the gate stays the
529 /// single arbiter. Empty (the default) turns the feature off. Runs under
530 /// `graph.verify_timeout()` per command, like the gate. Meant for light
531 /// tools: it is not scanned for `CARGO_TARGET_DIR`, and it should be
532 /// idempotent since a resumed run may repeat it.
533 #[serde(default)]
534 pub pre_gate: Vec<String>,
535 /// Shell used to run the commands above. Defaults to `sh -c`, or
536 /// `cmd /C` when `sh` is not on `PATH`.
537 pub shell: Option<Vec<String>>,
538}
539
540impl Verify {
541 /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
542 /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
543 /// this reads back. One rendering is enough - they all set the same
544 /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
545 /// command is checked before the gate because the e2e rebuilds the crate.
546 pub fn cache_dir(&self) -> Option<PathBuf> {
547 self.e2e
548 .iter()
549 .chain(self.gate.iter())
550 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
551 }
552}
553
554/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
555///
556/// The numbers below come from one incident, not from theory: a machine with
557/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
558/// Three multi-gigabyte classes of junk accumulated side by side - per-run
559/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
560/// each verify round and each implementation wave recompiles the derived
561/// section of the project into, and the outputs of runs that were removed but
562/// whose folders nobody deleted.
563#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
564#[serde(deny_unknown_fields, default)]
565pub struct Disk {
566 /// Free space, in bytes, below which no new run may start: the daemon and
567 /// the `magi run` gate answer with "the disk is full" instead of letting
568 /// the graph fill it the rest of the way. `0` turns the gate off.
569 ///
570 /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
571 /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
572 /// competition triggers and small enough that a 1 TB disk with 100 GB free
573 /// is nowhere near the threshold.
574 pub min_free_bytes: u64,
575 /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
576 /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
577 /// worktrees removed. `0` turns the janitor off.
578 ///
579 /// Default true.
580 pub auto_fold: bool,
581 /// How old a finished run must be before the janitor folds it, seconds.
582 ///
583 /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
584 /// run that `Ready` a week ago is worktrees holding a compile each. Six
585 /// hours is long enough that nobody loses an answer in the gap between
586 /// reading the report and starting from it, and short enough that a backlog
587 /// cannot pile up across two nights.
588 pub fold_grace_secs: u64,
589 /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
590 /// verify commands), in bytes. When the janitor runs and the cache is over
591 /// it, files are dropped oldest-first until it is not. `0` turns pruning
592 /// off - the cache then only ever grows, which is the operator's call.
593 ///
594 /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
595 /// shared cache on top of ~16 GB in the primary target directory and 6.7-
596 /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
597 /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
598 /// pruning only costs the rebuild of the dropped files, not of the world)
599 /// without letting one addled cache swallow the machine.
600 pub cache_limit_bytes: u64,
601}
602
603impl Default for Disk {
604 fn default() -> Self {
605 Self {
606 min_free_bytes: 8 * 1024 * 1024 * 1024,
607 auto_fold: true,
608 fold_grace_secs: 6 * 60 * 60,
609 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
610 }
611 }
612}
613
614/// What to do with the winning branch.
615#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
616#[serde(rename_all = "lowercase")]
617pub enum MergeMode {
618 /// Leave the branch alone and print the merge command matching
619 /// [`Merge::style`].
620 None,
621 /// Merge into the base branch in the primary worktree, using
622 /// [`Merge::style`].
623 Local,
624 /// Push the branch and open a PR with `gh pr create`. Landing this PR
625 /// (`[graph] land`) always squashes — see `land`'s module doc — so
626 /// [`Merge::style`] does not apply here.
627 Pr,
628}
629
630/// How the winning branch is attached to the base branch: what
631/// `mode = "local"` runs, and what `mode = "none"`'s printed guidance tells
632/// the operator to run by hand.
633///
634/// Read from configuration rather than asked of the repository at run time
635/// (e.g. `gh api repos/{owner}/{repo}/rulesets`) for two reasons: it keeps
636/// `mode = "none"`'s guidance a pure function of `RunState`, assertable in a
637/// unit test the same way `land::decide` is kept pure (see that module's
638/// doc), and it works for a base branch that is not hosted on GitHub, or not
639/// reachable at all, at the moment the report is rendered. An operator whose
640/// base branch enforces a ruleset already knows what it allows; declaring it
641/// once here is cheaper than magi re-discovering it, with a network call, on
642/// every render.
643#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
644#[serde(rename_all = "lowercase")]
645pub enum MergeStyle {
646 /// `git merge --no-ff`: every candidate commit lands, plus a merge
647 /// commit that records the merge as its own event in history. Rejected
648 /// by a base branch whose ruleset requires linear history or forbids
649 /// merge commits outright.
650 #[default]
651 Merge,
652 /// `git merge --squash` followed by a commit under an explicit message:
653 /// every candidate commit folds into one, and none of the candidate's
654 /// own placeholder subjects (`magi: candidate A (uncommitted work)`)
655 /// reach the base branch. No merge commit, so this satisfies a linear-
656 /// history ruleset.
657 Squash,
658 /// A fast-forward-only merge: every candidate commit lands verbatim, in
659 /// order, with no merge commit. Only succeeds because the winner was
660 /// already rebased onto the tracked base tip before this runs (see
661 /// `Runner::sync_to_base`) — equivalent to GitHub's "rebase and merge"
662 /// once that has happened.
663 Rebase,
664}
665
666/// Merge policy.
667#[derive(Debug, Clone, Deserialize, Serialize)]
668#[serde(deny_unknown_fields, default)]
669pub struct Merge {
670 /// Default is [`MergeMode::None`]: magi never touches your base branch
671 /// unless you ask it to.
672 pub mode: MergeMode,
673 /// Base branch. Defaults to the branch checked out when the run started.
674 pub base: Option<String>,
675 /// How the winner is attached to `base`; see [`MergeStyle`]. Ignored by
676 /// `mode = "pr"`.
677 pub style: MergeStyle,
678 /// Remote for `mode = "pr"`.
679 pub remote: String,
680 /// After a `mode = "pr"` run lands, open a `chore/release-vX.Y.Z` pull
681 /// request sized to the change by an agent's own judgement, so a version
682 /// bump does not depend on a human remembering to cut one.
683 ///
684 /// On by default. **Turning this off means a merge landed from the phone
685 /// never becomes a release**, so `POST /api/upgrade` keeps reporting
686 /// "already on the newest release" against a `main` that has moved past
687 /// it - the same gap this feature exists to close. Only for a repository
688 /// that wants to keep cutting releases by hand.
689 pub release_bump: bool,
690}
691
692impl Default for Merge {
693 fn default() -> Self {
694 Self {
695 mode: MergeMode::None,
696 base: None,
697 style: MergeStyle::default(),
698 remote: "origin".to_owned(),
699 release_bump: true,
700 }
701 }
702}
703
704/// How magi keeps itself current.
705#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
706#[serde(rename_all = "lowercase")]
707pub enum UpdateMode {
708 /// Never check.
709 Off,
710 /// Check in the background and print a one-line banner when a newer
711 /// release exists.
712 Notify,
713 /// Check and install silently.
714 Install,
715}
716
717/// Self-update policy.
718#[derive(Debug, Clone, Deserialize, Serialize)]
719#[serde(deny_unknown_fields, default)]
720pub struct Update {
721 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
722 pub mode: UpdateMode,
723 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
724 pub interval: Option<String>,
725}
726
727impl Default for Update {
728 fn default() -> Self {
729 Self {
730 mode: UpdateMode::Notify,
731 interval: None,
732 }
733 }
734}
735
736/// Top-level configuration.
737#[derive(Debug, Clone, Default, Deserialize, Serialize)]
738#[serde(deny_unknown_fields, default)]
739pub struct Config {
740 /// Agent roster.
741 pub agents: Vec<AgentSpec>,
742 /// Role assignment.
743 pub roles: Roles,
744 /// Graph shape.
745 pub graph: Graph,
746 /// Blindness policy.
747 pub blind: Blind,
748 /// Verification commands.
749 pub verify: Verify,
750 /// Disk hygiene.
751 pub disk: Disk,
752 /// Merge policy.
753 pub merge: Merge,
754 /// Self-update policy.
755 pub update: Update,
756 /// Project-specific text appended to the node prompts.
757 pub prompts: Prompts,
758 /// How the operator is told a run is waiting on them.
759 pub notify: Notify,
760 /// Local repositories the plan surface can start or derive a conversation
761 /// against.
762 pub repos: Repos,
763 /// Policy for the standing conversation ([`crate::talk`]).
764 pub talk: Talk,
765 /// How many runs `magi serve`'s own loop drives at once.
766 pub daemon: Daemon,
767}
768
769/// How the daemon loop itself behaves, as opposed to what one run does.
770///
771/// Machine-layer material in the same sense [`Repos::roots`] is: how many
772/// competitions this machine's own loop is willing to babysit at once is a
773/// fact about the machine running `magi serve`, not about any one
774/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
775/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
776/// nothing stops a repository from setting it too, since a scalar field
777/// takes whichever layer has the highest precedence.
778#[derive(Debug, Clone, Deserialize, Serialize)]
779#[serde(deny_unknown_fields, default)]
780pub struct Daemon {
781 /// How many runs `magi serve` may have actively in flight at once.
782 /// **One by default** - today's behaviour, one run at a time.
783 ///
784 /// This is a different knob from [`Graph::max_parallel`], and the two
785 /// must not be confused: `max_parallel` bounds how many agent *processes*
786 /// one run starts inside itself (implementers, judges, reviewers -
787 /// candidates competing on a single task); this field bounds how many
788 /// *runs* - whole competitions, each with its own `max_parallel` budget -
789 /// the loop drives side by side, possibly across different tasks and
790 /// different repositories. Raising `max_parallel` buys a bigger panel for
791 /// one task; raising this buys more tasks worked at once. A config file
792 /// that meant one and wrote the other would either starve a competition
793 /// of judges or leave the rest of the backlog waiting for no reason.
794 ///
795 /// A run parked waiting on the operator's land-merge approval - see
796 /// [`crate::land`] - does not hold one of these slots while it waits: the
797 /// whole point of parking there is to let the loop spend the slot on
798 /// something runnable instead of sitting on a decision only a human can
799 /// make. So even at the default of `1`, an approval that comes back does
800 /// not queue behind whatever else the loop happens to be running.
801 pub max_concurrent_runs: usize,
802 /// Let a task marked [`crate::queue::Task::interrupt`] (`magi task
803 /// interrupt`) cut ahead of whatever `magi serve` already has in flight,
804 /// instead of waiting for it to finish.
805 ///
806 /// **Off by default.** When enabled, a run that is in flight and is not
807 /// itself the interrupt candidate may be paused at its next safe node
808 /// boundary - see [`crate::graph::Runner::park_here`] - so the marked
809 /// task can run alone; the paused run resumes automatically, through the
810 /// same path any other parked run does, the moment the interrupting
811 /// task's own run reaches a terminal status. This is opt-in because it
812 /// bends the loop's own "one run at a time" principle (see this repository's
813 /// `magi serve` help) for a specific, explicit operator request, and a
814 /// repository that never files an interrupt task pays nothing for having
815 /// it on - but an operator who does not want any run of theirs preempted,
816 /// ever, should leave this `false`.
817 pub pause_for_interrupts: bool,
818}
819
820impl Default for Daemon {
821 fn default() -> Self {
822 Self {
823 max_concurrent_runs: 1,
824 pause_for_interrupts: false,
825 }
826 }
827}
828
829/// Where `magi repos` and `GET /api/repos` look for local checkouts.
830///
831/// `roots` is one of the array keys [`array_merge_policy`] marks as
832/// append-across-layers: which checkouts exist in general is a *machine*
833/// fact in the same way the agent roster is - a repository's own `magi.toml`
834/// cannot state where its siblings live before magi has resolved which
835/// repository to read that file from in the first place - but a repository
836/// that genuinely has an extra root worth scanning is not forced to choose
837/// between an error and losing the machine's roots outright. Both layers'
838/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
839/// are still refused.
840#[derive(Debug, Clone, Deserialize, Serialize)]
841#[serde(deny_unknown_fields, default)]
842pub struct Repos {
843 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
844 /// with a `.git` directory. Empty by default - nothing is scanned unless
845 /// asked to be.
846 pub roots: Vec<PathBuf>,
847 /// How long a scan is trusted before the next request re-scans it,
848 /// seconds. `0` means never trust it: scan on every request. Defaults to
849 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
850 /// the same reason - a checkout does not usually appear or vanish inside
851 /// a session, so there is little to gain from scanning more often than
852 /// that, and an explicit refresh exists for the moment one does.
853 pub scan_ttl: u64,
854}
855
856impl Default for Repos {
857 fn default() -> Self {
858 Self {
859 roots: Vec::new(),
860 scan_ttl: 86_400,
861 }
862 }
863}
864
865/// Project-specific text appended to each node's prompt.
866///
867/// **Additive by construction.** These fields cannot replace magi's prompts,
868/// only extend them, and that restriction is the whole design. The built-in
869/// prompts carry the invariants the competition rests on: a judging prompt
870/// names no authors, every structured answer must arrive as one fenced `json`
871/// block, and a judge is told not to speculate about who wrote what. A config
872/// that could overwrite them would let a typo silently un-blind the panel or
873/// break the parser, and the symptom would be "the judges got worse" rather
874/// than an error.
875///
876/// Repository-wide context belongs in `AGENTS.md`, which every agent already
877/// reads from the checkout. Use these fields for the things a *magi node*
878/// needs to know and a repository file cannot say - for instance that
879/// reviewers here should ignore formatting because a hook owns it.
880#[derive(Debug, Clone, Default, Deserialize, Serialize)]
881#[serde(deny_unknown_fields, default)]
882pub struct Prompts {
883 /// Appended to every node's prompt.
884 pub all: String,
885 /// Appended for implementers.
886 pub implement: String,
887 /// Appended for judges, both ranking and voting.
888 pub judge: String,
889 /// Appended for reviewers.
890 pub review: String,
891 /// Appended for the fixer.
892 pub fix: String,
893}
894
895impl Prompts {
896 /// The overlay for one node, or `None` when nothing is configured.
897 ///
898 /// `node` is the graph's own node name, so a new node gets no overlay
899 /// rather than the wrong one.
900 pub fn overlay(&self, node: &str) -> Option<String> {
901 let specific = match node {
902 "implement" => &self.implement,
903 "judge" | "vote" | "deliberate" => &self.judge,
904 "review" => &self.review,
905 "fix" => &self.fix,
906 _ => "",
907 };
908 let mut parts: Vec<&str> = Vec::new();
909 for p in [self.all.trim(), specific.trim()] {
910 if !p.is_empty() {
911 parts.push(p);
912 }
913 }
914 if parts.is_empty() {
915 return None;
916 }
917 Some(parts.join("\n\n"))
918 }
919}
920
921/// How the operator is told that a run is waiting on them.
922///
923/// A command rather than a built-in integration: magi is one binary with no
924/// network dependencies, and every operator's notification path is different -
925/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
926/// Shelling out keeps all of them possible and none of them magi's problem.
927#[derive(Debug, Clone, Default, Deserialize, Serialize)]
928#[serde(deny_unknown_fields, default)]
929pub struct Notify {
930 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
931 /// Empty means no notification - the web UI is then the only surface.
932 pub command: Vec<String>,
933}
934
935/// Policy for [`crate::talk`], the standing conversation.
936#[derive(Debug, Clone, Default, Deserialize, Serialize)]
937#[serde(deny_unknown_fields, default)]
938pub struct Talk {
939 /// Let the conversation's agent edit files in the repository instead of
940 /// filing a task for one. **Off by default** - see
941 /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
942 /// an edit no run and no review can be attributed to, which is exactly
943 /// the property a repository entered in a competition depends on. A
944 /// repository that is never judged - dotfiles, a personal config
945 /// checkout - has nothing to lose by turning this on in its own
946 /// `magi.toml`, and a one-line fix stops costing a queued task to get.
947 pub allow_write: bool,
948}
949
950/// Roles resolved to concrete agent specs for one run.
951#[derive(Debug, Clone)]
952pub struct ResolvedRoles {
953 /// One per candidate.
954 pub implementers: Vec<AgentSpec>,
955 /// One per judge.
956 pub judges: Vec<AgentSpec>,
957 /// One per reviewer slot.
958 pub reviewers: Vec<AgentSpec>,
959 /// Explicit fixer, if configured.
960 pub fixer: Option<AgentSpec>,
961 /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
962 pub conductor: AgentSpec,
963 /// The full ordered implementer roster, in [`Roles::implementers`]'s own
964 /// order — or `[[agents]]` in file order, when that list is empty. Unlike
965 /// [`Self::implementers`], never truncated to `graph.candidates` and
966 /// never `rotate`d/wrapped: a solo run (`candidates = 1`) resolves
967 /// `implementers` down to a single slot, but `graph::Runner`'s per-seat
968 /// quota fallback needs the *whole* list to walk forward through when
969 /// that one slot's agent runs out of quota mid-run.
970 pub implementer_roster: Vec<AgentSpec>,
971}
972
973/// Every array-valued key in a config table, as a dotted path.
974///
975/// Dotted so the error names `roles.implementers` rather than `implementers`:
976/// an operator with three config files needs to know which key, not just that
977/// there was one. `vars` is skipped because it is teravars' own input, merged
978/// on purpose and never deserialised into `Config`.
979fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
980 let mut out = Vec::new();
981 for (k, v) in table {
982 if prefix.is_empty() && k == "vars" {
983 continue;
984 }
985 let path = if prefix.is_empty() {
986 k.clone()
987 } else {
988 format!("{prefix}.{k}")
989 };
990 match v {
991 toml::Value::Array(_) => out.push(path),
992 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
993 _ => {}
994 }
995 }
996 out
997}
998
999/// How an array key behaves when two config layers both declare it.
1000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1001enum ArrayMerge {
1002 /// Two layers may both declare it; the composed value is the
1003 /// low-to-high-priority concatenation teravars already produces (see
1004 /// [`Config::load_layers`]'s doc for why that order and no dedup).
1005 Append,
1006 /// Two layers declaring it is refused; see
1007 /// [`Config::refuse_split_arrays`].
1008 Replace,
1009}
1010
1011/// The single place that decides, for a dotted array key (as returned by
1012/// [`array_keys`]), whether declaring it in two config layers is a
1013/// concatenation the operator asked for or a silent accident.
1014///
1015/// Kept as one match so the whole policy is visible in one place - the same
1016/// reason `claude_quota` and `dropped_stream` close their own classification
1017/// in one spot elsewhere in this codebase. Anything not listed defaults to
1018/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
1019/// reasoned about yet, and a new array key added later has to be added here
1020/// deliberately to become appendable.
1021///
1022/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
1023/// gate. Concatenating two of them is exactly the checks both layers
1024/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
1025/// live in a shared layer while a repository's own layer adds its own
1026/// command, instead of every repository copying the shared command into
1027/// its own file.
1028/// - `repos.roots` — a set of directories to scan for checkouts. A
1029/// repository adding its own root on top of the machine's is additive by
1030/// nature, not a replacement of where the machine looks; see
1031/// [`Repos::roots`].
1032///
1033/// Left on the refuse side, and why:
1034/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
1035/// list of *seats*, not a set. A machine's two implementers plus a
1036/// repository's one is three seats nobody asked for and nobody is paying
1037/// for on purpose.
1038/// - `notify.command` — an argv. Concatenating two argvs does not produce a
1039/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
1040/// - `blind.strip_lines` — technically safe to concatenate (each entry is
1041/// matched as an independent substring, so a longer list only strips
1042/// *more*), but left on the refuse side anyway: the same list also drives
1043/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
1044/// and a silent three-layer merge is exactly the kind of surprise
1045/// `refuse_split_arrays` exists to catch rather than to reason about
1046/// case-by-case. A repository that wants one more stripped phrase restates
1047/// the whole list; that restatement is visible in review, an accidental
1048/// concatenation would not be.
1049fn array_merge_policy(key: &str) -> ArrayMerge {
1050 match key {
1051 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1052 _ => ArrayMerge::Replace,
1053 }
1054}
1055
1056impl Config {
1057 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1058 /// and the `include = [...]` directive.
1059 pub fn load(path: &Path) -> Result<Self> {
1060 Self::load_layers(&[path.to_path_buf()])
1061 }
1062
1063 /// The Tera render context shared by every layer: `system.*` (from
1064 /// teravars), `env` (magi's own addition - a config that names a shared
1065 /// build-cache directory or a machine-specific path needs
1066 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1067 /// derived from the last (highest-priority) path's parent directory.
1068 ///
1069 /// Factored out so [`Config::array_provenance`] can re-render a single
1070 /// layer under the exact same context [`Config::load_layers`] uses for
1071 /// the joint render, rather than drifting from it by accident.
1072 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1073 let mut ctx = teravars::system_context();
1074 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1075 ctx.insert("env", &env);
1076 if let Some(last) = paths.last()
1077 && let Some(dir) = last.parent()
1078 {
1079 ctx.insert("repo", &dir.to_string_lossy());
1080 ctx.insert(
1081 "repo_name",
1082 &dir.file_name().unwrap_or_default().to_string_lossy(),
1083 );
1084 }
1085 ctx
1086 }
1087
1088 /// Load and deep-merge a stack of config files, later files winning.
1089 ///
1090 /// This is why the config is TOML-through-teravars rather than plain serde:
1091 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1092 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1093 /// there). Picking one file and ignoring the other would force every repo
1094 /// to restate the roster.
1095 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1096 let mut engine = teravars::Engine::default();
1097 let ctx = Self::render_ctx(paths);
1098 if paths.len() > 1 {
1099 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
1100 }
1101 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
1102 format!(
1103 "rendering config via teravars: {}",
1104 paths
1105 .iter()
1106 .map(|p| p.display().to_string())
1107 .collect::<Vec<_>>()
1108 .join(", ")
1109 )
1110 })?;
1111 let mut table = merged.config;
1112 // `[vars]` is teravars' own input, already resolved into the render
1113 // context; `deny_unknown_fields` must not trip over it.
1114 table.remove("vars");
1115 toml::Value::Table(table)
1116 .try_into()
1117 .context("deserializing magi config")
1118 }
1119
1120 /// Refuse an array that two layers both declare, unless
1121 /// [`array_merge_policy`] says that key is meant to accumulate.
1122 ///
1123 /// teravars **appends** arrays when it merges layers, and that is wrong for
1124 /// most arrays magi has: `implementers` is an ordered list of seats,
1125 /// `notify.command` is an argv. Concatenating two of them yields something
1126 /// nobody wrote - three implementers out of a machine's two and a
1127 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1128 ///
1129 /// Replacing instead would be the right merge rule for those keys, but the
1130 /// rule lives in teravars, which several other projects depend on;
1131 /// changing it there is a decision for that crate, not something to fake
1132 /// here by re-reading the files with different semantics and hoping the
1133 /// two paths agree.
1134 ///
1135 /// So magi refuses the ambiguity rather than resolving it silently, for
1136 /// every array key except the short, deliberate list
1137 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1138 /// concatenation teravars already produces *is* what both files say, so
1139 /// there is nothing to refuse. The cost of guessing wrong on the refused
1140 /// keys is a roster the operator did not ask for and is paying for by the
1141 /// token; the append keys carry no such risk because every element runs
1142 /// (or every directory is scanned) regardless of order.
1143 fn refuse_split_arrays(
1144 paths: &[PathBuf],
1145 engine: &mut teravars::Engine,
1146 ctx: &teravars::Context,
1147 ) -> Result<()> {
1148 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1149 for path in paths {
1150 let one = teravars::load_merged([path], engine, ctx)
1151 .with_context(|| format!("rendering {}", path.display()))?;
1152 for key in array_keys(&one.config, "") {
1153 if array_merge_policy(&key) == ArrayMerge::Append {
1154 continue;
1155 }
1156 if let Some(first) = seen.get(&key) {
1157 bail!(
1158 "`{key}` is an array declared in two config layers:\n \
1159 {}\n {}\nteravars appends arrays when it merges, so \
1160 magi would run the concatenation of both - which is \
1161 not what either file says. Declare `{key}` in exactly \
1162 one of them.",
1163 first.display(),
1164 path.display()
1165 );
1166 }
1167 seen.insert(key, path.clone());
1168 }
1169 }
1170 Ok(())
1171 }
1172
1173 /// Which layers contributed to a composed, appendable array key (e.g.
1174 /// `"verify.gate"`), in the same low-to-high-priority order
1175 /// [`Config::load_layers`] concatenates them in. Layers that do not
1176 /// declare `key` at all are omitted.
1177 ///
1178 /// This is a **display aid for `magi doctor` only.** The command list
1179 /// that actually runs always comes from the one joint
1180 /// [`teravars::load_merged`] call in `load_layers`, never from this
1181 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
1182 /// about is two merge paths that might disagree, so this function must
1183 /// never become a second source of the *composed* value, only of which
1184 /// file wrote which line in it.
1185 ///
1186 /// Re-rendering each layer alone can, in principle, resolve a
1187 /// `{{ vars.x }}` differently than the joint render would, if `x` is
1188 /// defined in one layer and referenced in another - the same caveat
1189 /// `refuse_split_arrays`'s structural, key-only check already lives with.
1190 /// None of magi's own gate commands cross that line, and a doctor listing
1191 /// is read by a human who can compare it against the joint one printed
1192 /// alongside it, so this is judged worth the simplicity of not
1193 /// threading provenance through the real load path.
1194 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1195 let mut engine = teravars::Engine::default();
1196 let ctx = Self::render_ctx(paths);
1197 let mut out = Vec::new();
1198 for path in paths {
1199 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1200 continue;
1201 };
1202 let mut cur = &one.config;
1203 let mut found = None;
1204 let parts: Vec<&str> = key.split('.').collect();
1205 for (i, part) in parts.iter().enumerate() {
1206 match cur.get(*part) {
1207 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1208 found = Some(a);
1209 break;
1210 }
1211 Some(toml::Value::Table(t)) => cur = t,
1212 _ => break,
1213 }
1214 }
1215 let Some(values) = found else { continue };
1216 let strings: Vec<String> = values
1217 .iter()
1218 .filter_map(|v| v.as_str().map(str::to_owned))
1219 .collect();
1220 if !strings.is_empty() {
1221 out.push((path.clone(), strings));
1222 }
1223 }
1224 out
1225 }
1226
1227 /// Render a composed command list for `magi doctor`: the joined command
1228 /// line the run actually uses, plus - only when more than one layer
1229 /// contributed - which layer wrote which line.
1230 ///
1231 /// A single contributing layer (the common case today) stays the plain
1232 /// one-line summary magi has always printed, `empty` included: that
1233 /// honest "(none — ...)" is what caught a real gate-composition gap
1234 /// before this array could compose at all, and composition should not
1235 /// make the common case noisier.
1236 pub fn describe_composed(
1237 paths: &[PathBuf],
1238 commands: &[String],
1239 key: &str,
1240 empty: &str,
1241 ) -> String {
1242 if commands.is_empty() {
1243 return empty.to_owned();
1244 }
1245 let joined = commands.join(" && ");
1246 let provenance = Self::array_provenance(paths, key);
1247 if provenance.len() <= 1 {
1248 return joined;
1249 }
1250 let mut out = joined;
1251 for (path, cmds) in &provenance {
1252 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1253 }
1254 out
1255 }
1256
1257 /// Resolve the config for `repo`, honouring an explicit `--config` path.
1258 ///
1259 /// Returns the config and the layers it came from, empty for built-in
1260 /// defaults.
1261 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1262 if let Some(p) = explicit {
1263 let paths = vec![p.to_path_buf()];
1264 return Ok((Self::load_layers(&paths)?, paths));
1265 }
1266 let paths = Self::layers(repo);
1267 if paths.is_empty() {
1268 return Ok((Self::autodetected(), paths));
1269 }
1270 Ok((Self::load_layers(&paths)?, paths))
1271 }
1272 /// Environment variable that relocates the machine-wide config layer.
1273 ///
1274 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1275 /// of the one under [`dirs::config_dir`]; set it to the empty string and
1276 /// magi reads no machine layer at all.
1277 ///
1278 /// This exists because the machine layer is otherwise unavoidable, and a
1279 /// test that builds a config fixture is not asking for the operator's
1280 /// preferences to be merged into it. Adding `[repos] roots` to the real
1281 /// machine config on a development box turned two passing tests red -
1282 /// `repos_list_returns_name_and_path_for_every_configured_root` and
1283 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1284 /// declare `[repos] roots` of their own, which [`Config::layers`] then
1285 /// found in two layers and [`Config::refuse_split_arrays`] correctly
1286 /// refused. CI never saw it: a runner has no machine config, so the suite
1287 /// was green there and red only where somebody actually uses magi.
1288 ///
1289 /// An operator gets the same escape hatch for free: a second machine
1290 /// config, or none, without moving files about.
1291 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1292
1293 /// Every config layer that applies to `repo`, in increasing precedence.
1294 ///
1295 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1296 /// which is nothing at all in a test build.
1297 pub fn layers(repo: &Path) -> Vec<PathBuf> {
1298 let mut paths = Vec::new();
1299 paths.extend(Self::machine_layer());
1300 paths.push(repo.join(".magi").join("config.toml"));
1301 paths.push(repo.join("magi.toml"));
1302 paths.retain(|p| p.is_file());
1303 paths
1304 }
1305
1306 /// The machine-wide layer's path, when there is one.
1307 ///
1308 /// **A test build has none unless it names one.** A fixture is a complete
1309 /// statement of the config under test, and the operator's own preferences
1310 /// have no business being merged into it - least of all silently, on one
1311 /// machine, in a suite that is green everywhere else.
1312 #[cfg(test)]
1313 fn machine_layer() -> Option<PathBuf> {
1314 std::env::var(Self::CONFIG_DIR_ENV)
1315 .ok()
1316 .filter(|dir| !dir.trim().is_empty())
1317 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1318 }
1319
1320 /// The machine-wide layer's path, when there is one.
1321 #[cfg(not(test))]
1322 fn machine_layer() -> Option<PathBuf> {
1323 match std::env::var(Self::CONFIG_DIR_ENV) {
1324 // Named, and empty on purpose: no machine layer.
1325 Ok(dir) if dir.trim().is_empty() => None,
1326 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1327 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1328 }
1329 }
1330
1331 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1332 pub fn autodetected() -> Self {
1333 let mut cfg = Self::default();
1334 for (kind, id, model) in [
1335 (AgentKind::Claude, "opus", Some("opus")),
1336 (AgentKind::Claude, "sonnet", Some("sonnet")),
1337 (AgentKind::Antigravity, "antigravity", None),
1338 (AgentKind::Opencode, "opencode", None),
1339 (AgentKind::Codex, "codex", None),
1340 (AgentKind::Omp, "omp", None),
1341 ] {
1342 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1343 cfg.agents.push(AgentSpec {
1344 id: id.to_owned(),
1345 kind,
1346 model: model.map(str::to_owned),
1347 command: Vec::new(),
1348 extra_args: Vec::new(),
1349 env: BTreeMap::new(),
1350 prompt_delivery: None,
1351 });
1352 }
1353 }
1354 cfg
1355 }
1356
1357 /// The shared build cache the verify commands and the agents both build
1358 /// into, when the config declares one. See [`Verify::cache_dir`].
1359 pub fn cache_dir(&self) -> Option<PathBuf> {
1360 self.verify.cache_dir()
1361 }
1362
1363 /// Look an agent up by id.
1364 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1365 self.agents
1366 .iter()
1367 .find(|a| a.id == id)
1368 .with_context(|| format!("no agent with id `{id}` in the roster"))
1369 }
1370
1371 /// Rotate `count` seats out of `ids`, or out of the whole roster at
1372 /// `offset` when `ids` is empty.
1373 ///
1374 /// The one rotation rule - explicit ids cycle, an empty list rotates the
1375 /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
1376 /// rather than each seat reimplementing it and drifting apart.
1377 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1378 let mut out = Vec::with_capacity(count);
1379 for i in 0..count {
1380 let spec = if ids.is_empty() {
1381 self.agents[(i + offset) % self.agents.len()].clone()
1382 } else {
1383 self.agent(&ids[i % ids.len()])?.clone()
1384 };
1385 out.push(spec);
1386 }
1387 Ok(out)
1388 }
1389
1390 /// `ids`, resolved to specs in the order named, or the whole `[[agents]]`
1391 /// roster in file order when `ids` is empty — the same "explicit ids
1392 /// stand alone, an empty list means the whole roster" rule [`Self::rotate`]
1393 /// applies, but with no `count` to truncate to and no `offset` to wrap by.
1394 /// See [`ResolvedRoles::implementer_roster`] for why a truncated, rotated
1395 /// list cannot answer the question this exists for.
1396 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
1397 if ids.is_empty() {
1398 Ok(self.agents.clone())
1399 } else {
1400 ids.iter().map(|id| self.agent(id).cloned()).collect()
1401 }
1402 }
1403
1404 /// Fill the roles out to the configured widths.
1405 ///
1406 /// An empty role list rotates through the whole roster, so a three-agent
1407 /// roster with `candidates = 3` gives one implementation per agent, and
1408 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1409 /// author of candidate *i* whenever the roster has more than one agent.
1410 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1411 if self.agents.is_empty() {
1412 bail!(
1413 "agent roster is empty: no agent CLI found on PATH and no \
1414 [[agents]] in the config. Run `magi init` to write a starter \
1415 magi.toml."
1416 );
1417 }
1418 Ok(ResolvedRoles {
1419 implementers: self.rotate(&self.roles.implementers, self.graph.candidates, 0)?,
1420 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1421 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1422 fixer: self
1423 .roles
1424 .fixer
1425 .as_deref()
1426 .map(|f| self.agent(f).cloned())
1427 .transpose()?,
1428 // Role resolution validates roster shape, but deliberately does
1429 // not preflight a CLI. The other graph seats have always deferred
1430 // that failure to invocation; doing it only for the conductor
1431 // made otherwise usable graph commands and `doctor` fail as one.
1432 conductor: match self.roles.conductor.as_deref() {
1433 Some(id) => self.agent(id)?.clone(),
1434 // Keep the normal standalone-seat preference when something
1435 // is installed, but retain a roster fallback when it is not.
1436 // Invocation then reports the unavailable CLI in the same
1437 // place it does for every other graph role.
1438 None => crate::agent::pick(&self.agents, None, &crate::agent::installed)
1439 .unwrap_or_else(|_| self.agents[0].clone()),
1440 },
1441 implementer_roster: self.full_roster(&self.roles.implementers)?,
1442 })
1443 }
1444
1445 /// Advisor seats for the design-deliberation stage (see
1446 /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
1447 /// judge roster - see [`Roles::advisors`] for why that fallback and not
1448 /// the whole roster.
1449 ///
1450 /// The fallback rotates with `offset = 1`, matching the judges line in
1451 /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
1452 /// `roles.judges`, which is empty whenever judges themselves are
1453 /// unconfigured and rotating the whole roster. Falling back with
1454 /// `offset = 0` there would silently hand the advisors a *different*
1455 /// agent set than the judges an unconfigured run would actually get,
1456 /// which is the one thing [`Roles::advisors`]'s doc promises will not
1457 /// happen.
1458 ///
1459 /// Called lazily from the graph node itself rather than folded into
1460 /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
1461 /// not stop a run from starting at all - the deliberation stage is an
1462 /// enrichment `[graph] advise` can turn off, not a seat later nodes
1463 /// cannot proceed without - and at the point `resolve_roles` runs (before
1464 /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
1465 /// run yet for a resolution failure to be reported against.
1466 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
1467 if self.agents.is_empty() {
1468 bail!(
1469 "agent roster is empty: no agent CLI found on PATH and no \
1470 [[agents]] in the config. Run `magi init` to write a starter \
1471 magi.toml."
1472 );
1473 }
1474 if !self.roles.advisors.is_empty() {
1475 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
1476 }
1477 self.rotate(&self.roles.judges, self.graph.advisors, 1)
1478 }
1479
1480 /// Shell prefix for [`Verify`] commands.
1481 pub fn shell(&self) -> Vec<String> {
1482 if let Some(s) = &self.verify.shell {
1483 return s.clone();
1484 }
1485 if which("sh") {
1486 vec!["sh".to_owned(), "-c".to_owned()]
1487 } else {
1488 vec!["cmd".to_owned(), "/C".to_owned()]
1489 }
1490 }
1491
1492 /// Starter config, as written by `magi init`.
1493 pub fn starter_toml() -> String {
1494 let detected = Self::autodetected();
1495 let mut s = String::from(
1496 "# magi — blind multi-agent implementation competition.\n\
1497 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
1498 # -> blind judging -> deliberation -> private final vote\n\
1499 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
1500 #\n\
1501 # Rendered by teravars: a `[vars]` table, env\n\
1502 # and system lookups, and `include = [...]` all work. Tera\n\
1503 # braces are live everywhere in this file, but comments are\n\
1504 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
1505 # may quote `{{ ... }}` freely.\n\
1506 #\n\
1507 # Layers deep-merge in increasing\n\
1508 # precedence, so the roster can live once per machine in\n\
1509 # <config_dir>/magi/config.toml and each repo only states its own\n\
1510 # gate:\n\
1511 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
1512 [vars]\n\
1513 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
1514 # Single quotes inside the braces: teravars renders the raw file\n\
1515 # text, so TOML's own \\\" escaping never reaches Tera.\n\
1516 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
1517 );
1518 if detected.agents.is_empty() {
1519 s.push_str(
1520 "# No agent CLI was found on PATH. Fill this in by hand.\n\
1521 # kind = claude | opencode | antigravity | codex | command\n\
1522 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
1523 );
1524 } else {
1525 for a in &detected.agents {
1526 s.push_str("[[agents]]\n");
1527 s.push_str(&format!("id = {:?}\n", a.id));
1528 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
1529 if let Some(m) = &a.model {
1530 s.push_str(&format!("model = {m:?}\n"));
1531 }
1532 s.push('\n');
1533 }
1534 }
1535 s.push_str(
1536 "# Leave a role list empty to rotate through the roster.\n\
1537 [roles]\n\
1538 implementers = []\n\
1539 judges = []\n\
1540 reviewers = []\n\
1541 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
1542 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\n\
1543 [graph]\n\
1544 candidates = 3\n\
1545 judges = 3\n\
1546 deliberate_rounds = 1\n\
1547 reviewers = 3\n\
1548 review_rounds = 6\n\
1549 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
1550 gate_fix_rounds = 1\n\
1551 max_parallel = 4\n\
1552 language = \"en\"\n\
1553 # One CLI conversation per seat: judges keep their own argument\n\
1554 # across deliberation, the fixer keeps its implementation context.\n\
1555 sessions = true\n\
1556 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
1557 # the final gate inherit this value for compatibility.\n\
1558 timeout_review = 1200\n\
1559 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
1560 # verification independent if timeout_review changes later.\n\
1561 # timeout_verify = 1200\n\n\
1562 [verify]\n\
1563 # Run once per review round in the winner's worktree; failures are\n\
1564 # fed back to the fixer.\n\
1565 e2e = []\n\
1566 # Final gate. Every command must exit 0 before a merge.\n\
1567 gate = []\n\
1568 # Mechanical fixers (formatters) run in the winner's worktree just\n\
1569 # before the gate; whatever they change becomes one commit. A failing\n\
1570 # command only warns - the gate stays the arbiter. Same timeout as the\n\
1571 # gate (timeout_verify). Keep it light and idempotent.\n\
1572 # pre_gate = []\n\n\
1573 [merge]\n\
1574 # none | local | pr\n\
1575 mode = \"none\"\n\n\
1576 [update]\n\
1577 # off | notify | install — checked in the background, throttled.\n\
1578 mode = \"notify\"\n\
1579 # interval = \"24h\"\n",
1580 );
1581 s
1582 }
1583}
1584
1585/// Is `program` on `PATH`?
1586pub fn which(program: &str) -> bool {
1587 find_program(program).is_some()
1588}
1589
1590/// The file a bare `program` name resolves to on `PATH`, the way the OS shell
1591/// would find it.
1592///
1593/// Spawn agents through this, not by bare name: on Windows Rust's std
1594/// only tries `name.exe`, so a CLI installed as an npm `.cmd` shim (codex
1595/// since its 2026-09-23 reinstall) is "not found" even though a shell runs it.
1596/// On Windows an extensionless file is never a match: npm writes an `sh`
1597/// script beside every `.cmd` shim, and spawning that fails with os error 193.
1598pub fn find_program(program: &str) -> Option<PathBuf> {
1599 find_program_on(program, &std::env::var_os("PATH")?)
1600}
1601
1602/// [`find_program`] against an explicit `PATH`, for a child whose environment
1603/// overrides it.
1604pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
1605 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
1606 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
1607}
1608
1609fn find_program_in(
1610 program: &str,
1611 paths: &std::ffi::OsStr,
1612 pathext: Option<&str>,
1613) -> Option<PathBuf> {
1614 let p = Path::new(program);
1615 if p.components().count() > 1 {
1616 return p.is_file().then(|| p.to_path_buf());
1617 }
1618 std::env::split_paths(paths).find_map(|dir| match pathext {
1619 Some(exts) => {
1620 let bare = dir.join(program);
1621 if p.extension().is_some() && bare.is_file() {
1622 return Some(bare);
1623 }
1624 exts.split(';')
1625 .filter(|e| !e.is_empty())
1626 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
1627 .find(|c| c.is_file())
1628 }
1629 None => Some(dir.join(program)).filter(|c| c.is_file()),
1630 })
1631}
1632
1633#[cfg(test)]
1634mod tests {
1635 use super::*;
1636
1637 /// npm writes an extensionless `sh` script beside `codex.cmd`; on Windows
1638 /// the `.cmd` is the spawnable one (os error 193 otherwise, 2026-09-23).
1639 #[test]
1640 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
1641 let dir = tempfile::tempdir().unwrap();
1642 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
1643 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
1644 let paths = dir.path().as_os_str();
1645 assert_eq!(
1646 find_program_in("codex", paths, Some(".EXE;.CMD")),
1647 Some(dir.path().join("codex.cmd"))
1648 );
1649 assert_eq!(
1650 find_program_in("codex", paths, None),
1651 Some(dir.path().join("codex"))
1652 );
1653 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
1654 }
1655
1656 fn spec(id: &str) -> AgentSpec {
1657 AgentSpec {
1658 id: id.to_owned(),
1659 kind: AgentKind::Command,
1660 model: None,
1661 command: vec!["true".to_owned()],
1662 extra_args: Vec::new(),
1663 env: BTreeMap::new(),
1664 prompt_delivery: None,
1665 }
1666 }
1667
1668 #[test]
1669 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
1670 // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
1671 // under `timeout_review`. A config written before this field existed
1672 // must run exactly as before, which means its default has to be the
1673 // same 1200s `timeout_review` has always defaulted to.
1674 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
1675 assert_eq!(g.timeout_verify, None);
1676 assert_eq!(g.verify_timeout(), 3600);
1677 }
1678
1679 #[test]
1680 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
1681 // The bug this field exists to close: `[graph] timeout_review = 45`
1682 // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
1683 // along with the reviewer seats' own timeout, because both read the
1684 // same field.
1685 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
1686 assert_eq!(g.timeout_review, 45);
1687 assert_eq!(
1688 g.verify_timeout(),
1689 45,
1690 "an omitted legacy value follows review"
1691 );
1692 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
1693 .expect("parse explicit override");
1694 assert_eq!(explicit.verify_timeout(), 1200);
1695 }
1696
1697 #[test]
1698 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
1699 // `deny_unknown_fields` cuts both ways: a config from before
1700 // `timeout_verify`/`e2e_every_round` existed must still parse, with
1701 // both defaulted rather than refused as unknown-in-reverse.
1702 let g: Graph =
1703 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
1704 .expect("an old-shaped [graph] table must still parse");
1705 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
1706 assert!(
1707 !g.e2e_every_round,
1708 "off by default, same as before this field existed"
1709 );
1710 }
1711
1712 #[test]
1713 fn empty_roles_rotate_judges_off_their_own_candidate() {
1714 // Three seats, said out loud: this is a test about *rotation*, and it
1715 // has nothing to say about how many candidates a task buys by default.
1716 let cfg = Config {
1717 agents: vec![spec("a"), spec("b"), spec("c")],
1718 graph: Graph {
1719 candidates: 3,
1720 ..Graph::default()
1721 },
1722 ..Config::default()
1723 };
1724 let roles = cfg.resolve_roles().unwrap();
1725 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
1726 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
1727 assert_eq!(impls, ["a", "b", "c"]);
1728 assert_eq!(judges, ["b", "c", "a"]);
1729 for (i, j) in judges.iter().enumerate() {
1730 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
1731 }
1732 }
1733
1734 #[test]
1735 fn single_agent_roster_fills_every_seat() {
1736 let cfg = Config {
1737 agents: vec![spec("solo")],
1738 graph: Graph {
1739 candidates: 3,
1740 ..Graph::default()
1741 },
1742 ..Config::default()
1743 };
1744 let roles = cfg.resolve_roles().unwrap();
1745 assert_eq!(roles.implementers.len(), 3);
1746 assert!(roles.judges.iter().all(|a| a.id == "solo"));
1747 }
1748
1749 #[test]
1750 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
1751 // `candidates = 1` (a solo run) still resolves `implementers` down to
1752 // one slot, but `implementer_roster` must carry every agent in the
1753 // roster, in file order, for `graph::Runner`'s quota fallback to walk
1754 // forward through once that one slot's agent runs out of quota.
1755 let cfg = Config {
1756 agents: vec![spec("a"), spec("b"), spec("c")],
1757 graph: Graph {
1758 candidates: 1,
1759 ..Graph::default()
1760 },
1761 ..Config::default()
1762 };
1763 let roles = cfg.resolve_roles().unwrap();
1764 assert_eq!(roles.implementers.len(), 1);
1765 let roster: Vec<&str> = roles
1766 .implementer_roster
1767 .iter()
1768 .map(|a| a.id.as_str())
1769 .collect();
1770 assert_eq!(roster, ["a", "b", "c"]);
1771 }
1772
1773 #[test]
1774 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
1775 let cfg = Config {
1776 agents: vec![spec("a"), spec("b"), spec("c")],
1777 roles: Roles {
1778 implementers: vec!["c".to_owned(), "a".to_owned()],
1779 ..Roles::default()
1780 },
1781 graph: Graph {
1782 candidates: 1,
1783 ..Graph::default()
1784 },
1785 ..Config::default()
1786 };
1787 let roles = cfg.resolve_roles().unwrap();
1788 // Unaffected by the new field: still just the first named id.
1789 assert_eq!(roles.implementers.len(), 1);
1790 assert_eq!(roles.implementers[0].id, "c");
1791 let roster: Vec<&str> = roles
1792 .implementer_roster
1793 .iter()
1794 .map(|a| a.id.as_str())
1795 .collect();
1796 assert_eq!(roster, ["c", "a"]);
1797 }
1798
1799 #[test]
1800 fn explicit_roles_win() {
1801 let cfg = Config {
1802 agents: vec![spec("a"), spec("b")],
1803 roles: Roles {
1804 implementers: vec!["b".to_owned()],
1805 judges: vec!["a".to_owned()],
1806 reviewers: Vec::new(),
1807 fixer: Some("a".to_owned()),
1808 ..Roles::default()
1809 },
1810 ..Config::default()
1811 };
1812 let roles = cfg.resolve_roles().unwrap();
1813 assert!(roles.implementers.iter().all(|a| a.id == "b"));
1814 assert!(roles.judges.iter().all(|a| a.id == "a"));
1815 assert_eq!(roles.fixer.unwrap().id, "a");
1816 assert_eq!(roles.conductor.id, "a");
1817 }
1818
1819 #[test]
1820 fn unknown_agent_id_is_an_error() {
1821 let cfg = Config {
1822 agents: vec![spec("a")],
1823 roles: Roles {
1824 judges: vec!["nope".to_owned()],
1825 ..Roles::default()
1826 },
1827 ..Config::default()
1828 };
1829 assert!(cfg.resolve_roles().is_err());
1830 }
1831
1832 #[test]
1833 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
1834 let mut cfg = Config {
1835 agents: vec![spec("a"), spec("b")],
1836 ..Config::default()
1837 };
1838 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
1839
1840 cfg.roles.conductor = Some("b".to_owned());
1841 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
1842
1843 cfg.roles.conductor = Some("missing".to_owned());
1844 assert!(cfg.resolve_roles().is_err());
1845 }
1846
1847 #[test]
1848 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
1849 // Unlike `conductor`, `synthesizer` is never validated by
1850 // `resolve_roles` — it is looked up lazily by
1851 // `graph::Runner::synthesize_brief` the same way `[roles] chatter`
1852 // is looked up by `talk::begin`, so this exercises `agent::pick`
1853 // directly instead of going through `resolve_roles`.
1854 let mut cfg = Config {
1855 agents: vec![spec("a"), spec("b")],
1856 ..Config::default()
1857 };
1858 let want = cfg.roles.synthesizer.as_deref();
1859 assert_eq!(
1860 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
1861 .unwrap()
1862 .id,
1863 "a",
1864 "unset falls back to agent::pick's own default order"
1865 );
1866
1867 cfg.roles.synthesizer = Some("b".to_owned());
1868 let want = cfg.roles.synthesizer.as_deref();
1869 assert_eq!(
1870 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
1871 .unwrap()
1872 .id,
1873 "b",
1874 "the named agent wins over the default order"
1875 );
1876 }
1877
1878 #[test]
1879 fn empty_roster_is_an_error() {
1880 assert!(Config::default().resolve_roles().is_err());
1881 }
1882
1883 #[test]
1884 fn advise_defaults_to_on_with_three_proposals() {
1885 let g = Graph::default();
1886 assert!(g.advise);
1887 assert_eq!(g.advisors, 3);
1888 }
1889
1890 #[test]
1891 fn unset_advisors_falls_back_to_the_judge_roster() {
1892 let cfg = Config {
1893 agents: vec![spec("a"), spec("b")],
1894 roles: Roles {
1895 judges: vec!["b".to_owned()],
1896 ..Roles::default()
1897 },
1898 graph: Graph {
1899 advisors: 2,
1900 ..Graph::default()
1901 },
1902 ..Config::default()
1903 };
1904 let advisors = cfg.advisors().expect("advisors resolve");
1905 assert_eq!(advisors.len(), 2);
1906 assert!(
1907 advisors.iter().all(|a| a.id == "b"),
1908 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
1909 );
1910 }
1911
1912 #[test]
1913 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
1914 let cfg = Config {
1915 agents: vec![spec("a"), spec("b")],
1916 roles: Roles {
1917 judges: vec!["b".to_owned()],
1918 advisors: vec!["a".to_owned()],
1919 ..Roles::default()
1920 },
1921 graph: Graph {
1922 advisors: 2,
1923 ..Graph::default()
1924 },
1925 ..Config::default()
1926 };
1927 let advisors = cfg.advisors().expect("advisors resolve");
1928 assert!(advisors.iter().all(|a| a.id == "a"));
1929 }
1930
1931 /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
1932 /// advisor roster must resolve to the exact same agents an unconfigured
1933 /// judge panel would get - same ids, same rotation offset - or the
1934 /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
1935 /// does not actually hold.
1936 #[test]
1937 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
1938 let cfg = Config {
1939 agents: vec![spec("a"), spec("b"), spec("c")],
1940 graph: Graph {
1941 advisors: 3,
1942 judges: 3,
1943 ..Graph::default()
1944 },
1945 ..Config::default()
1946 };
1947 let advisors = cfg.advisors().expect("advisors resolve");
1948 let judges = cfg.resolve_roles().expect("roles resolve").judges;
1949 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
1950 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
1951 assert_eq!(
1952 advisor_ids, judge_ids,
1953 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
1954 );
1955 }
1956
1957 #[test]
1958 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
1959 let cfg = Config {
1960 agents: vec![spec("a")],
1961 roles: Roles {
1962 advisors: vec!["nope".to_owned()],
1963 ..Roles::default()
1964 },
1965 graph: Graph {
1966 advisors: 1,
1967 ..Graph::default()
1968 },
1969 ..Config::default()
1970 };
1971 let err = cfg.advisors().expect_err("`nope` is not in the roster");
1972 assert!(format!("{err:#}").contains("nope"));
1973 }
1974
1975 #[test]
1976 fn repos_default_to_no_roots_and_a_day_of_trust() {
1977 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
1978 assert_eq!(Config::default().repos.scan_ttl, 86_400);
1979 }
1980
1981 #[test]
1982 fn a_config_file_with_no_repos_table_still_loads() {
1983 let dir = tempfile::tempdir().unwrap();
1984 let path = dir.path().join("magi.toml");
1985 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
1986 let cfg = Config::load(&path).expect("must load without [repos]");
1987 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
1988 assert_eq!(cfg.repos.scan_ttl, 86_400);
1989 }
1990
1991 /// A fixture is the whole config under test.
1992 ///
1993 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
1994 /// a machine where somebody had written `<config_dir>/magi/config.toml`
1995 /// the suite silently loaded it as the lowest layer. Adding `[repos]
1996 /// roots` there turned two web tests red - their fixtures declare
1997 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
1998 /// array key spread across two layers. CI stayed green throughout,
1999 /// because a runner has no such file: the suite failed only where magi is
2000 /// actually used.
2001 ///
2002 /// So a test build has no machine layer unless it asks for one, and this
2003 /// is that promise. Written against a real file at the real location so
2004 /// it fails if `machine_layer` starts reading it again.
2005 #[test]
2006 fn a_test_build_does_not_read_the_operators_machine_config() {
2007 let repo = tempfile::tempdir().unwrap();
2008 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
2009
2010 let layers = Config::layers(repo.path());
2011 assert_eq!(
2012 layers,
2013 vec![repo.path().join("magi.toml")],
2014 "only the fixture's own file may be a layer"
2015 );
2016 if let Some(real) = dirs::config_dir() {
2017 let machine = real.join("magi").join("config.toml");
2018 assert!(
2019 !layers.contains(&machine),
2020 "the operator's {} must not be a layer in a test build",
2021 machine.display()
2022 );
2023 }
2024 }
2025
2026 #[test]
2027 fn starter_toml_loads_through_teravars() {
2028 let dir = tempfile::tempdir().unwrap();
2029 let path = dir.path().join("magi.toml");
2030 std::fs::write(&path, Config::starter_toml()).unwrap();
2031 let parsed = Config::load(&path).expect("starter config must load");
2032 assert_eq!(parsed.graph.candidates, 3);
2033 assert_eq!(parsed.merge.mode, MergeMode::None);
2034 assert_eq!(parsed.merge.style, MergeStyle::Merge);
2035 assert!(parsed.graph.sessions);
2036 assert_eq!(parsed.graph.timeout_review, 1200);
2037 assert_eq!(parsed.graph.verify_timeout(), 1200);
2038 assert_eq!(parsed.update.mode, UpdateMode::Notify);
2039 }
2040
2041 #[test]
2042 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
2043 let dir = tempfile::tempdir().unwrap();
2044 let path = dir.path().join("magi.toml");
2045 std::fs::write(&path, Config::starter_toml()).unwrap();
2046 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
2047 assert!(Config::starter_toml().contains("# pre_gate = []"));
2048 }
2049
2050 #[test]
2051 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
2052 let starter = Config::starter_toml();
2053 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
2054 assert!(starter.contains("verification independent if timeout_review changes later"));
2055 assert!(starter.contains("# timeout_verify = 1200"));
2056 }
2057
2058 /// A repository whose ruleset forbids merge commits declares that once,
2059 /// here, rather than magi asking GitHub about it on every render (see
2060 /// [`MergeStyle`]'s own doc for why).
2061 #[test]
2062 fn a_repository_can_declare_a_linear_history_merge_style() {
2063 let dir = tempfile::tempdir().unwrap();
2064 let path = dir.path().join("magi.toml");
2065 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
2066 let parsed = Config::load(&path).expect("config must load");
2067 assert_eq!(parsed.merge.style, MergeStyle::Squash);
2068 }
2069
2070 #[test]
2071 fn later_layers_win_and_vars_render() {
2072 let dir = tempfile::tempdir().unwrap();
2073 let machine = dir.path().join("machine.toml");
2074 let project = dir.path().join("magi.toml");
2075 // The machine layer owns the roster...
2076 std::fs::write(
2077 &machine,
2078 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
2079 [graph]\ncandidates = 3\nmax_parallel = 8\n",
2080 )
2081 .unwrap();
2082 // ...and the project layer only states what is repo-specific, plus a
2083 // `[vars]` value interpolated into a command.
2084 std::fs::write(
2085 &project,
2086 "[vars]\ncache = \"/shared\"\n\n\
2087 [graph]\ncandidates = 2\n\n\
2088 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
2089 )
2090 .unwrap();
2091
2092 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
2093 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
2094 assert_eq!(cfg.graph.candidates, 2, "project layer wins");
2095 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
2096 assert_eq!(
2097 cfg.verify.gate,
2098 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
2099 );
2100 // The rendered command is where the cache path is read back from.
2101 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
2102 }
2103
2104 #[test]
2105 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
2106 // An operator who writes no `[graph]` timeout keys at all must still
2107 // land on the hour, not on the five/fifteen minutes this turn used
2108 // to hardcode before it read from config.
2109 let g = Graph::default();
2110 assert_eq!(g.timeout_talk, 3600);
2111
2112 let dir = tempfile::tempdir().unwrap();
2113 let path = dir.path().join("magi.toml");
2114 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
2115 let cfg = Config::load(&path).expect("must load without timeout_talk set");
2116 assert_eq!(cfg.graph.timeout_talk, 3600);
2117 }
2118
2119 #[test]
2120 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
2121 let dir = tempfile::tempdir().unwrap();
2122 let path = dir.path().join("magi.toml");
2123 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
2124 let cfg = Config::load(&path).expect("must load");
2125 assert_eq!(cfg.graph.timeout_talk, 120);
2126 }
2127
2128 #[test]
2129 fn the_disk_defaults_are_the_measurements_made_up_front() {
2130 let cfg = Config::default();
2131 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
2132 assert!(cfg.disk.auto_fold);
2133 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
2134 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
2135 }
2136
2137 #[test]
2138 fn an_unset_disk_section_is_the_safe_default() {
2139 let dir = tempfile::tempdir().unwrap();
2140 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
2141 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
2142 assert_eq!(cfg.disk, Disk::default());
2143 }
2144
2145 #[test]
2146 fn env_is_available_to_templates_with_a_default() {
2147 let dir = tempfile::tempdir().unwrap();
2148 let path = dir.path().join("magi.toml");
2149 // teravars ships no `env`; magi adds it, and the `default` filter has
2150 // to cover the unset case or every machine would need the variable.
2151 //
2152 // Deliberately no named variable: `env` is keyed by the exact spelling
2153 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
2154 // test asserting `env.PATH` passes on one runner and fails on another.
2155 // The map's non-emptiness is the platform-neutral claim.
2156 std::fs::write(
2157 &path,
2158 "[verify]\n\
2159 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
2160 \"populated={{ env | length > 0 }}\"]\n",
2161 )
2162 .unwrap();
2163 let cfg = Config::load(&path).expect("env lookup must render");
2164 assert_eq!(cfg.verify.gate[0], "cache=fallback");
2165 assert_eq!(cfg.verify.gate[1], "populated=true");
2166 }
2167
2168 #[test]
2169 fn a_broken_template_names_the_file() {
2170 let dir = tempfile::tempdir().unwrap();
2171 let path = dir.path().join("magi.toml");
2172 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
2173 let err = Config::load(&path).expect_err("must not silently ignore");
2174 assert!(err.to_string().contains("teravars"), "{err}");
2175 }
2176
2177 #[test]
2178 fn tera_syntax_in_comments_is_inert() {
2179 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
2180 // comment may quote template syntax without rendering. Before 0.2.2 this
2181 // load failed: the commented-out braces reached the template parser.
2182 let dir = tempfile::tempdir().unwrap();
2183 let path = dir.path().join("magi.toml");
2184 std::fs::write(
2185 &path,
2186 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
2187 [graph]\ncandidates = 2\n",
2188 )
2189 .unwrap();
2190 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
2191 assert_eq!(cfg.graph.candidates, 2);
2192 }
2193
2194 #[test]
2195 fn opencode_defaults_to_file_delivery() {
2196 let mut s = spec("oc");
2197 s.kind = AgentKind::Opencode;
2198 assert_eq!(s.delivery(), Delivery::File);
2199 s.prompt_delivery = Some(Delivery::Argv);
2200 assert_eq!(s.delivery(), Delivery::Argv);
2201 }
2202 #[test]
2203 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
2204 // Both default on, and that pair is the safety property: `land` takes
2205 // over the watching an operator was doing by hand, `land_approval`
2206 // keeps the irreversible step a human decision. An unattended merge
2207 // needs BOTH flipped, which has to be chosen deliberately twice.
2208 let g = Graph::default();
2209 assert!(
2210 g.land,
2211 "stopping at an open PR left the watching to a human"
2212 );
2213 assert!(
2214 g.land_approval,
2215 "on-by-default land is only defensible while this is also on"
2216 );
2217 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
2218 }
2219 #[test]
2220 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
2221 // teravars appends arrays. For an ordered list of seats, or an argv,
2222 // the concatenation is something neither file says - and the operator
2223 // pays for the extra seats by the token.
2224 let dir = tempfile::tempdir().unwrap();
2225 let machine = dir.path().join("machine.toml");
2226 let repo = dir.path().join("magi.toml");
2227 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
2228 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
2229
2230 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2231 .expect_err("two layers naming one array must not merge silently")
2232 .to_string();
2233 assert!(err.contains("roles.implementers"), "{err}");
2234 // Both files are named: the fix is to delete one of them, and the
2235 // operator has to know which two to choose between.
2236 assert!(err.contains("machine.toml"), "{err}");
2237 assert!(err.contains("magi.toml"), "{err}");
2238 }
2239
2240 #[test]
2241 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
2242 // The split the layering exists for: state a preference machine-wide,
2243 // let the repository own its own lists.
2244 let dir = tempfile::tempdir().unwrap();
2245 let machine = dir.path().join("machine.toml");
2246 let repo = dir.path().join("magi.toml");
2247 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
2248 std::fs::write(
2249 &repo,
2250 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
2251 [roles]\nimplementers = [\"oc\"]\n",
2252 )
2253 .unwrap();
2254
2255 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
2256 assert_eq!(cfg.roles.chatter.as_deref(), Some("opus"));
2257 assert_eq!(cfg.roles.implementers, ["oc"]);
2258 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
2259 }
2260
2261 #[test]
2262 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
2263 // The `editorconfig-checker` distribution problem: a shared layer
2264 // wants to add a gate command without erasing the repository's own.
2265 let dir = tempfile::tempdir().unwrap();
2266 let machine = dir.path().join("machine.toml");
2267 let repo = dir.path().join("magi.toml");
2268 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2269 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2270
2271 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2272 assert_eq!(
2273 cfg.verify.gate,
2274 [
2275 "editorconfig-checker".to_owned(),
2276 "cargo make check".to_owned()
2277 ],
2278 "low-priority (machine) command first, high-priority (repo) command after"
2279 );
2280 }
2281
2282 #[test]
2283 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
2284 let dir = tempfile::tempdir().unwrap();
2285 let machine = dir.path().join("machine.toml");
2286 let repo = dir.path().join("magi.toml");
2287 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
2288 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
2289
2290 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2291 assert_eq!(
2292 cfg.verify.e2e,
2293 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
2294 );
2295 }
2296
2297 #[test]
2298 fn two_layers_declaring_repos_roots_are_both_scanned() {
2299 let dir = tempfile::tempdir().unwrap();
2300 let machine = dir.path().join("machine.toml");
2301 let repo = dir.path().join("magi.toml");
2302 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
2303 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
2304
2305 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2306 assert_eq!(
2307 cfg.repos.roots,
2308 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
2309 );
2310 }
2311
2312 #[test]
2313 fn duplicate_gate_commands_across_layers_both_run() {
2314 // Dropping the duplicate would be a silent surprise; the operator
2315 // sees a slower gate, never a missing one.
2316 let dir = tempfile::tempdir().unwrap();
2317 let machine = dir.path().join("machine.toml");
2318 let repo = dir.path().join("magi.toml");
2319 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2320 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2321
2322 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2323 assert_eq!(
2324 cfg.verify.gate,
2325 ["same-command".to_owned(), "same-command".to_owned()]
2326 );
2327 }
2328
2329 #[test]
2330 fn notify_command_is_still_refused_across_two_layers() {
2331 // An argv, not a set: concatenating two of them is not a program.
2332 let dir = tempfile::tempdir().unwrap();
2333 let machine = dir.path().join("machine.toml");
2334 let repo = dir.path().join("magi.toml");
2335 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
2336 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
2337
2338 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2339 .expect_err("an argv split across layers must not concatenate")
2340 .to_string();
2341 assert!(err.contains("notify.command"), "{err}");
2342 assert!(err.contains("machine.toml"), "{err}");
2343 assert!(err.contains("magi.toml"), "{err}");
2344 }
2345
2346 #[test]
2347 fn one_layer_declaring_verify_gate_runs_unchanged() {
2348 // The classification must not change behaviour for the configuration
2349 // this very repository has today: exactly one layer names the gate.
2350 let dir = tempfile::tempdir().unwrap();
2351 let path = dir.path().join("magi.toml");
2352 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2353
2354 let cfg = Config::load(&path).expect("single layer must still load");
2355 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
2356 }
2357
2358 #[test]
2359 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
2360 let dir = tempfile::tempdir().unwrap();
2361 let machine = dir.path().join("machine.toml");
2362 let repo = dir.path().join("magi.toml");
2363 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2364 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2365 let paths = vec![machine.clone(), repo.clone()];
2366
2367 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
2368 let described =
2369 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
2370 assert!(described.contains("editorconfig-checker && cargo make check"));
2371 assert!(
2372 described.contains(&machine.display().to_string()),
2373 "{described}"
2374 );
2375 assert!(
2376 described.contains(&repo.display().to_string()),
2377 "{described}"
2378 );
2379
2380 // A single contributing layer stays the plain one-line summary.
2381 let single = vec![repo.clone()];
2382 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
2383 let solo_described =
2384 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
2385 assert_eq!(solo_described, "cargo make check");
2386 }
2387}