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