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 /// Only acts on Rust repositories (a `Cargo.toml` at the root of the base
685 /// branch); on any other repository it is a no-op that records one event.
686 ///
687 /// On by default. **Turning this off means a merge landed from the phone
688 /// never becomes a release**, so `POST /api/upgrade` keeps reporting
689 /// "already on the newest release" against a `main` that has moved past
690 /// it - the same gap this feature exists to close. Only for a repository
691 /// that wants to keep cutting releases by hand.
692 pub release_bump: bool,
693}
694
695impl Default for Merge {
696 fn default() -> Self {
697 Self {
698 mode: MergeMode::None,
699 base: None,
700 style: MergeStyle::default(),
701 remote: "origin".to_owned(),
702 release_bump: true,
703 }
704 }
705}
706
707/// How magi keeps itself current.
708#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
709#[serde(rename_all = "lowercase")]
710pub enum UpdateMode {
711 /// Never check.
712 Off,
713 /// Check in the background and print a one-line banner when a newer
714 /// release exists.
715 Notify,
716 /// Check and install silently.
717 Install,
718}
719
720/// Self-update policy.
721#[derive(Debug, Clone, Deserialize, Serialize)]
722#[serde(deny_unknown_fields, default)]
723pub struct Update {
724 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
725 pub mode: UpdateMode,
726 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
727 pub interval: Option<String>,
728}
729
730impl Default for Update {
731 fn default() -> Self {
732 Self {
733 mode: UpdateMode::Notify,
734 interval: None,
735 }
736 }
737}
738
739/// Top-level configuration.
740#[derive(Debug, Clone, Default, Deserialize, Serialize)]
741#[serde(deny_unknown_fields, default)]
742pub struct Config {
743 /// Agent roster.
744 pub agents: Vec<AgentSpec>,
745 /// Role assignment.
746 pub roles: Roles,
747 /// Graph shape.
748 pub graph: Graph,
749 /// Blindness policy.
750 pub blind: Blind,
751 /// Verification commands.
752 pub verify: Verify,
753 /// Disk hygiene.
754 pub disk: Disk,
755 /// Merge policy.
756 pub merge: Merge,
757 /// Self-update policy.
758 pub update: Update,
759 /// Project-specific text appended to the node prompts.
760 pub prompts: Prompts,
761 /// How the operator is told a run is waiting on them.
762 pub notify: Notify,
763 /// Local repositories the plan surface can start or derive a conversation
764 /// against.
765 pub repos: Repos,
766 /// Policy for the standing conversation ([`crate::talk`]).
767 pub talk: Talk,
768 /// How many runs `magi serve`'s own loop drives at once.
769 pub daemon: Daemon,
770}
771
772/// How the daemon loop itself behaves, as opposed to what one run does.
773///
774/// Machine-layer material in the same sense [`Repos::roots`] is: how many
775/// competitions this machine's own loop is willing to babysit at once is a
776/// fact about the machine running `magi serve`, not about any one
777/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
778/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
779/// nothing stops a repository from setting it too, since a scalar field
780/// takes whichever layer has the highest precedence.
781#[derive(Debug, Clone, Deserialize, Serialize)]
782#[serde(deny_unknown_fields, default)]
783pub struct Daemon {
784 /// How many runs `magi serve` may have actively in flight at once.
785 /// **One by default** - today's behaviour, one run at a time.
786 ///
787 /// This is a different knob from [`Graph::max_parallel`], and the two
788 /// must not be confused: `max_parallel` bounds how many agent *processes*
789 /// one run starts inside itself (implementers, judges, reviewers -
790 /// candidates competing on a single task); this field bounds how many
791 /// *runs* - whole competitions, each with its own `max_parallel` budget -
792 /// the loop drives side by side, possibly across different tasks and
793 /// different repositories. Raising `max_parallel` buys a bigger panel for
794 /// one task; raising this buys more tasks worked at once. A config file
795 /// that meant one and wrote the other would either starve a competition
796 /// of judges or leave the rest of the backlog waiting for no reason.
797 ///
798 /// A run parked waiting on the operator's land-merge approval - see
799 /// [`crate::land`] - does not hold one of these slots while it waits: the
800 /// whole point of parking there is to let the loop spend the slot on
801 /// something runnable instead of sitting on a decision only a human can
802 /// make. So even at the default of `1`, an approval that comes back does
803 /// not queue behind whatever else the loop happens to be running.
804 pub max_concurrent_runs: usize,
805 /// Let a task marked [`crate::queue::Task::interrupt`] (`magi task
806 /// interrupt`) cut ahead of whatever `magi serve` already has in flight,
807 /// instead of waiting for it to finish.
808 ///
809 /// **Off by default.** When enabled, a run that is in flight and is not
810 /// itself the interrupt candidate may be paused at its next safe node
811 /// boundary - see [`crate::graph::Runner::park_here`] - so the marked
812 /// task can run alone; the paused run resumes automatically, through the
813 /// same path any other parked run does, the moment the interrupting
814 /// task's own run reaches a terminal status. This is opt-in because it
815 /// bends the loop's own "one run at a time" principle (see this repository's
816 /// `magi serve` help) for a specific, explicit operator request, and a
817 /// repository that never files an interrupt task pays nothing for having
818 /// it on - but an operator who does not want any run of theirs preempted,
819 /// ever, should leave this `false`.
820 pub pause_for_interrupts: bool,
821}
822
823impl Default for Daemon {
824 fn default() -> Self {
825 Self {
826 max_concurrent_runs: 1,
827 pause_for_interrupts: false,
828 }
829 }
830}
831
832/// Where `magi repos` and `GET /api/repos` look for local checkouts.
833///
834/// `roots` is one of the array keys [`array_merge_policy`] marks as
835/// append-across-layers: which checkouts exist in general is a *machine*
836/// fact in the same way the agent roster is - a repository's own `magi.toml`
837/// cannot state where its siblings live before magi has resolved which
838/// repository to read that file from in the first place - but a repository
839/// that genuinely has an extra root worth scanning is not forced to choose
840/// between an error and losing the machine's roots outright. Both layers'
841/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
842/// are still refused.
843#[derive(Debug, Clone, Deserialize, Serialize)]
844#[serde(deny_unknown_fields, default)]
845pub struct Repos {
846 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
847 /// with a `.git` directory. Empty by default - nothing is scanned unless
848 /// asked to be.
849 pub roots: Vec<PathBuf>,
850 /// How long a scan is trusted before the next request re-scans it,
851 /// seconds. `0` means never trust it: scan on every request. Defaults to
852 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
853 /// the same reason - a checkout does not usually appear or vanish inside
854 /// a session, so there is little to gain from scanning more often than
855 /// that, and an explicit refresh exists for the moment one does.
856 pub scan_ttl: u64,
857}
858
859impl Default for Repos {
860 fn default() -> Self {
861 Self {
862 roots: Vec::new(),
863 scan_ttl: 86_400,
864 }
865 }
866}
867
868/// Project-specific text appended to each node's prompt.
869///
870/// **Additive by construction.** These fields cannot replace magi's prompts,
871/// only extend them, and that restriction is the whole design. The built-in
872/// prompts carry the invariants the competition rests on: a judging prompt
873/// names no authors, every structured answer must arrive as one fenced `json`
874/// block, and a judge is told not to speculate about who wrote what. A config
875/// that could overwrite them would let a typo silently un-blind the panel or
876/// break the parser, and the symptom would be "the judges got worse" rather
877/// than an error.
878///
879/// Repository-wide context belongs in `AGENTS.md`, which every agent already
880/// reads from the checkout. Use these fields for the things a *magi node*
881/// needs to know and a repository file cannot say - for instance that
882/// reviewers here should ignore formatting because a hook owns it.
883#[derive(Debug, Clone, Default, Deserialize, Serialize)]
884#[serde(deny_unknown_fields, default)]
885pub struct Prompts {
886 /// Appended to every node's prompt.
887 pub all: String,
888 /// Appended for implementers.
889 pub implement: String,
890 /// Appended for judges, both ranking and voting.
891 pub judge: String,
892 /// Appended for reviewers.
893 pub review: String,
894 /// Appended for the fixer.
895 pub fix: String,
896}
897
898impl Prompts {
899 /// The overlay for one node, or `None` when nothing is configured.
900 ///
901 /// `node` is the graph's own node name, so a new node gets no overlay
902 /// rather than the wrong one.
903 pub fn overlay(&self, node: &str) -> Option<String> {
904 let specific = match node {
905 "implement" => &self.implement,
906 "judge" | "vote" | "deliberate" => &self.judge,
907 "review" => &self.review,
908 "fix" => &self.fix,
909 _ => "",
910 };
911 let mut parts: Vec<&str> = Vec::new();
912 for p in [self.all.trim(), specific.trim()] {
913 if !p.is_empty() {
914 parts.push(p);
915 }
916 }
917 if parts.is_empty() {
918 return None;
919 }
920 Some(parts.join("\n\n"))
921 }
922}
923
924/// How the operator is told that a run is waiting on them.
925///
926/// A command rather than a built-in integration: magi is one binary with no
927/// network dependencies, and every operator's notification path is different -
928/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
929/// Shelling out keeps all of them possible and none of them magi's problem.
930#[derive(Debug, Clone, Default, Deserialize, Serialize)]
931#[serde(deny_unknown_fields, default)]
932pub struct Notify {
933 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
934 /// Empty means no notification - the web UI is then the only surface.
935 pub command: Vec<String>,
936}
937
938/// Policy for [`crate::talk`], the standing conversation.
939#[derive(Debug, Clone, Default, Deserialize, Serialize)]
940#[serde(deny_unknown_fields, default)]
941pub struct Talk {
942 /// Let the conversation's agent edit files in the repository instead of
943 /// filing a task for one. **Off by default** - see
944 /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
945 /// an edit no run and no review can be attributed to, which is exactly
946 /// the property a repository entered in a competition depends on. A
947 /// repository that is never judged - dotfiles, a personal config
948 /// checkout - has nothing to lose by turning this on in its own
949 /// `magi.toml`, and a one-line fix stops costing a queued task to get.
950 pub allow_write: bool,
951}
952
953/// Roles resolved to concrete agent specs for one run.
954#[derive(Debug, Clone)]
955pub struct ResolvedRoles {
956 /// One per candidate.
957 pub implementers: Vec<AgentSpec>,
958 /// One per judge.
959 pub judges: Vec<AgentSpec>,
960 /// One per reviewer slot.
961 pub reviewers: Vec<AgentSpec>,
962 /// Explicit fixer, if configured.
963 pub fixer: Option<AgentSpec>,
964 /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
965 pub conductor: AgentSpec,
966 /// The full ordered implementer roster, in [`Roles::implementers`]'s own
967 /// order — or `[[agents]]` in file order, when that list is empty. Unlike
968 /// [`Self::implementers`], never truncated to `graph.candidates` and
969 /// never `rotate`d/wrapped: a solo run (`candidates = 1`) resolves
970 /// `implementers` down to a single slot, but `graph::Runner`'s per-seat
971 /// quota fallback needs the *whole* list to walk forward through when
972 /// that one slot's agent runs out of quota mid-run.
973 pub implementer_roster: Vec<AgentSpec>,
974}
975
976/// Every array-valued key in a config table, as a dotted path.
977///
978/// Dotted so the error names `roles.implementers` rather than `implementers`:
979/// an operator with three config files needs to know which key, not just that
980/// there was one. `vars` is skipped because it is teravars' own input, merged
981/// on purpose and never deserialised into `Config`.
982fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
983 let mut out = Vec::new();
984 for (k, v) in table {
985 if prefix.is_empty() && k == "vars" {
986 continue;
987 }
988 let path = if prefix.is_empty() {
989 k.clone()
990 } else {
991 format!("{prefix}.{k}")
992 };
993 match v {
994 toml::Value::Array(_) => out.push(path),
995 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
996 _ => {}
997 }
998 }
999 out
1000}
1001
1002/// How an array key behaves when two config layers both declare it.
1003#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1004enum ArrayMerge {
1005 /// Two layers may both declare it; the composed value is the
1006 /// low-to-high-priority concatenation teravars already produces (see
1007 /// [`Config::load_layers`]'s doc for why that order and no dedup).
1008 Append,
1009 /// Two layers declaring it is refused; see
1010 /// [`Config::refuse_split_arrays`].
1011 Replace,
1012}
1013
1014/// The single place that decides, for a dotted array key (as returned by
1015/// [`array_keys`]), whether declaring it in two config layers is a
1016/// concatenation the operator asked for or a silent accident.
1017///
1018/// Kept as one match so the whole policy is visible in one place - the same
1019/// reason `claude_quota` and `dropped_stream` close their own classification
1020/// in one spot elsewhere in this codebase. Anything not listed defaults to
1021/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
1022/// reasoned about yet, and a new array key added later has to be added here
1023/// deliberately to become appendable.
1024///
1025/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
1026/// gate. Concatenating two of them is exactly the checks both layers
1027/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
1028/// live in a shared layer while a repository's own layer adds its own
1029/// command, instead of every repository copying the shared command into
1030/// its own file.
1031/// - `repos.roots` — a set of directories to scan for checkouts. A
1032/// repository adding its own root on top of the machine's is additive by
1033/// nature, not a replacement of where the machine looks; see
1034/// [`Repos::roots`].
1035///
1036/// Left on the refuse side, and why:
1037/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
1038/// list of *seats*, not a set. A machine's two implementers plus a
1039/// repository's one is three seats nobody asked for and nobody is paying
1040/// for on purpose.
1041/// - `notify.command` — an argv. Concatenating two argvs does not produce a
1042/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
1043/// - `blind.strip_lines` — technically safe to concatenate (each entry is
1044/// matched as an independent substring, so a longer list only strips
1045/// *more*), but left on the refuse side anyway: the same list also drives
1046/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
1047/// and a silent three-layer merge is exactly the kind of surprise
1048/// `refuse_split_arrays` exists to catch rather than to reason about
1049/// case-by-case. A repository that wants one more stripped phrase restates
1050/// the whole list; that restatement is visible in review, an accidental
1051/// concatenation would not be.
1052fn array_merge_policy(key: &str) -> ArrayMerge {
1053 match key {
1054 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1055 _ => ArrayMerge::Replace,
1056 }
1057}
1058
1059impl Config {
1060 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1061 /// and the `include = [...]` directive.
1062 pub fn load(path: &Path) -> Result<Self> {
1063 Self::load_layers(&[path.to_path_buf()])
1064 }
1065
1066 /// The Tera render context shared by every layer: `system.*` (from
1067 /// teravars), `env` (magi's own addition - a config that names a shared
1068 /// build-cache directory or a machine-specific path needs
1069 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1070 /// derived from the last (highest-priority) path's parent directory.
1071 ///
1072 /// Factored out so [`Config::array_provenance`] can re-render a single
1073 /// layer under the exact same context [`Config::load_layers`] uses for
1074 /// the joint render, rather than drifting from it by accident.
1075 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1076 let mut ctx = teravars::system_context();
1077 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1078 ctx.insert("env", &env);
1079 if let Some(last) = paths.last()
1080 && let Some(dir) = last.parent()
1081 {
1082 ctx.insert("repo", &dir.to_string_lossy());
1083 ctx.insert(
1084 "repo_name",
1085 &dir.file_name().unwrap_or_default().to_string_lossy(),
1086 );
1087 }
1088 ctx
1089 }
1090
1091 /// Load and deep-merge a stack of config files, later files winning.
1092 ///
1093 /// This is why the config is TOML-through-teravars rather than plain serde:
1094 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1095 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1096 /// there). Picking one file and ignoring the other would force every repo
1097 /// to restate the roster.
1098 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1099 let mut engine = teravars::Engine::default();
1100 let ctx = Self::render_ctx(paths);
1101 if paths.len() > 1 {
1102 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
1103 }
1104 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
1105 format!(
1106 "rendering config via teravars: {}",
1107 paths
1108 .iter()
1109 .map(|p| p.display().to_string())
1110 .collect::<Vec<_>>()
1111 .join(", ")
1112 )
1113 })?;
1114 let mut table = merged.config;
1115 // `[vars]` is teravars' own input, already resolved into the render
1116 // context; `deny_unknown_fields` must not trip over it.
1117 table.remove("vars");
1118 toml::Value::Table(table)
1119 .try_into()
1120 .context("deserializing magi config")
1121 }
1122
1123 /// Refuse an array that two layers both declare, unless
1124 /// [`array_merge_policy`] says that key is meant to accumulate.
1125 ///
1126 /// teravars **appends** arrays when it merges layers, and that is wrong for
1127 /// most arrays magi has: `implementers` is an ordered list of seats,
1128 /// `notify.command` is an argv. Concatenating two of them yields something
1129 /// nobody wrote - three implementers out of a machine's two and a
1130 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1131 ///
1132 /// Replacing instead would be the right merge rule for those keys, but the
1133 /// rule lives in teravars, which several other projects depend on;
1134 /// changing it there is a decision for that crate, not something to fake
1135 /// here by re-reading the files with different semantics and hoping the
1136 /// two paths agree.
1137 ///
1138 /// So magi refuses the ambiguity rather than resolving it silently, for
1139 /// every array key except the short, deliberate list
1140 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1141 /// concatenation teravars already produces *is* what both files say, so
1142 /// there is nothing to refuse. The cost of guessing wrong on the refused
1143 /// keys is a roster the operator did not ask for and is paying for by the
1144 /// token; the append keys carry no such risk because every element runs
1145 /// (or every directory is scanned) regardless of order.
1146 fn refuse_split_arrays(
1147 paths: &[PathBuf],
1148 engine: &mut teravars::Engine,
1149 ctx: &teravars::Context,
1150 ) -> Result<()> {
1151 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1152 for path in paths {
1153 let one = teravars::load_merged([path], engine, ctx)
1154 .with_context(|| format!("rendering {}", path.display()))?;
1155 for key in array_keys(&one.config, "") {
1156 if array_merge_policy(&key) == ArrayMerge::Append {
1157 continue;
1158 }
1159 if let Some(first) = seen.get(&key) {
1160 bail!(
1161 "`{key}` is an array declared in two config layers:\n \
1162 {}\n {}\nteravars appends arrays when it merges, so \
1163 magi would run the concatenation of both - which is \
1164 not what either file says. Declare `{key}` in exactly \
1165 one of them.",
1166 first.display(),
1167 path.display()
1168 );
1169 }
1170 seen.insert(key, path.clone());
1171 }
1172 }
1173 Ok(())
1174 }
1175
1176 /// Which layers contributed to a composed, appendable array key (e.g.
1177 /// `"verify.gate"`), in the same low-to-high-priority order
1178 /// [`Config::load_layers`] concatenates them in. Layers that do not
1179 /// declare `key` at all are omitted.
1180 ///
1181 /// This is a **display aid for `magi doctor` only.** The command list
1182 /// that actually runs always comes from the one joint
1183 /// [`teravars::load_merged`] call in `load_layers`, never from this
1184 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
1185 /// about is two merge paths that might disagree, so this function must
1186 /// never become a second source of the *composed* value, only of which
1187 /// file wrote which line in it.
1188 ///
1189 /// Re-rendering each layer alone can, in principle, resolve a
1190 /// `{{ vars.x }}` differently than the joint render would, if `x` is
1191 /// defined in one layer and referenced in another - the same caveat
1192 /// `refuse_split_arrays`'s structural, key-only check already lives with.
1193 /// None of magi's own gate commands cross that line, and a doctor listing
1194 /// is read by a human who can compare it against the joint one printed
1195 /// alongside it, so this is judged worth the simplicity of not
1196 /// threading provenance through the real load path.
1197 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1198 let mut engine = teravars::Engine::default();
1199 let ctx = Self::render_ctx(paths);
1200 let mut out = Vec::new();
1201 for path in paths {
1202 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1203 continue;
1204 };
1205 let mut cur = &one.config;
1206 let mut found = None;
1207 let parts: Vec<&str> = key.split('.').collect();
1208 for (i, part) in parts.iter().enumerate() {
1209 match cur.get(*part) {
1210 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1211 found = Some(a);
1212 break;
1213 }
1214 Some(toml::Value::Table(t)) => cur = t,
1215 _ => break,
1216 }
1217 }
1218 let Some(values) = found else { continue };
1219 let strings: Vec<String> = values
1220 .iter()
1221 .filter_map(|v| v.as_str().map(str::to_owned))
1222 .collect();
1223 if !strings.is_empty() {
1224 out.push((path.clone(), strings));
1225 }
1226 }
1227 out
1228 }
1229
1230 /// Render a composed command list for `magi doctor`: the joined command
1231 /// line the run actually uses, plus - only when more than one layer
1232 /// contributed - which layer wrote which line.
1233 ///
1234 /// A single contributing layer (the common case today) stays the plain
1235 /// one-line summary magi has always printed, `empty` included: that
1236 /// honest "(none — ...)" is what caught a real gate-composition gap
1237 /// before this array could compose at all, and composition should not
1238 /// make the common case noisier.
1239 pub fn describe_composed(
1240 paths: &[PathBuf],
1241 commands: &[String],
1242 key: &str,
1243 empty: &str,
1244 ) -> String {
1245 if commands.is_empty() {
1246 return empty.to_owned();
1247 }
1248 let joined = commands.join(" && ");
1249 let provenance = Self::array_provenance(paths, key);
1250 if provenance.len() <= 1 {
1251 return joined;
1252 }
1253 let mut out = joined;
1254 for (path, cmds) in &provenance {
1255 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1256 }
1257 out
1258 }
1259
1260 /// Resolve the config for `repo`, honouring an explicit `--config` path.
1261 ///
1262 /// Returns the config and the layers it came from, empty for built-in
1263 /// defaults.
1264 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1265 if let Some(p) = explicit {
1266 let paths = vec![p.to_path_buf()];
1267 return Ok((Self::load_layers(&paths)?, paths));
1268 }
1269 let paths = Self::layers(repo);
1270 if paths.is_empty() {
1271 return Ok((Self::autodetected(), paths));
1272 }
1273 Ok((Self::load_layers(&paths)?, paths))
1274 }
1275 /// Environment variable that relocates the machine-wide config layer.
1276 ///
1277 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1278 /// of the one under [`dirs::config_dir`]; set it to the empty string and
1279 /// magi reads no machine layer at all.
1280 ///
1281 /// This exists because the machine layer is otherwise unavoidable, and a
1282 /// test that builds a config fixture is not asking for the operator's
1283 /// preferences to be merged into it. Adding `[repos] roots` to the real
1284 /// machine config on a development box turned two passing tests red -
1285 /// `repos_list_returns_name_and_path_for_every_configured_root` and
1286 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1287 /// declare `[repos] roots` of their own, which [`Config::layers`] then
1288 /// found in two layers and [`Config::refuse_split_arrays`] correctly
1289 /// refused. CI never saw it: a runner has no machine config, so the suite
1290 /// was green there and red only where somebody actually uses magi.
1291 ///
1292 /// An operator gets the same escape hatch for free: a second machine
1293 /// config, or none, without moving files about.
1294 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1295
1296 /// Every config layer that applies to `repo`, in increasing precedence.
1297 ///
1298 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1299 /// which is nothing at all in a test build.
1300 pub fn layers(repo: &Path) -> Vec<PathBuf> {
1301 let mut paths = Vec::new();
1302 paths.extend(Self::machine_layer());
1303 paths.push(repo.join(".magi").join("config.toml"));
1304 paths.push(repo.join("magi.toml"));
1305 paths.retain(|p| p.is_file());
1306 paths
1307 }
1308
1309 /// The machine-wide layer's path, when there is one.
1310 ///
1311 /// **A test build has none unless it names one.** A fixture is a complete
1312 /// statement of the config under test, and the operator's own preferences
1313 /// have no business being merged into it - least of all silently, on one
1314 /// machine, in a suite that is green everywhere else.
1315 #[cfg(test)]
1316 fn machine_layer() -> Option<PathBuf> {
1317 std::env::var(Self::CONFIG_DIR_ENV)
1318 .ok()
1319 .filter(|dir| !dir.trim().is_empty())
1320 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1321 }
1322
1323 /// The machine-wide layer's path, when there is one.
1324 #[cfg(not(test))]
1325 fn machine_layer() -> Option<PathBuf> {
1326 match std::env::var(Self::CONFIG_DIR_ENV) {
1327 // Named, and empty on purpose: no machine layer.
1328 Ok(dir) if dir.trim().is_empty() => None,
1329 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1330 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1331 }
1332 }
1333
1334 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1335 pub fn autodetected() -> Self {
1336 let mut cfg = Self::default();
1337 for (kind, id, model) in [
1338 (AgentKind::Claude, "opus", Some("opus")),
1339 (AgentKind::Claude, "sonnet", Some("sonnet")),
1340 (AgentKind::Antigravity, "antigravity", None),
1341 (AgentKind::Opencode, "opencode", None),
1342 (AgentKind::Codex, "codex", None),
1343 (AgentKind::Omp, "omp", None),
1344 ] {
1345 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1346 cfg.agents.push(AgentSpec {
1347 id: id.to_owned(),
1348 kind,
1349 model: model.map(str::to_owned),
1350 command: Vec::new(),
1351 extra_args: Vec::new(),
1352 env: BTreeMap::new(),
1353 prompt_delivery: None,
1354 });
1355 }
1356 }
1357 cfg
1358 }
1359
1360 /// The shared build cache the verify commands and the agents both build
1361 /// into, when the config declares one. See [`Verify::cache_dir`].
1362 pub fn cache_dir(&self) -> Option<PathBuf> {
1363 self.verify.cache_dir()
1364 }
1365
1366 /// Look an agent up by id.
1367 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1368 self.agents
1369 .iter()
1370 .find(|a| a.id == id)
1371 .with_context(|| format!("no agent with id `{id}` in the roster"))
1372 }
1373
1374 /// Rotate `count` seats out of `ids`, or out of the whole roster at
1375 /// `offset` when `ids` is empty.
1376 ///
1377 /// The one rotation rule - explicit ids cycle, an empty list rotates the
1378 /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
1379 /// rather than each seat reimplementing it and drifting apart.
1380 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1381 let mut out = Vec::with_capacity(count);
1382 for i in 0..count {
1383 let spec = if ids.is_empty() {
1384 self.agents[(i + offset) % self.agents.len()].clone()
1385 } else {
1386 self.agent(&ids[i % ids.len()])?.clone()
1387 };
1388 out.push(spec);
1389 }
1390 Ok(out)
1391 }
1392
1393 /// `ids`, resolved to specs in the order named, or the whole `[[agents]]`
1394 /// roster in file order when `ids` is empty — the same "explicit ids
1395 /// stand alone, an empty list means the whole roster" rule [`Self::rotate`]
1396 /// applies, but with no `count` to truncate to and no `offset` to wrap by.
1397 /// See [`ResolvedRoles::implementer_roster`] for why a truncated, rotated
1398 /// list cannot answer the question this exists for.
1399 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
1400 if ids.is_empty() {
1401 Ok(self.agents.clone())
1402 } else {
1403 ids.iter().map(|id| self.agent(id).cloned()).collect()
1404 }
1405 }
1406
1407 /// Fill the roles out to the configured widths.
1408 ///
1409 /// An empty role list rotates through the whole roster, so a three-agent
1410 /// roster with `candidates = 3` gives one implementation per agent, and
1411 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1412 /// author of candidate *i* whenever the roster has more than one agent.
1413 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1414 if self.agents.is_empty() {
1415 bail!(
1416 "agent roster is empty: no agent CLI found on PATH and no \
1417 [[agents]] in the config. Run `magi init` to write a starter \
1418 magi.toml."
1419 );
1420 }
1421 Ok(ResolvedRoles {
1422 implementers: self.rotate(&self.roles.implementers, self.graph.candidates, 0)?,
1423 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1424 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1425 fixer: self
1426 .roles
1427 .fixer
1428 .as_deref()
1429 .map(|f| self.agent(f).cloned())
1430 .transpose()?,
1431 // Role resolution validates roster shape, but deliberately does
1432 // not preflight a CLI. The other graph seats have always deferred
1433 // that failure to invocation; doing it only for the conductor
1434 // made otherwise usable graph commands and `doctor` fail as one.
1435 conductor: match self.roles.conductor.as_deref() {
1436 Some(id) => self.agent(id)?.clone(),
1437 // Keep the normal standalone-seat preference when something
1438 // is installed, but retain a roster fallback when it is not.
1439 // Invocation then reports the unavailable CLI in the same
1440 // place it does for every other graph role.
1441 None => crate::agent::pick(&self.agents, None, &crate::agent::installed)
1442 .unwrap_or_else(|_| self.agents[0].clone()),
1443 },
1444 implementer_roster: self.full_roster(&self.roles.implementers)?,
1445 })
1446 }
1447
1448 /// Advisor seats for the design-deliberation stage (see
1449 /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
1450 /// judge roster - see [`Roles::advisors`] for why that fallback and not
1451 /// the whole roster.
1452 ///
1453 /// The fallback rotates with `offset = 1`, matching the judges line in
1454 /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
1455 /// `roles.judges`, which is empty whenever judges themselves are
1456 /// unconfigured and rotating the whole roster. Falling back with
1457 /// `offset = 0` there would silently hand the advisors a *different*
1458 /// agent set than the judges an unconfigured run would actually get,
1459 /// which is the one thing [`Roles::advisors`]'s doc promises will not
1460 /// happen.
1461 ///
1462 /// Called lazily from the graph node itself rather than folded into
1463 /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
1464 /// not stop a run from starting at all - the deliberation stage is an
1465 /// enrichment `[graph] advise` can turn off, not a seat later nodes
1466 /// cannot proceed without - and at the point `resolve_roles` runs (before
1467 /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
1468 /// run yet for a resolution failure to be reported against.
1469 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
1470 if self.agents.is_empty() {
1471 bail!(
1472 "agent roster is empty: no agent CLI found on PATH and no \
1473 [[agents]] in the config. Run `magi init` to write a starter \
1474 magi.toml."
1475 );
1476 }
1477 if !self.roles.advisors.is_empty() {
1478 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
1479 }
1480 self.rotate(&self.roles.judges, self.graph.advisors, 1)
1481 }
1482
1483 /// Shell prefix for [`Verify`] commands.
1484 pub fn shell(&self) -> Vec<String> {
1485 if let Some(s) = &self.verify.shell {
1486 return s.clone();
1487 }
1488 if which("sh") {
1489 vec!["sh".to_owned(), "-c".to_owned()]
1490 } else {
1491 vec!["cmd".to_owned(), "/C".to_owned()]
1492 }
1493 }
1494
1495 /// Starter config, as written by `magi init`.
1496 pub fn starter_toml() -> String {
1497 let detected = Self::autodetected();
1498 let mut s = String::from(
1499 "# magi — blind multi-agent implementation competition.\n\
1500 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
1501 # -> blind judging -> deliberation -> private final vote\n\
1502 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
1503 #\n\
1504 # Rendered by teravars: a `[vars]` table, env\n\
1505 # and system lookups, and `include = [...]` all work. Tera\n\
1506 # braces are live everywhere in this file, but comments are\n\
1507 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
1508 # may quote `{{ ... }}` freely.\n\
1509 #\n\
1510 # Layers deep-merge in increasing\n\
1511 # precedence, so the roster can live once per machine in\n\
1512 # <config_dir>/magi/config.toml and each repo only states its own\n\
1513 # gate:\n\
1514 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
1515 [vars]\n\
1516 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
1517 # Single quotes inside the braces: teravars renders the raw file\n\
1518 # text, so TOML's own \\\" escaping never reaches Tera.\n\
1519 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
1520 );
1521 if detected.agents.is_empty() {
1522 s.push_str(
1523 "# No agent CLI was found on PATH. Fill this in by hand.\n\
1524 # kind = claude | opencode | antigravity | codex | command\n\
1525 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
1526 );
1527 } else {
1528 for a in &detected.agents {
1529 s.push_str("[[agents]]\n");
1530 s.push_str(&format!("id = {:?}\n", a.id));
1531 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
1532 if let Some(m) = &a.model {
1533 s.push_str(&format!("model = {m:?}\n"));
1534 }
1535 s.push('\n');
1536 }
1537 }
1538 s.push_str(
1539 "# Leave a role list empty to rotate through the roster.\n\
1540 [roles]\n\
1541 implementers = []\n\
1542 judges = []\n\
1543 reviewers = []\n\
1544 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
1545 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\n\
1546 [graph]\n\
1547 candidates = 3\n\
1548 judges = 3\n\
1549 deliberate_rounds = 1\n\
1550 reviewers = 3\n\
1551 review_rounds = 6\n\
1552 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
1553 gate_fix_rounds = 1\n\
1554 max_parallel = 4\n\
1555 language = \"en\"\n\
1556 # One CLI conversation per seat: judges keep their own argument\n\
1557 # across deliberation, the fixer keeps its implementation context.\n\
1558 sessions = true\n\
1559 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
1560 # the final gate inherit this value for compatibility.\n\
1561 timeout_review = 1200\n\
1562 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
1563 # verification independent if timeout_review changes later.\n\
1564 # timeout_verify = 1200\n\n\
1565 [verify]\n\
1566 # Run once per review round in the winner's worktree; failures are\n\
1567 # fed back to the fixer.\n\
1568 e2e = []\n\
1569 # Final gate. Every command must exit 0 before a merge.\n\
1570 gate = []\n\
1571 # Mechanical fixers (formatters) run in the winner's worktree just\n\
1572 # before the gate; whatever they change becomes one commit. A failing\n\
1573 # command only warns - the gate stays the arbiter. Same timeout as the\n\
1574 # gate (timeout_verify). Keep it light and idempotent.\n\
1575 # pre_gate = []\n\n\
1576 [merge]\n\
1577 # none | local | pr\n\
1578 mode = \"none\"\n\
1579 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
1580 [update]\n\
1581 # off | notify | install — checked in the background, throttled.\n\
1582 mode = \"notify\"\n\
1583 # interval = \"24h\"\n",
1584 );
1585 s
1586 }
1587}
1588
1589/// Is `program` on `PATH`?
1590pub fn which(program: &str) -> bool {
1591 find_program(program).is_some()
1592}
1593
1594/// The file a bare `program` name resolves to on `PATH`, the way the OS shell
1595/// would find it.
1596///
1597/// Spawn agents through this, not by bare name: on Windows Rust's std
1598/// only tries `name.exe`, so a CLI installed as an npm `.cmd` shim (codex
1599/// since its 2026-09-23 reinstall) is "not found" even though a shell runs it.
1600/// On Windows an extensionless file is never a match: npm writes an `sh`
1601/// script beside every `.cmd` shim, and spawning that fails with os error 193.
1602pub fn find_program(program: &str) -> Option<PathBuf> {
1603 find_program_on(program, &std::env::var_os("PATH")?)
1604}
1605
1606/// [`find_program`] against an explicit `PATH`, for a child whose environment
1607/// overrides it.
1608pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
1609 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
1610 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
1611}
1612
1613fn find_program_in(
1614 program: &str,
1615 paths: &std::ffi::OsStr,
1616 pathext: Option<&str>,
1617) -> Option<PathBuf> {
1618 let p = Path::new(program);
1619 if p.components().count() > 1 {
1620 return p.is_file().then(|| p.to_path_buf());
1621 }
1622 std::env::split_paths(paths).find_map(|dir| match pathext {
1623 Some(exts) => {
1624 let bare = dir.join(program);
1625 if p.extension().is_some() && bare.is_file() {
1626 return Some(bare);
1627 }
1628 exts.split(';')
1629 .filter(|e| !e.is_empty())
1630 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
1631 .find(|c| c.is_file())
1632 }
1633 None => Some(dir.join(program)).filter(|c| c.is_file()),
1634 })
1635}
1636
1637#[cfg(test)]
1638mod tests {
1639 use super::*;
1640
1641 /// npm writes an extensionless `sh` script beside `codex.cmd`; on Windows
1642 /// the `.cmd` is the spawnable one (os error 193 otherwise, 2026-09-23).
1643 #[test]
1644 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
1645 let dir = tempfile::tempdir().unwrap();
1646 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
1647 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
1648 let paths = dir.path().as_os_str();
1649 assert_eq!(
1650 find_program_in("codex", paths, Some(".EXE;.CMD")),
1651 Some(dir.path().join("codex.cmd"))
1652 );
1653 assert_eq!(
1654 find_program_in("codex", paths, None),
1655 Some(dir.path().join("codex"))
1656 );
1657 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
1658 }
1659
1660 fn spec(id: &str) -> AgentSpec {
1661 AgentSpec {
1662 id: id.to_owned(),
1663 kind: AgentKind::Command,
1664 model: None,
1665 command: vec!["true".to_owned()],
1666 extra_args: Vec::new(),
1667 env: BTreeMap::new(),
1668 prompt_delivery: None,
1669 }
1670 }
1671
1672 #[test]
1673 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
1674 // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
1675 // under `timeout_review`. A config written before this field existed
1676 // must run exactly as before, which means its default has to be the
1677 // same 1200s `timeout_review` has always defaulted to.
1678 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
1679 assert_eq!(g.timeout_verify, None);
1680 assert_eq!(g.verify_timeout(), 3600);
1681 }
1682
1683 #[test]
1684 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
1685 // The bug this field exists to close: `[graph] timeout_review = 45`
1686 // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
1687 // along with the reviewer seats' own timeout, because both read the
1688 // same field.
1689 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
1690 assert_eq!(g.timeout_review, 45);
1691 assert_eq!(
1692 g.verify_timeout(),
1693 45,
1694 "an omitted legacy value follows review"
1695 );
1696 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
1697 .expect("parse explicit override");
1698 assert_eq!(explicit.verify_timeout(), 1200);
1699 }
1700
1701 #[test]
1702 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
1703 // `deny_unknown_fields` cuts both ways: a config from before
1704 // `timeout_verify`/`e2e_every_round` existed must still parse, with
1705 // both defaulted rather than refused as unknown-in-reverse.
1706 let g: Graph =
1707 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
1708 .expect("an old-shaped [graph] table must still parse");
1709 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
1710 assert!(
1711 !g.e2e_every_round,
1712 "off by default, same as before this field existed"
1713 );
1714 }
1715
1716 #[test]
1717 fn empty_roles_rotate_judges_off_their_own_candidate() {
1718 // Three seats, said out loud: this is a test about *rotation*, and it
1719 // has nothing to say about how many candidates a task buys by default.
1720 let cfg = Config {
1721 agents: vec![spec("a"), spec("b"), spec("c")],
1722 graph: Graph {
1723 candidates: 3,
1724 ..Graph::default()
1725 },
1726 ..Config::default()
1727 };
1728 let roles = cfg.resolve_roles().unwrap();
1729 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
1730 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
1731 assert_eq!(impls, ["a", "b", "c"]);
1732 assert_eq!(judges, ["b", "c", "a"]);
1733 for (i, j) in judges.iter().enumerate() {
1734 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
1735 }
1736 }
1737
1738 #[test]
1739 fn single_agent_roster_fills_every_seat() {
1740 let cfg = Config {
1741 agents: vec![spec("solo")],
1742 graph: Graph {
1743 candidates: 3,
1744 ..Graph::default()
1745 },
1746 ..Config::default()
1747 };
1748 let roles = cfg.resolve_roles().unwrap();
1749 assert_eq!(roles.implementers.len(), 3);
1750 assert!(roles.judges.iter().all(|a| a.id == "solo"));
1751 }
1752
1753 #[test]
1754 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
1755 // `candidates = 1` (a solo run) still resolves `implementers` down to
1756 // one slot, but `implementer_roster` must carry every agent in the
1757 // roster, in file order, for `graph::Runner`'s quota fallback to walk
1758 // forward through once that one slot's agent runs out of quota.
1759 let cfg = Config {
1760 agents: vec![spec("a"), spec("b"), spec("c")],
1761 graph: Graph {
1762 candidates: 1,
1763 ..Graph::default()
1764 },
1765 ..Config::default()
1766 };
1767 let roles = cfg.resolve_roles().unwrap();
1768 assert_eq!(roles.implementers.len(), 1);
1769 let roster: Vec<&str> = roles
1770 .implementer_roster
1771 .iter()
1772 .map(|a| a.id.as_str())
1773 .collect();
1774 assert_eq!(roster, ["a", "b", "c"]);
1775 }
1776
1777 #[test]
1778 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
1779 let cfg = Config {
1780 agents: vec![spec("a"), spec("b"), spec("c")],
1781 roles: Roles {
1782 implementers: vec!["c".to_owned(), "a".to_owned()],
1783 ..Roles::default()
1784 },
1785 graph: Graph {
1786 candidates: 1,
1787 ..Graph::default()
1788 },
1789 ..Config::default()
1790 };
1791 let roles = cfg.resolve_roles().unwrap();
1792 // Unaffected by the new field: still just the first named id.
1793 assert_eq!(roles.implementers.len(), 1);
1794 assert_eq!(roles.implementers[0].id, "c");
1795 let roster: Vec<&str> = roles
1796 .implementer_roster
1797 .iter()
1798 .map(|a| a.id.as_str())
1799 .collect();
1800 assert_eq!(roster, ["c", "a"]);
1801 }
1802
1803 #[test]
1804 fn explicit_roles_win() {
1805 let cfg = Config {
1806 agents: vec![spec("a"), spec("b")],
1807 roles: Roles {
1808 implementers: vec!["b".to_owned()],
1809 judges: vec!["a".to_owned()],
1810 reviewers: Vec::new(),
1811 fixer: Some("a".to_owned()),
1812 ..Roles::default()
1813 },
1814 ..Config::default()
1815 };
1816 let roles = cfg.resolve_roles().unwrap();
1817 assert!(roles.implementers.iter().all(|a| a.id == "b"));
1818 assert!(roles.judges.iter().all(|a| a.id == "a"));
1819 assert_eq!(roles.fixer.unwrap().id, "a");
1820 assert_eq!(roles.conductor.id, "a");
1821 }
1822
1823 #[test]
1824 fn unknown_agent_id_is_an_error() {
1825 let cfg = Config {
1826 agents: vec![spec("a")],
1827 roles: Roles {
1828 judges: vec!["nope".to_owned()],
1829 ..Roles::default()
1830 },
1831 ..Config::default()
1832 };
1833 assert!(cfg.resolve_roles().is_err());
1834 }
1835
1836 #[test]
1837 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
1838 let mut cfg = Config {
1839 agents: vec![spec("a"), spec("b")],
1840 ..Config::default()
1841 };
1842 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
1843
1844 cfg.roles.conductor = Some("b".to_owned());
1845 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
1846
1847 cfg.roles.conductor = Some("missing".to_owned());
1848 assert!(cfg.resolve_roles().is_err());
1849 }
1850
1851 #[test]
1852 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
1853 // Unlike `conductor`, `synthesizer` is never validated by
1854 // `resolve_roles` — it is looked up lazily by
1855 // `graph::Runner::synthesize_brief` the same way `[roles] chatter`
1856 // is looked up by `talk::begin`, so this exercises `agent::pick`
1857 // directly instead of going through `resolve_roles`.
1858 let mut cfg = Config {
1859 agents: vec![spec("a"), spec("b")],
1860 ..Config::default()
1861 };
1862 let want = cfg.roles.synthesizer.as_deref();
1863 assert_eq!(
1864 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
1865 .unwrap()
1866 .id,
1867 "a",
1868 "unset falls back to agent::pick's own default order"
1869 );
1870
1871 cfg.roles.synthesizer = Some("b".to_owned());
1872 let want = cfg.roles.synthesizer.as_deref();
1873 assert_eq!(
1874 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
1875 .unwrap()
1876 .id,
1877 "b",
1878 "the named agent wins over the default order"
1879 );
1880 }
1881
1882 #[test]
1883 fn empty_roster_is_an_error() {
1884 assert!(Config::default().resolve_roles().is_err());
1885 }
1886
1887 #[test]
1888 fn advise_defaults_to_on_with_three_proposals() {
1889 let g = Graph::default();
1890 assert!(g.advise);
1891 assert_eq!(g.advisors, 3);
1892 }
1893
1894 #[test]
1895 fn unset_advisors_falls_back_to_the_judge_roster() {
1896 let cfg = Config {
1897 agents: vec![spec("a"), spec("b")],
1898 roles: Roles {
1899 judges: vec!["b".to_owned()],
1900 ..Roles::default()
1901 },
1902 graph: Graph {
1903 advisors: 2,
1904 ..Graph::default()
1905 },
1906 ..Config::default()
1907 };
1908 let advisors = cfg.advisors().expect("advisors resolve");
1909 assert_eq!(advisors.len(), 2);
1910 assert!(
1911 advisors.iter().all(|a| a.id == "b"),
1912 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
1913 );
1914 }
1915
1916 #[test]
1917 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
1918 let cfg = Config {
1919 agents: vec![spec("a"), spec("b")],
1920 roles: Roles {
1921 judges: vec!["b".to_owned()],
1922 advisors: vec!["a".to_owned()],
1923 ..Roles::default()
1924 },
1925 graph: Graph {
1926 advisors: 2,
1927 ..Graph::default()
1928 },
1929 ..Config::default()
1930 };
1931 let advisors = cfg.advisors().expect("advisors resolve");
1932 assert!(advisors.iter().all(|a| a.id == "a"));
1933 }
1934
1935 /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
1936 /// advisor roster must resolve to the exact same agents an unconfigured
1937 /// judge panel would get - same ids, same rotation offset - or the
1938 /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
1939 /// does not actually hold.
1940 #[test]
1941 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
1942 let cfg = Config {
1943 agents: vec![spec("a"), spec("b"), spec("c")],
1944 graph: Graph {
1945 advisors: 3,
1946 judges: 3,
1947 ..Graph::default()
1948 },
1949 ..Config::default()
1950 };
1951 let advisors = cfg.advisors().expect("advisors resolve");
1952 let judges = cfg.resolve_roles().expect("roles resolve").judges;
1953 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
1954 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
1955 assert_eq!(
1956 advisor_ids, judge_ids,
1957 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
1958 );
1959 }
1960
1961 #[test]
1962 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
1963 let cfg = Config {
1964 agents: vec![spec("a")],
1965 roles: Roles {
1966 advisors: vec!["nope".to_owned()],
1967 ..Roles::default()
1968 },
1969 graph: Graph {
1970 advisors: 1,
1971 ..Graph::default()
1972 },
1973 ..Config::default()
1974 };
1975 let err = cfg.advisors().expect_err("`nope` is not in the roster");
1976 assert!(format!("{err:#}").contains("nope"));
1977 }
1978
1979 #[test]
1980 fn repos_default_to_no_roots_and_a_day_of_trust() {
1981 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
1982 assert_eq!(Config::default().repos.scan_ttl, 86_400);
1983 }
1984
1985 #[test]
1986 fn a_config_file_with_no_repos_table_still_loads() {
1987 let dir = tempfile::tempdir().unwrap();
1988 let path = dir.path().join("magi.toml");
1989 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
1990 let cfg = Config::load(&path).expect("must load without [repos]");
1991 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
1992 assert_eq!(cfg.repos.scan_ttl, 86_400);
1993 }
1994
1995 /// A fixture is the whole config under test.
1996 ///
1997 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
1998 /// a machine where somebody had written `<config_dir>/magi/config.toml`
1999 /// the suite silently loaded it as the lowest layer. Adding `[repos]
2000 /// roots` there turned two web tests red - their fixtures declare
2001 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
2002 /// array key spread across two layers. CI stayed green throughout,
2003 /// because a runner has no such file: the suite failed only where magi is
2004 /// actually used.
2005 ///
2006 /// So a test build has no machine layer unless it asks for one, and this
2007 /// is that promise. Written against a real file at the real location so
2008 /// it fails if `machine_layer` starts reading it again.
2009 #[test]
2010 fn a_test_build_does_not_read_the_operators_machine_config() {
2011 let repo = tempfile::tempdir().unwrap();
2012 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
2013
2014 let layers = Config::layers(repo.path());
2015 assert_eq!(
2016 layers,
2017 vec![repo.path().join("magi.toml")],
2018 "only the fixture's own file may be a layer"
2019 );
2020 if let Some(real) = dirs::config_dir() {
2021 let machine = real.join("magi").join("config.toml");
2022 assert!(
2023 !layers.contains(&machine),
2024 "the operator's {} must not be a layer in a test build",
2025 machine.display()
2026 );
2027 }
2028 }
2029
2030 #[test]
2031 fn starter_toml_loads_through_teravars() {
2032 let dir = tempfile::tempdir().unwrap();
2033 let path = dir.path().join("magi.toml");
2034 std::fs::write(&path, Config::starter_toml()).unwrap();
2035 let parsed = Config::load(&path).expect("starter config must load");
2036 assert_eq!(parsed.graph.candidates, 3);
2037 assert_eq!(parsed.merge.mode, MergeMode::None);
2038 assert_eq!(parsed.merge.style, MergeStyle::Merge);
2039 assert!(parsed.graph.sessions);
2040 assert_eq!(parsed.graph.timeout_review, 1200);
2041 assert_eq!(parsed.graph.verify_timeout(), 1200);
2042 assert_eq!(parsed.update.mode, UpdateMode::Notify);
2043 }
2044
2045 #[test]
2046 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
2047 let dir = tempfile::tempdir().unwrap();
2048 let path = dir.path().join("magi.toml");
2049 std::fs::write(&path, Config::starter_toml()).unwrap();
2050 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
2051 assert!(Config::starter_toml().contains("# pre_gate = []"));
2052 }
2053
2054 #[test]
2055 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
2056 let starter = Config::starter_toml();
2057 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
2058 assert!(starter.contains("verification independent if timeout_review changes later"));
2059 assert!(starter.contains("# timeout_verify = 1200"));
2060 }
2061
2062 /// A repository whose ruleset forbids merge commits declares that once,
2063 /// here, rather than magi asking GitHub about it on every render (see
2064 /// [`MergeStyle`]'s own doc for why).
2065 #[test]
2066 fn a_repository_can_declare_a_linear_history_merge_style() {
2067 let dir = tempfile::tempdir().unwrap();
2068 let path = dir.path().join("magi.toml");
2069 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
2070 let parsed = Config::load(&path).expect("config must load");
2071 assert_eq!(parsed.merge.style, MergeStyle::Squash);
2072 }
2073
2074 #[test]
2075 fn later_layers_win_and_vars_render() {
2076 let dir = tempfile::tempdir().unwrap();
2077 let machine = dir.path().join("machine.toml");
2078 let project = dir.path().join("magi.toml");
2079 // The machine layer owns the roster...
2080 std::fs::write(
2081 &machine,
2082 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
2083 [graph]\ncandidates = 3\nmax_parallel = 8\n",
2084 )
2085 .unwrap();
2086 // ...and the project layer only states what is repo-specific, plus a
2087 // `[vars]` value interpolated into a command.
2088 std::fs::write(
2089 &project,
2090 "[vars]\ncache = \"/shared\"\n\n\
2091 [graph]\ncandidates = 2\n\n\
2092 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
2093 )
2094 .unwrap();
2095
2096 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
2097 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
2098 assert_eq!(cfg.graph.candidates, 2, "project layer wins");
2099 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
2100 assert_eq!(
2101 cfg.verify.gate,
2102 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
2103 );
2104 // The rendered command is where the cache path is read back from.
2105 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
2106 }
2107
2108 #[test]
2109 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
2110 // An operator who writes no `[graph]` timeout keys at all must still
2111 // land on the hour, not on the five/fifteen minutes this turn used
2112 // to hardcode before it read from config.
2113 let g = Graph::default();
2114 assert_eq!(g.timeout_talk, 3600);
2115
2116 let dir = tempfile::tempdir().unwrap();
2117 let path = dir.path().join("magi.toml");
2118 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
2119 let cfg = Config::load(&path).expect("must load without timeout_talk set");
2120 assert_eq!(cfg.graph.timeout_talk, 3600);
2121 }
2122
2123 #[test]
2124 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
2125 let dir = tempfile::tempdir().unwrap();
2126 let path = dir.path().join("magi.toml");
2127 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
2128 let cfg = Config::load(&path).expect("must load");
2129 assert_eq!(cfg.graph.timeout_talk, 120);
2130 }
2131
2132 #[test]
2133 fn the_disk_defaults_are_the_measurements_made_up_front() {
2134 let cfg = Config::default();
2135 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
2136 assert!(cfg.disk.auto_fold);
2137 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
2138 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
2139 }
2140
2141 #[test]
2142 fn an_unset_disk_section_is_the_safe_default() {
2143 let dir = tempfile::tempdir().unwrap();
2144 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
2145 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
2146 assert_eq!(cfg.disk, Disk::default());
2147 }
2148
2149 #[test]
2150 fn env_is_available_to_templates_with_a_default() {
2151 let dir = tempfile::tempdir().unwrap();
2152 let path = dir.path().join("magi.toml");
2153 // teravars ships no `env`; magi adds it, and the `default` filter has
2154 // to cover the unset case or every machine would need the variable.
2155 //
2156 // Deliberately no named variable: `env` is keyed by the exact spelling
2157 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
2158 // test asserting `env.PATH` passes on one runner and fails on another.
2159 // The map's non-emptiness is the platform-neutral claim.
2160 std::fs::write(
2161 &path,
2162 "[verify]\n\
2163 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
2164 \"populated={{ env | length > 0 }}\"]\n",
2165 )
2166 .unwrap();
2167 let cfg = Config::load(&path).expect("env lookup must render");
2168 assert_eq!(cfg.verify.gate[0], "cache=fallback");
2169 assert_eq!(cfg.verify.gate[1], "populated=true");
2170 }
2171
2172 #[test]
2173 fn a_broken_template_names_the_file() {
2174 let dir = tempfile::tempdir().unwrap();
2175 let path = dir.path().join("magi.toml");
2176 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
2177 let err = Config::load(&path).expect_err("must not silently ignore");
2178 assert!(err.to_string().contains("teravars"), "{err}");
2179 }
2180
2181 #[test]
2182 fn tera_syntax_in_comments_is_inert() {
2183 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
2184 // comment may quote template syntax without rendering. Before 0.2.2 this
2185 // load failed: the commented-out braces reached the template parser.
2186 let dir = tempfile::tempdir().unwrap();
2187 let path = dir.path().join("magi.toml");
2188 std::fs::write(
2189 &path,
2190 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
2191 [graph]\ncandidates = 2\n",
2192 )
2193 .unwrap();
2194 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
2195 assert_eq!(cfg.graph.candidates, 2);
2196 }
2197
2198 #[test]
2199 fn opencode_defaults_to_file_delivery() {
2200 let mut s = spec("oc");
2201 s.kind = AgentKind::Opencode;
2202 assert_eq!(s.delivery(), Delivery::File);
2203 s.prompt_delivery = Some(Delivery::Argv);
2204 assert_eq!(s.delivery(), Delivery::Argv);
2205 }
2206 #[test]
2207 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
2208 // Both default on, and that pair is the safety property: `land` takes
2209 // over the watching an operator was doing by hand, `land_approval`
2210 // keeps the irreversible step a human decision. An unattended merge
2211 // needs BOTH flipped, which has to be chosen deliberately twice.
2212 let g = Graph::default();
2213 assert!(
2214 g.land,
2215 "stopping at an open PR left the watching to a human"
2216 );
2217 assert!(
2218 g.land_approval,
2219 "on-by-default land is only defensible while this is also on"
2220 );
2221 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
2222 }
2223 #[test]
2224 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
2225 // teravars appends arrays. For an ordered list of seats, or an argv,
2226 // the concatenation is something neither file says - and the operator
2227 // pays for the extra seats by the token.
2228 let dir = tempfile::tempdir().unwrap();
2229 let machine = dir.path().join("machine.toml");
2230 let repo = dir.path().join("magi.toml");
2231 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
2232 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
2233
2234 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2235 .expect_err("two layers naming one array must not merge silently")
2236 .to_string();
2237 assert!(err.contains("roles.implementers"), "{err}");
2238 // Both files are named: the fix is to delete one of them, and the
2239 // operator has to know which two to choose between.
2240 assert!(err.contains("machine.toml"), "{err}");
2241 assert!(err.contains("magi.toml"), "{err}");
2242 }
2243
2244 #[test]
2245 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
2246 // The split the layering exists for: state a preference machine-wide,
2247 // let the repository own its own lists.
2248 let dir = tempfile::tempdir().unwrap();
2249 let machine = dir.path().join("machine.toml");
2250 let repo = dir.path().join("magi.toml");
2251 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
2252 std::fs::write(
2253 &repo,
2254 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
2255 [roles]\nimplementers = [\"oc\"]\n",
2256 )
2257 .unwrap();
2258
2259 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
2260 assert_eq!(cfg.roles.chatter.as_deref(), Some("opus"));
2261 assert_eq!(cfg.roles.implementers, ["oc"]);
2262 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
2263 }
2264
2265 #[test]
2266 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
2267 // The `editorconfig-checker` distribution problem: a shared layer
2268 // wants to add a gate command without erasing the repository's own.
2269 let dir = tempfile::tempdir().unwrap();
2270 let machine = dir.path().join("machine.toml");
2271 let repo = dir.path().join("magi.toml");
2272 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2273 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2274
2275 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2276 assert_eq!(
2277 cfg.verify.gate,
2278 [
2279 "editorconfig-checker".to_owned(),
2280 "cargo make check".to_owned()
2281 ],
2282 "low-priority (machine) command first, high-priority (repo) command after"
2283 );
2284 }
2285
2286 #[test]
2287 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
2288 let dir = tempfile::tempdir().unwrap();
2289 let machine = dir.path().join("machine.toml");
2290 let repo = dir.path().join("magi.toml");
2291 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
2292 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
2293
2294 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2295 assert_eq!(
2296 cfg.verify.e2e,
2297 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
2298 );
2299 }
2300
2301 #[test]
2302 fn two_layers_declaring_repos_roots_are_both_scanned() {
2303 let dir = tempfile::tempdir().unwrap();
2304 let machine = dir.path().join("machine.toml");
2305 let repo = dir.path().join("magi.toml");
2306 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
2307 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
2308
2309 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2310 assert_eq!(
2311 cfg.repos.roots,
2312 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
2313 );
2314 }
2315
2316 #[test]
2317 fn duplicate_gate_commands_across_layers_both_run() {
2318 // Dropping the duplicate would be a silent surprise; the operator
2319 // sees a slower gate, never a missing one.
2320 let dir = tempfile::tempdir().unwrap();
2321 let machine = dir.path().join("machine.toml");
2322 let repo = dir.path().join("magi.toml");
2323 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2324 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
2325
2326 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
2327 assert_eq!(
2328 cfg.verify.gate,
2329 ["same-command".to_owned(), "same-command".to_owned()]
2330 );
2331 }
2332
2333 #[test]
2334 fn notify_command_is_still_refused_across_two_layers() {
2335 // An argv, not a set: concatenating two of them is not a program.
2336 let dir = tempfile::tempdir().unwrap();
2337 let machine = dir.path().join("machine.toml");
2338 let repo = dir.path().join("magi.toml");
2339 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
2340 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
2341
2342 let err = Config::load_layers(&[machine.clone(), repo.clone()])
2343 .expect_err("an argv split across layers must not concatenate")
2344 .to_string();
2345 assert!(err.contains("notify.command"), "{err}");
2346 assert!(err.contains("machine.toml"), "{err}");
2347 assert!(err.contains("magi.toml"), "{err}");
2348 }
2349
2350 #[test]
2351 fn one_layer_declaring_verify_gate_runs_unchanged() {
2352 // The classification must not change behaviour for the configuration
2353 // this very repository has today: exactly one layer names the gate.
2354 let dir = tempfile::tempdir().unwrap();
2355 let path = dir.path().join("magi.toml");
2356 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2357
2358 let cfg = Config::load(&path).expect("single layer must still load");
2359 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
2360 }
2361
2362 #[test]
2363 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
2364 let dir = tempfile::tempdir().unwrap();
2365 let machine = dir.path().join("machine.toml");
2366 let repo = dir.path().join("magi.toml");
2367 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
2368 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
2369 let paths = vec![machine.clone(), repo.clone()];
2370
2371 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
2372 let described =
2373 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
2374 assert!(described.contains("editorconfig-checker && cargo make check"));
2375 assert!(
2376 described.contains(&machine.display().to_string()),
2377 "{described}"
2378 );
2379 assert!(
2380 described.contains(&repo.display().to_string()),
2381 "{described}"
2382 );
2383
2384 // A single contributing layer stays the plain one-line summary.
2385 let single = vec![repo.clone()];
2386 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
2387 let solo_described =
2388 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
2389 assert_eq!(solo_described, "cargo make check");
2390 }
2391}