magi/config.rs
1//! Run configuration: the agent roster, the shape of the graph, and the
2//! blindness / verification policy.
3//!
4//! Layers, lowest precedence first: `<config_dir>/magi/config.toml` (machine),
5//! `.magi/config.toml`, `magi.toml`. With none, built-in defaults apply, the
6//! agent roster derived from the agent CLIs actually installed on this
7//! machine. `--config <path>` replaces the whole stack with that one file.
8//!
9//! **The repository layers are read from `<remote>/<base>`, never from the
10//! working tree.** A primary checkout is often stale or on a detached HEAD, so
11//! a gate read from it can be older than the one the branch under review is
12//! cut from (run ce6e failed on a gate step `origin/main` had already
13//! dropped). `git show <sha>:magi.toml` of the remote-tracking ref's commit is
14//! written to a content-addressed directory under the git common dir
15//! (`<common>/magi/config/<sha>-<hash of repo>/`, temp dir when that is not
16//! writable) and loaded from there.
17//!
18//! `remote` and `base` are themselves in the file, so they are resolved in a
19//! fixed order, first hit wins:
20//!
21//! 1. `[merge] base` / `remote` of the machine layer, rendered as a real load
22//! would (env templates, includes);
23//! 2. the same keys, read minimally (only `[merge]`, nothing deserialized into
24//! `Config`) from the checkout's `magi.toml`, then `.magi/config.toml` -
25//! only to *locate* the ref; an unreadable file is ignored;
26//! 3. `remote` defaults to `origin`, `base` to what
27//! `refs/remotes/<remote>/HEAD` points at.
28//!
29//! [`Config::discover`] is synchronous and reads the remote-tracking ref as it
30//! is (`daemon::fetch_loop` keeps it fresh); [`Config::discover_fetched`] runs
31//! `git fetch` first and is what every path that starts work uses. A failed
32//! fetch, a missing ref or an unresolvable base is an **error**, never a
33//! silent fall back to the working tree or a local branch. Two cases are not
34//! that: an explicit `--config`, and a `repo` that is not a git working tree
35//! at all (no branch exists, so nothing can be stale).
36//!
37//! A repository layer that declares `include = [...]` gets the whole tree of
38//! that commit extracted, so relative includes resolve against the same
39//! commit. The directory is built beside its name and renamed in, so a
40//! concurrent `discover` never reads a half-written layer.
41use std::collections::BTreeMap;
42use std::path::{Path, PathBuf};
43
44use anyhow::{Context as _, Result, bail};
45use serde::{Deserialize, Serialize};
46
47/// Which CLI drives an agent.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
49#[serde(rename_all = "lowercase")]
50pub enum AgentKind {
51 /// Anthropic Claude Code (`claude -p`).
52 Claude,
53 /// opencode (`opencode run`).
54 Opencode,
55 /// Antigravity CLI (`agy -p`). Gemini CLI is deliberately absent: Google
56 /// retired the standalone client for individual accounts in favour of this
57 /// one, so an adapter for it would be dead code on a live machine.
58 Antigravity,
59 /// OpenAI Codex CLI (`codex exec`). The one roster member with a real
60 /// read-only mode: `--sandbox read-only` is enforced by the CLI, not by
61 /// the prompt.
62 Codex,
63 /// oh-my-pi (`omp -p --mode=json`). Another CLI with no read-only mode of
64 /// its own - `--auto-approve` gates reads and writes together - so a
65 /// read-only seat rests on the prompt and on the worktree discipline the
66 /// other non-codex seats already rely on. It is also the roster member that
67 /// reaches DeepSeek, whose models ship in `omp`'s own catalog.
68 Omp,
69 /// Arbitrary command. The escape hatch, and what the test suite drives.
70 Command,
71}
72
73impl AgentKind {
74 /// Executable that must be on `PATH` for this kind, if any.
75 pub fn program(self) -> Option<&'static str> {
76 match self {
77 Self::Claude => Some("claude"),
78 Self::Opencode => Some("opencode"),
79 Self::Antigravity => Some("agy"),
80 Self::Codex => Some("codex"),
81 Self::Omp => Some("omp"),
82 Self::Command => None,
83 }
84 }
85
86 /// Lowercase name as written in the config file.
87 pub fn as_str(self) -> &'static str {
88 match self {
89 Self::Claude => "claude",
90 Self::Opencode => "opencode",
91 Self::Antigravity => "antigravity",
92 Self::Codex => "codex",
93 Self::Omp => "omp",
94 Self::Command => "command",
95 }
96 }
97
98 /// Every kind the roster can name, in display order.
99 ///
100 /// This is what `magi doctor` lists, and it has to be one list rather than
101 /// the same set typed out again wherever a kind is enumerated. The last
102 /// time it was typed out twice, `omp` was added as a roster member and the
103 /// doctor output went on saying the machine had four CLIs - which reads as
104 /// "that agent is not installed" to the person the command exists for.
105 pub const ALL: [Self; 6] = [
106 Self::Claude,
107 Self::Opencode,
108 Self::Antigravity,
109 Self::Codex,
110 Self::Omp,
111 Self::Command,
112 ];
113}
114
115/// How the prompt reaches the agent process.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
117#[serde(rename_all = "lowercase")]
118pub enum Delivery {
119 /// Piped on stdin.
120 Stdin,
121 /// Passed as a positional argument. Beware OS command-line limits.
122 Argv,
123 /// Written to a file; the agent is told to read it. No length limit.
124 File,
125}
126
127/// One addressable agent in the roster.
128#[derive(Debug, Clone, Deserialize, Serialize)]
129#[serde(deny_unknown_fields)]
130pub struct AgentSpec {
131 /// Stable identifier used by `[roles]` and by the stats tables.
132 pub id: String,
133 /// Which CLI to drive.
134 pub kind: AgentKind,
135 /// Model passed through to the CLI (`--model` / `-m`). CLI default if unset.
136 #[serde(default)]
137 pub model: Option<String>,
138 /// `kind = "command"` only: argv. Supports `{prompt_file}`, `{cwd}`,
139 /// `{label}`, `{session}` placeholders.
140 #[serde(default)]
141 pub command: Vec<String>,
142 /// Extra arguments appended to the built command line.
143 #[serde(default)]
144 pub extra_args: Vec<String>,
145 /// Extra environment variables for the child process.
146 #[serde(default)]
147 pub env: BTreeMap<String, String>,
148 /// Override the per-kind prompt delivery default.
149 #[serde(default)]
150 pub prompt_delivery: Option<Delivery>,
151}
152
153impl AgentSpec {
154 /// Default prompt delivery for this agent.
155 ///
156 /// `opencode` and `agy` take the prompt as an argument, which on Windows
157 /// caps out around 32 KiB — well under a judging prompt carrying three
158 /// patches — so both get a file instead.
159 pub fn delivery(&self) -> Delivery {
160 self.prompt_delivery.unwrap_or(match self.kind {
161 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
162 // `codex exec -` reads the prompt from stdin, so the whole
163 // instruction arrives without an argv length limit and without a
164 // tool round-trip to open a file.
165 AgentKind::Codex => Delivery::Stdin,
166 // `omp -p` reads the prompt from stdin too, and a judging prompt
167 // carrying three patches is well past the Windows argv cap, so this
168 // is the only delivery that works for every node.
169 AgentKind::Omp => Delivery::Stdin,
170 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
171 })
172 }
173
174 /// Human-facing label, e.g. `opus (claude:opus)`.
175 pub fn display(&self) -> String {
176 match &self.model {
177 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
178 None => format!("{} ({})", self.id, self.kind.as_str()),
179 }
180 }
181}
182
183/// A standalone seat's agent: one roster id, or an ordered fallback chain.
184///
185/// The string form is what every existing config uses and serializes back as
186/// a string; the array form tries each id at most once, in order, moving on
187/// when a call ends in quota or fails (see [`crate::agent::pick_chain`]).
188/// An empty string or array is the same as unset.
189#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
190#[serde(untagged)]
191pub enum AgentChoice {
192 /// One agent id.
193 One(String),
194 /// Ordered fallback chain of agent ids.
195 Chain(Vec<String>),
196}
197
198impl AgentChoice {
199 /// The ids named, in order, with blanks dropped. Empty means unset.
200 pub fn ids(&self) -> Vec<&str> {
201 let all: Vec<&str> = match self {
202 Self::One(id) => vec![id.as_str()],
203 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
204 };
205 all.into_iter()
206 .map(str::trim)
207 .filter(|id| !id.is_empty())
208 .collect()
209 }
210
211 /// The first id named, if any.
212 pub fn primary(&self) -> Option<&str> {
213 self.ids().into_iter().next()
214 }
215}
216
217impl From<&str> for AgentChoice {
218 fn from(id: &str) -> Self {
219 Self::One(id.to_owned())
220 }
221}
222
223/// The first id of an optional choice: what a single-seat caller resolves.
224pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
225 choice.and_then(AgentChoice::primary)
226}
227
228/// Explicit role assignment. Empty lists are filled in by
229/// [`Config::resolve_roles`] by rotating the roster.
230#[derive(Debug, Clone, Default, Deserialize, Serialize)]
231#[serde(deny_unknown_fields, default)]
232pub struct Roles {
233 /// Agents that implement the task, one worktree each.
234 pub implementers: Vec<String>,
235 /// Agents that rank the candidates blind.
236 pub judges: Vec<String>,
237 /// Agents that review the winning patch.
238 pub reviewers: Vec<String>,
239 /// Agent that applies review findings. Defaults to the winner's author.
240 ///
241 /// Accepts one id or an ordered array of ids: a fallback chain, see
242 /// [`AgentChoice`]. The review loop, the gate-fix round, `land`'s fix
243 /// rounds and the rebase conflict round move to the next id when one
244 /// errors, hits its quota or answers nothing usable; each id is tried at
245 /// most once per call, and once a fallback answered, the rest of the run
246 /// starts from it (see `crate::fixer`). Unset keeps the winner's author.
247 pub fixer: Option<AgentChoice>,
248 /// Agent that answers the standing chat's turns (`src/talk.rs`).
249 ///
250 /// Unset picks a `claude` seat, else the first runnable agent in roster
251 /// order (see [`crate::agent::pick`]) - which is roster *order*, not a
252 /// judgement about who converses well. Naming one here matters once an
253 /// agent is also sitting as a judge: the chat is opened far more often
254 /// than any single competition, and every open competes with that judge
255 /// seat for the same account's concurrency. A timeout on an ordinary chat
256 /// turn traced to exactly this - `opus` triple-booked as chatter and judge
257 /// - is what this field exists to let an operator break apart.
258 ///
259 /// Accepts one id or an ordered array of ids: a fallback chain, see
260 /// [`AgentChoice`].
261 pub chatter: Option<AgentChoice>,
262 /// Agent that judges duplicate-work claims in [`crate::dupes`].
263 /// Unset inherits [`Self::chatter`], including its default agent selection.
264 /// Accepts a string or an ordered fallback chain, like [`Self::chatter`].
265 pub dupes_judge: Option<AgentChoice>,
266 /// Agent that arranges the queue between polls: `crate::conduct`'s single
267 /// seat, called once per cycle to decide a runnable task's `blocked_by`
268 /// and how a stalled or finished task recovers.
269 ///
270 /// The same precedent as [`Self::chatter`] for a seat that stands alone
271 /// rather than rotating through the roster - resolved through
272 /// [`crate::agent::pick`], so unset falls back to its own default order
273 /// (a claude seat, else the first runnable agent) rather than reusing a
274 /// judge or reviewer seat that the conductor's own poll-cycle cadence
275 /// would otherwise compete with for the same account's concurrency.
276 ///
277 /// Accepts a string or a fallback chain, like [`Self::chatter`].
278 pub conductor: Option<AgentChoice>,
279 /// Seats for the design-deliberation stage `graph::Runner::advise` runs
280 /// before `implement`: independent, read-only design proposals gathered
281 /// once a run has a settled task instruction and before any implementer
282 /// touches the repository.
283 ///
284 /// Empty falls back to `judges` rather than to the whole roster: a panel
285 /// trusted to rank patches independently is exactly the panel worth
286 /// asking to sketch a design independently, and an operator who has
287 /// already thought about judge diversity gets advisor diversity for free
288 /// instead of a fourth roster to maintain.
289 pub advisors: Vec<String>,
290 /// Agent that blends [`Self::advisors`]' proposals into the one design
291 /// brief `graph::Runner::synthesize_brief` carries into every
292 /// implementer's prompt.
293 ///
294 /// The same precedent as [`Self::chatter`] and [`Self::conductor`] for a
295 /// seat that stands alone rather than rotating through the roster -
296 /// resolved through [`crate::agent::pick`], so unset falls back to its
297 /// own default order (a claude seat, else the first runnable agent in
298 /// roster order) - exactly today's behavior, unchanged by leaving this
299 /// field out.
300 ///
301 /// Accepts a string or a fallback chain, like [`Self::chatter`].
302 pub synthesizer: Option<AgentChoice>,
303 /// Agent (normally a `kind = "command"` wrapper around Jev) that decides
304 /// whether a pull request title and prose are English, for
305 /// [`crate::github_text`]'s posting gate.
306 ///
307 /// Unset spawns nothing: the gate keeps its built-in heuristics. Set, a
308 /// failed, timed-out or unparsable call also falls back to them, so the
309 /// gate never depends on this seat being reachable. Accepts a string or a
310 /// fallback chain, like [`Self::chatter`].
311 pub language_judge: Option<AgentChoice>,
312}
313
314/// Graph shape and limits.
315#[derive(Debug, Clone, Deserialize, Serialize)]
316#[serde(deny_unknown_fields, default)]
317pub struct Graph {
318 /// Gate GitHub prose before posting. Secret redaction remains mandatory when disabled.
319 pub github_text_guard: bool,
320 /// Parallel implementations of the same task (the number of implementer
321 /// seats; pairs with [`Roles::implementers`]). **One by default.**
322 ///
323 /// Formerly `candidates`, still read as a deprecated alias.
324 ///
325 /// Competition is the thing magi is for, and it is still here - it is just
326 /// no longer what every task buys without being asked. Three days and 13
327 /// runs on this repository, which is the workload these numbers are drawn
328 /// from:
329 ///
330 /// - **0 of 13** competed runs reached a merge. Everything that landed in
331 /// that window went through `magi review` - the cheap half, no
332 /// competition - and passed on the first try.
333 /// - The judges' first choices **split 73% of the time** (8 of 11
334 /// tallies). Candidates that close together make the ranking a weak
335 /// signal for what it costs to produce.
336 /// - One run's own breakdown: implement 60min, judge 40min, fix 40min,
337 /// review 28min, **verify 5min** - and verify is the node that caught a
338 /// defect every reviewer had passed as clean. The cheapest step is the
339 /// one that earns its place every time.
340 ///
341 /// It is not worthless: `oc` won 3 of those tallies against `sonnet`, so a
342 /// single-seat default would have shipped the worse implementation in
343 /// roughly a quarter of them. That is exactly why this is a *default* and
344 /// not a removal - `magi run --candidates N` and a per-task seat count are
345 /// how a task that deserves a competition gets one.
346 ///
347 /// A single-candidate run needs no special case: `Runner::review`'s doc
348 /// records that `execute` already degrades to implement -> review -> gate
349 /// -> merge, because `judge` skips a one-candidate field, `deliberate` has
350 /// no two first choices to reconcile and `vote` returns early.
351 #[serde(alias = "candidates")]
352 pub implementers: usize,
353 /// Independent judges.
354 pub judges: usize,
355 /// Deliberation rounds when the judges' first choices disagree.
356 pub deliberate_rounds: usize,
357 /// Reviewers per review round. **Three by default** - the smallest panel
358 /// a lens cycle (see [`crate::prompt::Lens`]) covers exactly once, so the
359 /// default panel reads the patch for spec compliance, regressions, and
360 /// simplicity without repeating an angle. Review is also the one stage
361 /// [`Self::implementers`]'s doc describes as running on every task
362 /// regardless of competition, which is what makes a panel worth its cost
363 /// here even though `implementers` itself defaults to one.
364 pub reviewers: usize,
365 /// Maximum review+fix rounds before the run is declared blocked.
366 pub review_rounds: usize,
367 /// Fix rounds a failing `verify.gate` gets before the run is blocked. The
368 /// fixer is handed the gate's own output; `0` keeps the old behaviour of
369 /// blocking on the first red gate. Independent of [`Self::review_rounds`]
370 /// so a run that spent its review budget can still repair a one-line gate
371 /// failure.
372 pub gate_fix_rounds: usize,
373 /// Maximum agent processes running at once.
374 pub max_parallel: usize,
375 /// Language for the prose the agents write (`en` / `ja` / any language name).
376 pub language: String,
377 /// Keep one CLI conversation per seat, so a judge remembers its own
378 /// argument across deliberation rounds and the fixer remembers its own
379 /// implementation across review rounds.
380 ///
381 /// Sessions are scoped to a *seat*, never to an agent id: the same model
382 /// sitting as implementer and as judge gets two unrelated conversations,
383 /// which is what keeps blind judging blind.
384 pub sessions: bool,
385 /// Per-node timeouts, seconds.
386 pub timeout_implement: u64,
387 /// Per-node timeouts, seconds.
388 pub timeout_judge: u64,
389 /// Per-node timeouts, seconds.
390 pub timeout_review: u64,
391 /// Timeout for `verify.e2e` and `verify.gate`, seconds. Separate from
392 /// [`Self::timeout_review`] so shrinking a reviewer's budget cannot
393 /// silently shrink a real-machine command's budget too — the two used to
394 /// share `timeout_review`, and turning a slow reviewer down cut the
395 /// timeout `cargo test --all-targets` runs under along with it. When
396 /// omitted, preserves legacy configurations by using
397 /// [`Self::timeout_review`]. Set an explicit value to make verification
398 /// independent of later review-seat budget changes.
399 pub timeout_verify: Option<u64>,
400 /// Per-node timeouts, seconds.
401 pub timeout_fix: u64,
402 /// Wall-clock limit for one turn of [`crate::talk`]'s standing
403 /// conversation, seconds.
404 ///
405 /// An hour: the operator is not watching this turn resolve in real time,
406 /// so the budget can match what the work - reading files, running
407 /// commands, checking their output - actually needs rather than what a
408 /// person waiting on a phone can tolerate.
409 pub timeout_talk: u64,
410 /// Retries for an agent invocation that fails or returns nothing usable.
411 pub retries: usize,
412 /// Root for candidate / judge worktrees. Defaults to `~/wt/magi`.
413 pub worktree_root: Option<PathBuf>,
414 /// After the pull request is open, keep going: watch its checks and
415 /// reviews, run a fix round when they are unhappy, and ask to merge.
416 ///
417 /// On, because stopping at an open pull request left the operator doing
418 /// the watching by hand - six times in the session this was built in - and
419 /// that is the work the loop exists to take. It only engages for
420 /// `merge = "pr"`; every other merge mode ends the run as before.
421 ///
422 /// Turning this on does **not** hand magi the merge button:
423 /// [`Graph::land_approval`] is on too, and nothing merges without an
424 /// explicit answer. Setting both to their non-defaults is the only way to
425 /// get an unattended merge, and it has to be chosen twice.
426 pub land: bool,
427 /// Land rounds - watch, fix, push - before the run is left for a human.
428 pub land_rounds: usize,
429 /// When `land` sees a required check fail on the head it is bound to, rerun
430 /// that check's workflow run once (`gh run rerun <id> --failed`) before
431 /// spending a fix round on it. A run id is rerun at most once, recorded
432 /// before the call, and forgotten when the head moves; the rerun costs no
433 /// fix round and no attempt. A failure with no workflow run (an external
434 /// status) goes straight to the fixer. On; off sends every red check to
435 /// the fixer at once.
436 pub rerun_flaky_checks: bool,
437 /// Ask the owner before merging, showing what is about to land.
438 ///
439 /// On, and it is what makes `land` safe to have on: the question carries a
440 /// rendered panel - the diffstat, the patch, the checks, the review
441 /// comments that were addressed, and the subject the squash will use - so
442 /// the decision is made on evidence rather than on trust, from wherever
443 /// the operator happens to be.
444 ///
445 /// Silence is a hold. An unanswered approval never merges, and neither
446 /// does any answer other than the word `merge`.
447 pub land_approval: bool,
448 /// Ask the owner before merging a run whose review loop handed off over a
449 /// contested finding: the last round ended with a Major-or-above finding
450 /// still open *and* at least one reviewer's final vote (after
451 /// reconsideration) was reject. Findings raised in the last round are
452 /// never fixed or re-reviewed, so this is the one case an unattended
453 /// merge would land over a reviewer's explicit objection.
454 ///
455 /// On. Interaction with [`Self::land_approval`]: when that is on, every
456 /// merge is asked about and this key changes nothing. When it is off,
457 /// this key alone decides whether a contested hand-off is asked about
458 /// (the question says why); every other run still merges unattended.
459 /// Read at land time, so turning it off restores the unattended merge at
460 /// once. The pull request is opened either way; only the merge waits.
461 pub hold_contested_merge: bool,
462 /// After a run's pull request merges, file the findings its last review
463 /// round left open as follow-up tasks (`crate::followup`) instead of
464 /// letting them vanish with the merge: every Major-or-above finding, and
465 /// every finding of a seat whose final vote was reject. Other Minor/Nit
466 /// findings are only listed in the pull-request comment. Does not affect
467 /// whether the merge happens. On; best-effort, a failure is a run event.
468 pub file_followups: bool,
469 /// After a run's pull request merges, release the follow-up tasks the
470 /// merge approval's deputy filed held for that pull request
471 /// (`crate::followup::settle_deputy_tasks`): only a task the deputy filed
472 /// for this run whose hold reason names this pull request, exactly once,
473 /// and never one that duplicates an automatic follow-up (that one is left
474 /// held with the reason). The generation cap applies. Independent of
475 /// `file_followups`. On; off leaves them held until `magi task release`.
476 pub release_deputy_followups: bool,
477 /// How long to wait for an owner to answer a question before the run is
478 /// abandoned, seconds. A parked run costs nothing, so this is generous;
479 /// it exists so a forgotten question cannot pin a worktree forever.
480 pub answer_timeout: u64,
481 /// What a round does when one or more reviewer seats never answered
482 /// (timeout, crash, unparsable output).
483 pub incomplete_review: IncompleteReviewPolicy,
484 /// Run `verify.e2e` on every round, even one that already has blocking
485 /// findings and another round left to try.
486 ///
487 /// Off by default: a round with a blocking finding and rounds still left
488 /// is going back to the fixer regardless of what `verify.e2e` says, so
489 /// running it first only spends the round's slowest step (minutes, on a
490 /// Rust repo's `cargo test --all-targets`) on a head about to be
491 /// rewritten anyway. `verify.e2e` still runs once a round has no
492 /// blocking findings left (a round cannot go `clean` without it) and the
493 /// final `verify.gate` always runs on the actual tree that would land —
494 /// deferring is about *when* e2e runs mid-loop, never about skipping it.
495 ///
496 /// Set this to restore the old every-round diagnostic behaviour: e2e
497 /// output from a round that still has blocking findings is occasionally
498 /// useful on its own (a runtime failure a reviewer's panel would not
499 /// have caught by reading), and this is the way back to seeing it every
500 /// round instead of only once the panel has nothing left to flag.
501 pub e2e_every_round: bool,
502 /// Run the design-deliberation stage before `implement`: independent
503 /// advisor seats each sketch a design, and (when at least one produced a
504 /// usable proposal) a synthesis blends them into a brief carried in the
505 /// implementer's prompt. See `graph::Runner::advise`.
506 ///
507 /// On by default. A design sketch is a few paragraphs an agent can write
508 /// without touching the repository, where a full implementation is a
509 /// tool loop that re-reads the codebase on every turn - so three
510 /// sketches, gathered once before `implement` starts, cost a fraction of
511 /// a fourth candidate and buy back a form of the same disagreement
512 /// [`Self::implementers`]'s doc describes moving away from being the
513 /// default, on every run rather than only the ones an operator remembers
514 /// to ask for with `--implementers`.
515 pub advise: bool,
516 /// How many independent design proposals the deliberation stage gathers.
517 /// **Three by default** - the same number [`Self::implementers`]'s doc
518 /// names as the point where a fourth judge's first choice stopped
519 /// changing the tally.
520 pub advisors: usize,
521 /// After the tally picks a winner and before the review loop, a fixer
522 /// round ports the strengths the judges explicitly attributed to the
523 /// losing candidates onto the winner (`graph::Runner::graft`). Skipped
524 /// for a single candidate, a run with no winner or no quorum, and when
525 /// no judge recorded a strength for a loser. Best-effort: a failure, a
526 /// quota hit, no change or a diff over the size limit restores the
527 /// winner's pre-graft commit and the run carries on as if this were off.
528 /// On by default.
529 pub graft_runner_up: bool,
530}
531
532impl Default for Graph {
533 fn default() -> Self {
534 Self {
535 github_text_guard: true,
536 implementers: 1,
537 judges: 3,
538 deliberate_rounds: 1,
539 reviewers: 3,
540 review_rounds: 6,
541 gate_fix_rounds: 1,
542 max_parallel: 4,
543 language: "en".to_owned(),
544 sessions: true,
545 timeout_implement: 3600,
546 timeout_judge: 1200,
547 timeout_review: 1200,
548 timeout_verify: None,
549 timeout_fix: 1800,
550 timeout_talk: 3600,
551 retries: 1,
552 worktree_root: None,
553 land: true,
554 land_rounds: 4,
555 rerun_flaky_checks: true,
556 land_approval: true,
557 hold_contested_merge: true,
558 file_followups: true,
559 release_deputy_followups: true,
560 answer_timeout: 86_400,
561 incomplete_review: IncompleteReviewPolicy::Block,
562 e2e_every_round: false,
563 advise: true,
564 advisors: 3,
565 graft_runner_up: true,
566 }
567 }
568}
569
570impl Graph {
571 /// Effective machine-command budget. Older configuration files had only
572 /// `timeout_review`, which also governed verification, so absence is a
573 /// compatibility fallback rather than a new 1200-second default.
574 pub fn verify_timeout(&self) -> u64 {
575 self.timeout_verify.unwrap_or(self.timeout_review)
576 }
577}
578
579/// What a review round does when a reviewer seat never answered.
580///
581/// A round where half the panel timed out is not evidence of a clean patch —
582/// it is evidence of nothing. The default refuses to call that clean; `warn`
583/// exists for an operator who would rather keep a flaky seat from stalling
584/// every run, and accepts that the gap is on them to read in the report.
585#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
586#[serde(rename_all = "lowercase")]
587pub enum IncompleteReviewPolicy {
588 /// A round with a missing seat is never `clean`: with nothing raised to
589 /// fix, the round is re-reviewed instead of gating; with the max rounds
590 /// exhausted, the run is left `Blocked` rather than declared ready.
591 Block,
592 /// A round with a missing seat can still gate as clean, once every seat
593 /// that *did* answer raised nothing blocking and verification is green.
594 /// The record keeps the gap visible (`magi show`, `magi stats`) even
595 /// though the run does not wait on it.
596 Warn,
597}
598
599/// What to do when vendor-identifying text is found in material shown to judges.
600#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
601#[serde(rename_all = "lowercase")]
602pub enum LeakPolicy {
603 /// Record the leak, show the patch unmodified.
604 Warn,
605 /// Replace the token with `[REDACTED]` in the presented patch.
606 Redact,
607 /// Abort the run.
608 Fail,
609}
610
611/// Blindness policy.
612///
613/// Commit messages and candidate summaries are *always* stripped of
614/// attribution trailers and redacted — that is where signatures actually
615/// appear. [`Blind::on_leak`] governs the patch body only, where blanket
616/// redaction would corrupt the artifact under judgement.
617#[derive(Debug, Clone, Deserialize, Serialize)]
618#[serde(deny_unknown_fields, default)]
619pub struct Blind {
620 /// Install a per-worktree `commit-msg` hook that deletes attribution
621 /// trailers before they can land in a candidate's history.
622 pub commit_msg_hook: bool,
623 /// Literal, case-insensitive substrings. A line containing any of them is
624 /// dropped from commit messages and summaries; the `commit-msg` hook is
625 /// generated from the same list.
626 pub strip_lines: Vec<String>,
627 /// Case-insensitive substrings that identify a vendor or model.
628 pub vendor_tokens: Vec<String>,
629 /// Policy for vendor tokens found in the patch body.
630 pub on_leak: LeakPolicy,
631 /// Seed for label assignment and per-judge presentation order. Derived from
632 /// the run id when unset; set it to make a run reproducible.
633 pub seed: Option<u64>,
634}
635
636impl Default for Blind {
637 fn default() -> Self {
638 Self {
639 commit_msg_hook: true,
640 strip_lines: [
641 "Co-Authored-By:",
642 "Signed-off-by:",
643 "Assisted-by:",
644 "Generated-by:",
645 "Generated with",
646 "\u{1f916}",
647 ]
648 .iter()
649 .map(|s| (*s).to_owned())
650 .collect(),
651 vendor_tokens: [
652 "claude",
653 "anthropic",
654 "codex",
655 "openai",
656 "chatgpt",
657 "gemini",
658 "grok",
659 "xai",
660 "copilot",
661 "opencode",
662 "qoder",
663 "cursor",
664 "\u{1f916}",
665 ]
666 .iter()
667 .map(|s| (*s).to_owned())
668 .collect(),
669 on_leak: LeakPolicy::Warn,
670 seed: None,
671 }
672 }
673}
674
675/// Shell commands that gate the winner.
676#[derive(Debug, Clone, Default, Deserialize, Serialize)]
677#[serde(deny_unknown_fields, default)]
678pub struct Verify {
679 /// Run in the winner's worktree once per review round. Its output is fed
680 /// back to the fixer. This is the "real machine" leg of the review.
681 pub e2e: Vec<String>,
682 /// Final gate. Must all exit 0 before a merge is attempted.
683 pub gate: Vec<String>,
684 /// Mechanical fixers (formatters) run in the winner's worktree just before
685 /// `gate`, after review is clean. Anything they change is committed as one
686 /// neutral-identity commit so the gate and the PR see it. A command that
687 /// fails or times out is a warning, never a failed run: the gate stays the
688 /// single arbiter. Empty (the default) turns the feature off. Runs under
689 /// `graph.verify_timeout()` per command, like the gate. Meant for light
690 /// tools: it is not scanned for `CARGO_TARGET_DIR`, and it should be
691 /// idempotent since a resumed run may repeat it.
692 #[serde(default)]
693 pub pre_gate: Vec<String>,
694 /// Shell used to run the commands above. Defaults to `sh -c`, or
695 /// `cmd /C` when `sh` is not on `PATH`.
696 pub shell: Option<Vec<String>>,
697}
698
699impl Verify {
700 /// The `CARGO_TARGET_DIR=` value of the first rendered command that sets
701 /// one, if any. See [`crate::disk::extract_cargo_target_dir`] for the shape
702 /// this reads back. One rendering is enough - they all set the same
703 /// rendered `{{ vars.cache }}` path via the same shell - and the first e2e
704 /// command is checked before the gate because the e2e rebuilds the crate.
705 pub fn cache_dir(&self) -> Option<PathBuf> {
706 self.e2e
707 .iter()
708 .chain(self.gate.iter())
709 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
710 }
711
712 /// Every `--manifest-path` the e2e and gate commands pass to cargo, for the
713 /// shared cache's freshness check in repositories with no root manifest.
714 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
715 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
716 crate::cache::extract_manifest_paths(&all)
717 }
718}
719
720/// Per-repository worktree preparation, run right after magi creates a worktree.
721#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
722#[serde(deny_unknown_fields, default)]
723pub struct Worktree {
724 /// Ordered steps. Declare in one layer only. Empty (the default) changes
725 /// nothing. See [`crate::worktree_setup`].
726 pub setup: Vec<SetupStep>,
727}
728
729/// One setup step: exactly one of `copy` / `run`.
730#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
731#[serde(deny_unknown_fields, default)]
732pub struct SetupStep {
733 /// `"src -> dst"` (or just `"path"`): copy from the primary checkout (an
734 /// absolute source is allowed) into the worktree. Never overwrites.
735 pub copy: Option<String>,
736 /// With `copy`: a missing source is skipped instead of an error.
737 pub optional: bool,
738 /// Shell command, run with the worktree as cwd.
739 pub run: Option<String>,
740 /// With `run`: seconds before the command is killed. Defaults to
741 /// `graph.verify_timeout()`.
742 pub timeout_secs: Option<u64>,
743}
744
745impl Worktree {
746 /// Refuse a malformed step at load time rather than in the middle of a run.
747 pub fn validate(&self) -> Result<()> {
748 for (i, step) in self.setup.iter().enumerate() {
749 let n = i + 1;
750 match (&step.copy, &step.run) {
751 (Some(c), None) => {
752 if step.timeout_secs.is_some() {
753 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
754 }
755 crate::worktree_setup::validate_copy(c)
756 .with_context(|| format!("[worktree] setup step {n}"))?;
757 }
758 (None, Some(r)) => {
759 if r.trim().is_empty() {
760 bail!("[worktree] setup step {n}: `run` is empty");
761 }
762 if step.optional {
763 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
764 }
765 }
766 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
767 }
768 }
769 Ok(())
770 }
771}
772
773/// Disk hygiene: how hard magi is allowed to press on the machine's free space.
774///
775/// The numbers below come from one incident, not from theory: a machine with
776/// 951.8 GB free ran a few competitions and plans and best read 6.7 GB free.
777/// Three multi-gigabyte classes of junk accumulated side by side - per-run
778/// worktrees that end as `Merged`/`Ready`/`Failed`, a shared build cache whose
779/// each verify round and each implementation wave recompiles the derived
780/// section of the project into, and the outputs of runs that were removed but
781/// whose folders nobody deleted.
782#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
783#[serde(deny_unknown_fields, default)]
784pub struct Disk {
785 /// Free space, in bytes, below which no new run may start: the daemon and
786 /// the `magi run` gate answer with "the disk is full" instead of letting
787 /// the graph fill it the rest of the way. `0` turns the gate off.
788 ///
789 /// Default 8 GiB. The incident ran down to 6.7 GB free of 951.8 GB total
790 /// before anybody noticed; 8 GiB is enough headroom for the compile a fresh
791 /// competition triggers and small enough that a 1 TB disk with 100 GB free
792 /// is nowhere near the threshold.
793 pub min_free_bytes: u64,
794 /// Fold finished runs without being asked. `Merged`, `Ready` and `Failed`
795 /// runs older than [`fold_grace_secs`](Self::fold_grace_secs) have their
796 /// worktrees removed. `0` turns the janitor off.
797 ///
798 /// Default true.
799 pub auto_fold: bool,
800 /// How old a finished run must be before the janitor folds it, seconds.
801 ///
802 /// Default 6 hours. A run that `Ready` at 8am is the operator's answer; a
803 /// run that `Ready` a week ago is worktrees holding a compile each. Six
804 /// hours is long enough that nobody loses an answer in the gap between
805 /// reading the report and starting from it, and short enough that a backlog
806 /// cannot pile up across two nights.
807 pub fold_grace_secs: u64,
808 /// Ceiling for the shared build cache (`CARGO_TARGET_DIR` in the rendered
809 /// verify commands), in bytes. When the janitor runs and the cache is over
810 /// it, files are dropped oldest-first until it is not. `0` turns pruning
811 /// off - the cache then only ever grows, which is the operator's call.
812 ///
813 /// Default 10 GiB. This is what the incident measured: 30.61 GB sat in the
814 /// shared cache on top of ~16 GB in the primary target directory and 6.7-
815 /// 11.15 GB in each of four per-worktree targets. 10 GiB holds a healthy
816 /// stack of prebuilt dependencies (cargo's per-file fingerprinting means
817 /// pruning only costs the rebuild of the dropped files, not of the world)
818 /// without letting one addled cache swallow the machine.
819 pub cache_limit_bytes: u64,
820}
821
822impl Default for Disk {
823 fn default() -> Self {
824 Self {
825 min_free_bytes: 8 * 1024 * 1024 * 1024,
826 auto_fold: true,
827 fold_grace_secs: 6 * 60 * 60,
828 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
829 }
830 }
831}
832
833/// What to do with the winning branch.
834#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
835#[serde(rename_all = "lowercase")]
836pub enum MergeMode {
837 /// Leave the branch alone and print the merge command matching
838 /// [`Merge::style`].
839 None,
840 /// Merge into the base branch in the primary worktree, using
841 /// [`Merge::style`].
842 Local,
843 /// Push the branch and open a PR with `gh pr create`. Landing this PR
844 /// (`[graph] land`) always squashes — see `land`'s module doc — so
845 /// [`Merge::style`] does not apply here.
846 Pr,
847}
848
849/// How the winning branch is attached to the base branch: what
850/// `mode = "local"` runs, and what `mode = "none"`'s printed guidance tells
851/// the operator to run by hand.
852///
853/// Read from configuration rather than asked of the repository at run time
854/// (e.g. `gh api repos/{owner}/{repo}/rulesets`) for two reasons: it keeps
855/// `mode = "none"`'s guidance a pure function of `RunState`, assertable in a
856/// unit test the same way `land::decide` is kept pure (see that module's
857/// doc), and it works for a base branch that is not hosted on GitHub, or not
858/// reachable at all, at the moment the report is rendered. An operator whose
859/// base branch enforces a ruleset already knows what it allows; declaring it
860/// once here is cheaper than magi re-discovering it, with a network call, on
861/// every render.
862#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
863#[serde(rename_all = "lowercase")]
864pub enum MergeStyle {
865 /// `git merge --no-ff`: every candidate commit lands, plus a merge
866 /// commit that records the merge as its own event in history. Rejected
867 /// by a base branch whose ruleset requires linear history or forbids
868 /// merge commits outright.
869 #[default]
870 Merge,
871 /// `git merge --squash` followed by a commit under an explicit message:
872 /// every candidate commit folds into one, and none of the candidate's
873 /// own placeholder subjects (`magi: candidate A (uncommitted work)`)
874 /// reach the base branch. No merge commit, so this satisfies a linear-
875 /// history ruleset.
876 Squash,
877 /// A fast-forward-only merge: every candidate commit lands verbatim, in
878 /// order, with no merge commit. Only succeeds because the winner was
879 /// already rebased onto the tracked base tip before this runs (see
880 /// `Runner::sync_to_base`) — equivalent to GitHub's "rebase and merge"
881 /// once that has happened.
882 Rebase,
883}
884
885/// Merge policy.
886#[derive(Debug, Clone, Deserialize, Serialize)]
887#[serde(deny_unknown_fields, default)]
888pub struct Merge {
889 /// Default is [`MergeMode::None`]: magi never touches your base branch
890 /// unless you ask it to.
891 pub mode: MergeMode,
892 /// Base branch. Defaults to the branch checked out when the run started.
893 pub base: Option<String>,
894 /// How the winner is attached to `base`; see [`MergeStyle`]. Ignored by
895 /// `mode = "pr"`.
896 pub style: MergeStyle,
897 /// Remote for `mode = "pr"`.
898 pub remote: String,
899 /// After a `mode = "pr"` run lands, open a `chore/release-vX.Y.Z` pull
900 /// request sized to the change by an agent's own judgement, so a version
901 /// bump does not depend on a human remembering to cut one.
902 ///
903 /// Only acts on Rust repositories (a `Cargo.toml` at the root of the base
904 /// branch); on any other repository it is a no-op that records one event.
905 ///
906 /// On by default. **Turning this off means a merge landed from the phone
907 /// never becomes a release**, so `POST /api/upgrade` keeps reporting
908 /// "already on the newest release" against a `main` that has moved past
909 /// it - the same gap this feature exists to close. Only for a repository
910 /// that wants to keep cutting releases by hand.
911 pub release_bump: bool,
912}
913
914impl Default for Merge {
915 fn default() -> Self {
916 Self {
917 mode: MergeMode::None,
918 base: None,
919 style: MergeStyle::default(),
920 remote: "origin".to_owned(),
921 release_bump: true,
922 }
923 }
924}
925
926/// How magi keeps itself current.
927#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
928#[serde(rename_all = "lowercase")]
929pub enum UpdateMode {
930 /// Never check.
931 Off,
932 /// Check in the background and print a one-line banner when a newer
933 /// release exists.
934 Notify,
935 /// Check and install silently.
936 Install,
937}
938
939/// Self-update policy.
940#[derive(Debug, Clone, Deserialize, Serialize)]
941#[serde(deny_unknown_fields, default)]
942pub struct Update {
943 /// Default is [`UpdateMode::Notify`]: magi tells you, and lets you decide.
944 pub mode: UpdateMode,
945 /// Minimum time between checks, e.g. `24h`. kaishin's default when unset.
946 pub interval: Option<String>,
947}
948
949impl Default for Update {
950 fn default() -> Self {
951 Self {
952 mode: UpdateMode::Notify,
953 interval: None,
954 }
955 }
956}
957
958/// Who performs the release after a `chore/release-vX.Y.Z` pull request merges.
959#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
960#[serde(rename_all = "lowercase")]
961pub enum ReleaseMode {
962 /// The repository's own workflows do (`auto-tag.yml` then `release.yml`),
963 /// and the release pull request merges on its checks.
964 #[default]
965 Actions,
966 /// magi does, from this machine: no CI is awaited, the owner approves the
967 /// merge, and magi then tags and runs [`Release::commands`]. See
968 /// [`crate::release_local`].
969 Local,
970}
971
972/// `[release]`: releasing without GitHub Actions. Opt-in per repository.
973#[derive(Debug, Clone, Deserialize, Serialize)]
974#[serde(deny_unknown_fields, default)]
975pub struct Release {
976 /// [`ReleaseMode::Actions`] (default: nothing changes) or
977 /// [`ReleaseMode::Local`].
978 pub mode: ReleaseMode,
979 /// Shell commands run in order, from a clean checkout of the merge commit,
980 /// once the tag is pushed. The first failure stops the list. They see
981 /// `MAGI_RELEASE_VERSION`, `MAGI_RELEASE_TAG`, `MAGI_RELEASE_COMMIT` and
982 /// `MAGI_RELEASE_PR` in the environment; `{{ ... }}` cannot carry the
983 /// version because teravars renders the whole file before any release
984 /// exists. Only read when `mode = "local"`.
985 pub commands: Vec<String>,
986 /// Minutes each command may run before it is killed and counted as failed.
987 pub timeout_minutes: u64,
988}
989
990impl Default for Release {
991 fn default() -> Self {
992 Self {
993 mode: ReleaseMode::Actions,
994 commands: Vec::new(),
995 timeout_minutes: 30,
996 }
997 }
998}
999
1000impl Release {
1001 /// Is this repository released by magi rather than by its workflows?
1002 pub fn is_local(&self) -> bool {
1003 self.mode == ReleaseMode::Local
1004 }
1005}
1006
1007/// Top-level configuration.
1008#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1009#[serde(deny_unknown_fields, default)]
1010pub struct Config {
1011 /// Agent roster.
1012 pub agents: Vec<AgentSpec>,
1013 /// Role assignment.
1014 pub roles: Roles,
1015 /// Graph shape.
1016 pub graph: Graph,
1017 /// Blindness policy.
1018 pub blind: Blind,
1019 /// Verification commands.
1020 pub verify: Verify,
1021 /// Worktree preparation.
1022 pub worktree: Worktree,
1023 /// Disk hygiene.
1024 pub disk: Disk,
1025 /// Merge policy.
1026 pub merge: Merge,
1027 /// Self-update policy.
1028 pub update: Update,
1029 /// Project-specific text appended to the node prompts.
1030 pub prompts: Prompts,
1031 /// How the operator is told a run is waiting on them.
1032 pub notify: Notify,
1033 /// Local repositories the plan surface can start or derive a conversation
1034 /// against.
1035 pub repos: Repos,
1036 /// Policy for the standing conversation ([`crate::talk`]).
1037 pub talk: Talk,
1038 /// How many runs `magi serve`'s own loop drives at once.
1039 pub daemon: Daemon,
1040 /// Who tags and publishes after a release pull request merges.
1041 pub release: Release,
1042 /// Context-window sizes in tokens, keyed by model name, merged over
1043 /// [`BUILTIN_CONTEXT_WINDOWS`]. See [`Config::context_window`].
1044 pub context_windows: BTreeMap<String, u64>,
1045}
1046
1047/// Context windows of models magi commonly drives, in tokens.
1048///
1049/// A convenience, not a source of truth: vendors resize windows and ship new
1050/// models faster than this table is edited, so an entry that is stale or
1051/// missing is fixed by `[context_windows]` in `magi.toml`, which wins. Matched
1052/// by [`Config::context_window`]: exact name first, then the longest key that
1053/// prefixes the model name (so a dated or suffixed id such as
1054/// `claude-sonnet-4-5-20250929` finds `claude-sonnet-4-5`). A model matching
1055/// nothing has no percentage - the UI shows the raw count.
1056const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1057 ("claude-opus-4", 200_000),
1058 ("claude-sonnet-4", 200_000),
1059 ("claude-haiku-4", 200_000),
1060 ("claude-3", 200_000),
1061 ("opus", 200_000),
1062 ("sonnet", 200_000),
1063 ("haiku", 200_000),
1064 ("gpt-5", 400_000),
1065 ("gpt-4.1", 1_000_000),
1066 ("gpt-4o", 128_000),
1067 ("o3", 200_000),
1068 ("o4-mini", 200_000),
1069 ("gemini-2.5", 1_000_000),
1070 ("deepseek", 128_000),
1071];
1072
1073impl Config {
1074 /// Context window in tokens for `model`: `[context_windows]` first, then
1075 /// the built-in table; within each, an exact name beats the longest
1076 /// prefix. `None` for an unknown model, which is a deliberate answer -
1077 /// guessing a denominator would print a confident wrong percentage.
1078 pub fn context_window(&self, model: &str) -> Option<u64> {
1079 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1080 let mut best: Option<(usize, u64)> = None;
1081 for (key, window) in entries {
1082 if key == model {
1083 return Some(window);
1084 }
1085 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1086 best = Some((key.len(), window));
1087 }
1088 }
1089 best.map(|(_, w)| w)
1090 }
1091 lookup(
1092 model,
1093 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1094 )
1095 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1096 }
1097}
1098
1099/// How the daemon loop itself behaves, as opposed to what one run does.
1100///
1101/// Machine-layer material in the same sense [`Repos::roots`] is: how many
1102/// competitions this machine's own loop is willing to babysit at once is a
1103/// fact about the machine running `magi serve`, not about any one
1104/// repository's task, so it belongs in `<config_dir>/magi/config.toml`
1105/// rather than a repository's own `magi.toml` - though, like `Repos::roots`,
1106/// nothing stops a repository from setting it too, since a scalar field
1107/// takes whichever layer has the highest precedence.
1108#[derive(Debug, Clone, Deserialize, Serialize)]
1109#[serde(deny_unknown_fields, default)]
1110pub struct Daemon {
1111 /// How many runs `magi serve` may have actively in flight at once.
1112 /// **One by default** - today's behaviour, one run at a time.
1113 ///
1114 /// This is a different knob from [`Graph::max_parallel`], and the two
1115 /// must not be confused: `max_parallel` bounds how many agent *processes*
1116 /// one run starts inside itself (implementers, judges, reviewers -
1117 /// candidates competing on a single task); this field bounds how many
1118 /// *runs* - whole competitions, each with its own `max_parallel` budget -
1119 /// the loop drives side by side, possibly across different tasks and
1120 /// different repositories. Raising `max_parallel` buys a bigger panel for
1121 /// one task; raising this buys more tasks worked at once. A config file
1122 /// that meant one and wrote the other would either starve a competition
1123 /// of judges or leave the rest of the backlog waiting for no reason.
1124 ///
1125 /// A run parked waiting on the operator's land-merge approval - see
1126 /// [`crate::land`] - does not hold one of these slots while it waits: the
1127 /// whole point of parking there is to let the loop spend the slot on
1128 /// something runnable instead of sitting on a decision only a human can
1129 /// make. So even at the default of `1`, an approval that comes back does
1130 /// not queue behind whatever else the loop happens to be running.
1131 pub max_concurrent_runs: usize,
1132 /// Let a task marked [`crate::queue::Task::interrupt`] (`magi task
1133 /// interrupt`) cut ahead of whatever `magi serve` already has in flight,
1134 /// instead of waiting for it to finish.
1135 ///
1136 /// **Off by default.** When enabled, a run that is in flight and is not
1137 /// itself the interrupt candidate may be paused at its next safe node
1138 /// boundary - see [`crate::graph::Runner::park_here`] - so the marked
1139 /// task can run alone; the paused run resumes automatically, through the
1140 /// same path any other parked run does, the moment the interrupting
1141 /// task's own run reaches a terminal status. This is opt-in because it
1142 /// bends the loop's own "one run at a time" principle (see this repository's
1143 /// `magi serve` help) for a specific, explicit operator request, and a
1144 /// repository that never files an interrupt task pays nothing for having
1145 /// it on - but an operator who does not want any run of theirs preempted,
1146 /// ever, should leave this `false`.
1147 pub pause_for_interrupts: bool,
1148 /// How many deputies `magi serve` runs at once. A deputy is the short-lived
1149 /// seat that waits on one open conductor question (see [`crate::deputy`]);
1150 /// each is a live agent conversation, so this is bounded - **two by
1151 /// default**, because the agent CLIs' quota is the scarce resource. A
1152 /// question over the limit keeps its place and starts when a deputy
1153 /// finishes; `0` runs none.
1154 pub max_deputies: usize,
1155 /// Minutes a release-bump pull request may make no progress before
1156 /// `magi serve` raises a notice and asks the owner (see
1157 /// [`crate::release_watch`]). Progress is a change of head commit or of any
1158 /// check's verdict. A required check that stays red after the one rerun the
1159 /// watcher is allowed escalates at once, whatever this says. **Sixty by
1160 /// default**; `0` turns the watcher off.
1161 pub release_stall_minutes: u64,
1162}
1163
1164impl Default for Daemon {
1165 fn default() -> Self {
1166 Self {
1167 max_concurrent_runs: 1,
1168 pause_for_interrupts: false,
1169 max_deputies: 2,
1170 release_stall_minutes: 60,
1171 }
1172 }
1173}
1174
1175/// Where `magi repos` and `GET /api/repos` look for local checkouts.
1176///
1177/// `roots` is one of the array keys [`array_merge_policy`] marks as
1178/// append-across-layers: which checkouts exist in general is a *machine*
1179/// fact in the same way the agent roster is - a repository's own `magi.toml`
1180/// cannot state where its siblings live before magi has resolved which
1181/// repository to read that file from in the first place - but a repository
1182/// that genuinely has an extra root worth scanning is not forced to choose
1183/// between an error and losing the machine's roots outright. Both layers'
1184/// roots are scanned; see [`Config::refuse_split_arrays`] for the keys that
1185/// are still refused.
1186#[derive(Debug, Clone, Deserialize, Serialize)]
1187#[serde(deny_unknown_fields, default)]
1188pub struct Repos {
1189 /// Roots to scan for a ghq-layout checkout: `<root>/<host>/<owner>/<repo>`
1190 /// with a `.git` directory. Empty by default - nothing is scanned unless
1191 /// asked to be.
1192 pub roots: Vec<PathBuf>,
1193 /// How long a scan is trusted before the next request re-scans it,
1194 /// seconds. `0` means never trust it: scan on every request. Defaults to
1195 /// a day, the same order of magnitude as [`Graph::answer_timeout`] for
1196 /// the same reason - a checkout does not usually appear or vanish inside
1197 /// a session, so there is little to gain from scanning more often than
1198 /// that, and an explicit refresh exists for the moment one does.
1199 pub scan_ttl: u64,
1200 /// How often `magi serve` runs `git fetch origin` in every checkout under
1201 /// `roots`, seconds, so `origin/main` stays fresh whatever state the
1202 /// working tree is in. Fetch only: no branch, HEAD or working tree is
1203 /// touched. `0` disables it.
1204 pub fetch_interval: u64,
1205}
1206
1207impl Default for Repos {
1208 fn default() -> Self {
1209 Self {
1210 roots: Vec::new(),
1211 scan_ttl: 86_400,
1212 fetch_interval: 600,
1213 }
1214 }
1215}
1216
1217/// Project-specific text appended to each node's prompt.
1218///
1219/// **Additive by construction.** These fields cannot replace magi's prompts,
1220/// only extend them, and that restriction is the whole design. The built-in
1221/// prompts carry the invariants the competition rests on: a judging prompt
1222/// names no authors, every structured answer must arrive as one fenced `json`
1223/// block, and a judge is told not to speculate about who wrote what. A config
1224/// that could overwrite them would let a typo silently un-blind the panel or
1225/// break the parser, and the symptom would be "the judges got worse" rather
1226/// than an error.
1227///
1228/// Repository-wide context belongs in `AGENTS.md`, which every agent already
1229/// reads from the checkout. Use these fields for the things a *magi node*
1230/// needs to know and a repository file cannot say - for instance that
1231/// reviewers here should ignore formatting because a hook owns it.
1232#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1233#[serde(deny_unknown_fields, default)]
1234pub struct Prompts {
1235 /// Appended to every node's prompt.
1236 pub all: String,
1237 /// Appended for implementers.
1238 pub implement: String,
1239 /// Appended for judges, both ranking and voting.
1240 pub judge: String,
1241 /// Appended for reviewers.
1242 pub review: String,
1243 /// Appended for the fixer.
1244 pub fix: String,
1245}
1246
1247impl Prompts {
1248 /// The overlay for one node, or `None` when nothing is configured.
1249 ///
1250 /// `node` is the graph's own node name, so a new node gets no overlay
1251 /// rather than the wrong one.
1252 pub fn overlay(&self, node: &str) -> Option<String> {
1253 let specific = match node {
1254 "implement" => &self.implement,
1255 "judge" | "vote" | "deliberate" => &self.judge,
1256 "review" => &self.review,
1257 "fix" => &self.fix,
1258 _ => "",
1259 };
1260 let mut parts: Vec<&str> = Vec::new();
1261 for p in [self.all.trim(), specific.trim()] {
1262 if !p.is_empty() {
1263 parts.push(p);
1264 }
1265 }
1266 if parts.is_empty() {
1267 return None;
1268 }
1269 Some(parts.join("\n\n"))
1270 }
1271}
1272
1273/// How the operator is told that a run is waiting on them.
1274///
1275/// A command rather than a built-in integration: magi is one binary with no
1276/// network dependencies, and every operator's notification path is different -
1277/// ntfy, a Slack webhook, a Windows toast, an SSH to a machine that beeps.
1278/// Shelling out keeps all of them possible and none of them magi's problem.
1279#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1280#[serde(deny_unknown_fields, default)]
1281pub struct Notify {
1282 /// Command and arguments. `{summary}`, `{run}` and `{url}` are replaced.
1283 /// Empty means no notification - the web UI is then the only surface.
1284 pub command: Vec<String>,
1285}
1286
1287/// Policy for [`crate::talk`], the standing conversation.
1288#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1289#[serde(deny_unknown_fields, default)]
1290pub struct Talk {
1291 /// Let the conversation's agent edit files in the repository instead of
1292 /// filing a task for one. **Off by default** - see
1293 /// [`crate::talk`]'s module doc for why an edit made mid-conversation is
1294 /// an edit no run and no review can be attributed to, which is exactly
1295 /// the property a repository entered in a competition depends on. A
1296 /// repository that is never judged - dotfiles, a personal config
1297 /// checkout - has nothing to lose by turning this on in its own
1298 /// `magi.toml`, and a one-line fix stops costing a queued task to get.
1299 pub allow_write: bool,
1300 /// Extra chat personas, `[[talk.personas]]`. They add to the built-ins in
1301 /// [`crate::persona`]; an entry with a built-in's id replaces it. Like every
1302 /// array outside [`array_merge_policy`]'s append list, declaring it in two
1303 /// layers is refused.
1304 pub personas: Vec<PersonaSpec>,
1305 /// What the chat calls the operator: the persona addresses them by this
1306 /// name and the web Chat labels their turns with it instead of `YOU`.
1307 /// Blank is unset; at most [`OPERATOR_NAME_MAX`] characters, one line.
1308 pub operator_name: Option<String>,
1309}
1310
1311/// Longest accepted `[talk] operator_name`, in characters.
1312pub const OPERATOR_NAME_MAX: usize = 64;
1313
1314impl Talk {
1315 /// The trimmed operator name, `None` when unset or blank.
1316 pub fn operator_name(&self) -> Option<&str> {
1317 self.operator_name
1318 .as_deref()
1319 .map(str::trim)
1320 .filter(|n| !n.is_empty())
1321 }
1322}
1323
1324/// One `[[talk.personas]]` entry: a tone for the standing chat, nothing more.
1325#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1326#[serde(deny_unknown_fields)]
1327pub struct PersonaSpec {
1328 /// Stable id the conversation stores. Not `default`.
1329 pub id: String,
1330 /// What the selector shows. May be omitted when `id` is a built-in's: the
1331 /// built-in's name is kept.
1332 #[serde(default)]
1333 pub name: String,
1334 /// The voice instruction appended to the chat's system prompt. May be
1335 /// omitted when `id` is a built-in's.
1336 #[serde(default)]
1337 pub prompt: String,
1338 /// Optional avatar, display only: a `data:image/(png|jpeg|gif|webp);base64,`
1339 /// URI or an absolute (or `~/`) path to a raster image. See
1340 /// [`crate::persona_icon`]. Never part of the briefing.
1341 #[serde(default, skip_serializing_if = "Option::is_none")]
1342 pub icon: Option<String>,
1343}
1344
1345/// Roles resolved to concrete agent specs for one run.
1346#[derive(Debug, Clone)]
1347pub struct ResolvedRoles {
1348 /// One per candidate.
1349 pub implementers: Vec<AgentSpec>,
1350 /// One per judge.
1351 pub judges: Vec<AgentSpec>,
1352 /// One per reviewer slot.
1353 pub reviewers: Vec<AgentSpec>,
1354 /// The configured fixer chain in order, if `[roles] fixer` is set
1355 /// (resolved like [`crate::agent::pick_chain`]: unknown or uninstalled ids
1356 /// skipped, duplicates keep their first place). `None` means the winner's
1357 /// own author.
1358 pub fixer: Option<Vec<AgentSpec>>,
1359 /// Queue conductor, explicitly selected or resolved by the standalone-seat fallback.
1360 pub conductor: AgentSpec,
1361 /// The full ordered implementer roster, in [`Roles::implementers`]'s own
1362 /// order — or `[[agents]]` in file order, when that list is empty. Unlike
1363 /// [`Self::implementers`], never truncated to `graph.implementers` and
1364 /// never `rotate`d/wrapped: a solo run (`implementers = 1`) resolves
1365 /// `implementers` down to a single slot, but `graph::Runner`'s per-seat
1366 /// quota fallback needs the *whole* list to walk forward through when
1367 /// that one slot's agent runs out of quota mid-run.
1368 pub implementer_roster: Vec<AgentSpec>,
1369 /// [`Self::implementer_roster`]'s counterpart for judge seats: the whole
1370 /// `[roles] judges` list (or every agent), untruncated and unrotated, for
1371 /// the per-seat handover when a judge's agent fails.
1372 pub judge_roster: Vec<AgentSpec>,
1373 /// Likewise for reviewer seats.
1374 pub reviewer_roster: Vec<AgentSpec>,
1375}
1376
1377/// Every array-valued key in a config table, as a dotted path.
1378///
1379/// Dotted so the error names `roles.implementers` rather than `implementers`:
1380/// an operator with three config files needs to know which key, not just that
1381/// there was one. `vars` is skipped because it is teravars' own input, merged
1382/// on purpose and never deserialised into `Config`.
1383fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1384 let mut out = Vec::new();
1385 for (k, v) in table {
1386 if prefix.is_empty() && k == "vars" {
1387 continue;
1388 }
1389 let path = if prefix.is_empty() {
1390 k.clone()
1391 } else {
1392 format!("{prefix}.{k}")
1393 };
1394 match v {
1395 toml::Value::Array(_) => out.push(path),
1396 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1397 _ => {}
1398 }
1399 }
1400 out
1401}
1402
1403/// How an array key behaves when two config layers both declare it.
1404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1405enum ArrayMerge {
1406 /// Two layers may both declare it; the composed value is the
1407 /// low-to-high-priority concatenation teravars already produces (see
1408 /// [`Config::load_layers`]'s doc for why that order and no dedup).
1409 Append,
1410 /// Two layers declaring it is refused; see
1411 /// [`Config::refuse_split_arrays`].
1412 Replace,
1413}
1414
1415/// The single place that decides, for a dotted array key (as returned by
1416/// [`array_keys`]), whether declaring it in two config layers is a
1417/// concatenation the operator asked for or a silent accident.
1418///
1419/// Kept as one match so the whole policy is visible in one place - the same
1420/// reason `claude_quota` and `dropped_stream` close their own classification
1421/// in one spot elsewhere in this codebase. Anything not listed defaults to
1422/// [`ArrayMerge::Replace`]: refusing is the safe default for a key nobody has
1423/// reasoned about yet, and a new array key added later has to be added here
1424/// deliberately to become appendable.
1425///
1426/// - `verify.e2e` / `verify.gate` — a "run all of these, all must exit 0"
1427/// gate. Concatenating two of them is exactly the checks both layers
1428/// wanted, which is what lets a common gate (e.g. `editorconfig-checker`)
1429/// live in a shared layer while a repository's own layer adds its own
1430/// command, instead of every repository copying the shared command into
1431/// its own file.
1432/// - `repos.roots` — a set of directories to scan for checkouts. A
1433/// repository adding its own root on top of the machine's is additive by
1434/// nature, not a replacement of where the machine looks; see
1435/// [`Repos::roots`].
1436///
1437/// Left on the refuse side, and why:
1438/// - `roles.implementers` / `roles.judges` / `roles.reviewers` — an ordered
1439/// list of *seats*, not a set. A machine's two implementers plus a
1440/// repository's one is three seats nobody asked for and nobody is paying
1441/// for on purpose.
1442/// - `notify.command` — an argv. Concatenating two argvs does not produce a
1443/// program that runs; it produces `["ntfy", "publish", "curl", "-X"]`.
1444/// - `blind.strip_lines` — technically safe to concatenate (each entry is
1445/// matched as an independent substring, so a longer list only strips
1446/// *more*), but left on the refuse side anyway: the same list also drives
1447/// `commit_msg_hook`'s generated `sed` addresses, where position matters,
1448/// and a silent three-layer merge is exactly the kind of surprise
1449/// `refuse_split_arrays` exists to catch rather than to reason about
1450/// case-by-case. A repository that wants one more stripped phrase restates
1451/// the whole list; that restatement is visible in review, an accidental
1452/// concatenation would not be.
1453fn array_merge_policy(key: &str) -> ArrayMerge {
1454 match key {
1455 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1456 _ => ArrayMerge::Replace,
1457 }
1458}
1459
1460impl Config {
1461 /// Load one file through teravars: Tera rendering, `[vars]` resolution,
1462 /// and the `include = [...]` directive.
1463 pub fn load(path: &Path) -> Result<Self> {
1464 Self::load_layers(&[path.to_path_buf()])
1465 }
1466
1467 /// The Tera render context shared by every layer: `system.*` (from
1468 /// teravars), `env` (magi's own addition - a config that names a shared
1469 /// build-cache directory or a machine-specific path needs
1470 /// `{{ env.NAME | default(value='...') }}`), and `repo` / `repo_name`
1471 /// derived from the last (highest-priority) path's parent directory.
1472 ///
1473 /// Factored out so [`Config::array_provenance`] can re-render a single
1474 /// layer under the exact same context [`Config::load_layers`] uses for
1475 /// the joint render, rather than drifting from it by accident.
1476 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1477 let mut ctx = teravars::system_context();
1478 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1479 ctx.insert("env", &env);
1480 if let Some(last) = paths.last()
1481 && let Some(dir) = last.parent()
1482 {
1483 // A layer extracted from `<remote>/<base>` records the checkout it
1484 // stands for beside itself; its own directory is a cache path.
1485 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1486 .map(|s| PathBuf::from(s.trim()))
1487 .unwrap_or_else(|_| dir.to_path_buf());
1488 ctx.insert("repo", &dir.to_string_lossy());
1489 ctx.insert(
1490 "repo_name",
1491 &dir.file_name().unwrap_or_default().to_string_lossy(),
1492 );
1493 }
1494 ctx
1495 }
1496
1497 /// Load and deep-merge a stack of config files, later files winning.
1498 ///
1499 /// This is why the config is TOML-through-teravars rather than plain serde:
1500 /// the roster is a *machine* fact (which CLIs and plans you pay for) while
1501 /// the gate is a *repository* fact (`cargo make check` here, `pnpm test`
1502 /// there). Picking one file and ignoring the other would force every repo
1503 /// to restate the roster.
1504 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1505 let mut engine = teravars::Engine::default();
1506 let ctx = Self::render_ctx(paths);
1507 if paths.len() > 1 {
1508 Self::refuse_split_arrays(paths, &mut engine, &ctx)?;
1509 }
1510 let merged = teravars::load_merged(paths, &mut engine, &ctx).with_context(|| {
1511 format!(
1512 "rendering config via teravars: {}",
1513 paths
1514 .iter()
1515 .map(|p| p.display().to_string())
1516 .collect::<Vec<_>>()
1517 .join(", ")
1518 )
1519 })?;
1520 let mut table = merged.config;
1521 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1522 // `[vars]` is teravars' own input, already resolved into the render
1523 // context; `deny_unknown_fields` must not trip over it.
1524 table.remove("vars");
1525 // No layer says anything about `agents`: the roster is whatever is on
1526 // `PATH` now, exactly as when no layer exists at all. An explicit
1527 // `agents = []` is a statement and is kept.
1528 let detect_agents = !table.contains_key("agents");
1529 let mut cfg: Self = toml::Value::Table(table)
1530 .try_into()
1531 .context("deserializing magi config")?;
1532 crate::persona::validate(&cfg.talk.personas)?;
1533 cfg.worktree.validate()?;
1534 if let Some(name) = cfg.talk.operator_name() {
1535 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1536 bail!(
1537 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1538 );
1539 }
1540 }
1541 if detect_agents {
1542 cfg.agents = Self::autodetected().agents;
1543 }
1544 Ok(cfg)
1545 }
1546
1547 /// `graph.candidates` was renamed `graph.implementers`. Both spellings are
1548 /// read, but the layers are merged into one table before serde sees it, so
1549 /// an old name in a lower layer and the new name in a higher one would
1550 /// arrive together and fail as a duplicate field instead of letting the
1551 /// higher layer win. Resolve it here: a single layer that writes both is
1552 /// refused (naming both keys and the file); otherwise the value from the
1553 /// last layer that wrote either key becomes `implementers`.
1554 fn normalize_renamed_keys(
1555 paths: &[PathBuf],
1556 engine: &mut teravars::Engine,
1557 ctx: &teravars::Context,
1558 table: &mut toml::map::Map<String, toml::Value>,
1559 ) -> Result<()> {
1560 let both = matches!(
1561 table.get("graph"),
1562 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1563 );
1564 if !both {
1565 return Ok(());
1566 }
1567 let mut winner: Option<toml::Value> = None;
1568 for path in paths {
1569 let one = teravars::load_merged([path], engine, ctx)
1570 .with_context(|| format!("rendering {}", path.display()))?;
1571 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1572 continue;
1573 };
1574 if g.contains_key("candidates") && g.contains_key("implementers") {
1575 bail!(
1576 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1577 path.display()
1578 );
1579 }
1580 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1581 winner = Some(v.clone());
1582 }
1583 }
1584 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1585 g.remove("candidates");
1586 if let Some(v) = winner {
1587 g.insert("implementers".to_owned(), v);
1588 }
1589 }
1590 Ok(())
1591 }
1592
1593 /// Refuse an array that two layers both declare, unless
1594 /// [`array_merge_policy`] says that key is meant to accumulate.
1595 ///
1596 /// teravars **appends** arrays when it merges layers, and that is wrong for
1597 /// most arrays magi has: `implementers` is an ordered list of seats,
1598 /// `notify.command` is an argv. Concatenating two of them yields something
1599 /// nobody wrote - three implementers out of a machine's two and a
1600 /// repository's one, or an argv of `["ntfy", "publish", "curl", "-X"]`.
1601 ///
1602 /// Replacing instead would be the right merge rule for those keys, but the
1603 /// rule lives in teravars, which several other projects depend on;
1604 /// changing it there is a decision for that crate, not something to fake
1605 /// here by re-reading the files with different semantics and hoping the
1606 /// two paths agree.
1607 ///
1608 /// So magi refuses the ambiguity rather than resolving it silently, for
1609 /// every array key except the short, deliberate list
1610 /// [`array_merge_policy`] marks [`ArrayMerge::Append`] - for those, the
1611 /// concatenation teravars already produces *is* what both files say, so
1612 /// there is nothing to refuse. The cost of guessing wrong on the refused
1613 /// keys is a roster the operator did not ask for and is paying for by the
1614 /// token; the append keys carry no such risk because every element runs
1615 /// (or every directory is scanned) regardless of order.
1616 fn refuse_split_arrays(
1617 paths: &[PathBuf],
1618 engine: &mut teravars::Engine,
1619 ctx: &teravars::Context,
1620 ) -> Result<()> {
1621 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1622 for path in paths {
1623 let one = teravars::load_merged([path], engine, ctx)
1624 .with_context(|| format!("rendering {}", path.display()))?;
1625 for key in array_keys(&one.config, "") {
1626 if array_merge_policy(&key) == ArrayMerge::Append {
1627 continue;
1628 }
1629 if let Some(first) = seen.get(&key) {
1630 bail!(
1631 "`{key}` is an array declared in two config layers:\n \
1632 {}\n {}\nteravars appends arrays when it merges, so \
1633 magi would run the concatenation of both - which is \
1634 not what either file says. Declare `{key}` in exactly \
1635 one of them.",
1636 first.display(),
1637 path.display()
1638 );
1639 }
1640 seen.insert(key, path.clone());
1641 }
1642 }
1643 Ok(())
1644 }
1645
1646 /// Which layers contributed to a composed, appendable array key (e.g.
1647 /// `"verify.gate"`), in the same low-to-high-priority order
1648 /// [`Config::load_layers`] concatenates them in. Layers that do not
1649 /// declare `key` at all are omitted.
1650 ///
1651 /// This is a **display aid for `magi doctor` only.** The command list
1652 /// that actually runs always comes from the one joint
1653 /// [`teravars::load_merged`] call in `load_layers`, never from this
1654 /// function - the exact hazard [`Config::refuse_split_arrays`] warns
1655 /// about is two merge paths that might disagree, so this function must
1656 /// never become a second source of the *composed* value, only of which
1657 /// file wrote which line in it.
1658 ///
1659 /// Re-rendering each layer alone can, in principle, resolve a
1660 /// `{{ vars.x }}` differently than the joint render would, if `x` is
1661 /// defined in one layer and referenced in another - the same caveat
1662 /// `refuse_split_arrays`'s structural, key-only check already lives with.
1663 /// None of magi's own gate commands cross that line, and a doctor listing
1664 /// is read by a human who can compare it against the joint one printed
1665 /// alongside it, so this is judged worth the simplicity of not
1666 /// threading provenance through the real load path.
1667 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1668 let mut engine = teravars::Engine::default();
1669 let ctx = Self::render_ctx(paths);
1670 let mut out = Vec::new();
1671 for path in paths {
1672 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1673 continue;
1674 };
1675 let mut cur = &one.config;
1676 let mut found = None;
1677 let parts: Vec<&str> = key.split('.').collect();
1678 for (i, part) in parts.iter().enumerate() {
1679 match cur.get(*part) {
1680 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1681 found = Some(a);
1682 break;
1683 }
1684 Some(toml::Value::Table(t)) => cur = t,
1685 _ => break,
1686 }
1687 }
1688 let Some(values) = found else { continue };
1689 let strings: Vec<String> = values
1690 .iter()
1691 .filter_map(|v| v.as_str().map(str::to_owned))
1692 .collect();
1693 if !strings.is_empty() {
1694 out.push((path.clone(), strings));
1695 }
1696 }
1697 out
1698 }
1699
1700 /// Each layer rendered on its own, with the outcome per file: the
1701 /// settings screen's way of saying which layer a value came from and which
1702 /// layer is the one that does not parse. A **display aid only**, for the
1703 /// same reason as [`Config::array_provenance`]: the effective config
1704 /// always comes from the one joint [`Config::load_layers`].
1705 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1706 let mut engine = teravars::Engine::default();
1707 let ctx = Self::render_ctx(paths);
1708 paths
1709 .iter()
1710 .map(|path| {
1711 let one = teravars::load_merged([path], &mut engine, &ctx)
1712 .map(|m| m.config)
1713 .with_context(|| format!("rendering {}", path.display()));
1714 (path.clone(), one)
1715 })
1716 .collect()
1717 }
1718
1719 /// Render a composed command list for `magi doctor`: the joined command
1720 /// line the run actually uses, plus - only when more than one layer
1721 /// contributed - which layer wrote which line.
1722 ///
1723 /// A single contributing layer (the common case today) stays the plain
1724 /// one-line summary magi has always printed, `empty` included: that
1725 /// honest "(none — ...)" is what caught a real gate-composition gap
1726 /// before this array could compose at all, and composition should not
1727 /// make the common case noisier.
1728 pub fn describe_composed(
1729 paths: &[PathBuf],
1730 commands: &[String],
1731 key: &str,
1732 empty: &str,
1733 ) -> String {
1734 if commands.is_empty() {
1735 return empty.to_owned();
1736 }
1737 let joined = commands.join(" && ");
1738 let provenance = Self::array_provenance(paths, key);
1739 if provenance.len() <= 1 {
1740 return joined;
1741 }
1742 let mut out = joined;
1743 for (path, cmds) in &provenance {
1744 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1745 }
1746 out
1747 }
1748
1749 /// Resolve the config for `repo`, honouring an explicit `--config` path.
1750 ///
1751 /// Returns the config and the layers it came from, empty for built-in
1752 /// defaults. The repository layers come from the remote-tracking ref as it
1753 /// stands (see the module doc); use [`Config::discover_fetched`] where a
1754 /// stale ref would matter.
1755 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1756 if let Some(p) = explicit {
1757 let paths = vec![p.to_path_buf()];
1758 return Ok((Self::load_layers(&paths)?, paths));
1759 }
1760 let paths = Self::layers_checked(repo)?;
1761 if paths.is_empty() {
1762 return Ok((Self::autodetected(), paths));
1763 }
1764 Ok((Self::load_layers(&paths)?, paths))
1765 }
1766
1767 /// [`Config::discover`] after `git fetch <remote> <base>`: for every path
1768 /// that is about to start work. A failed fetch is an error.
1769 pub async fn discover_fetched(
1770 repo: &Path,
1771 explicit: Option<&Path>,
1772 ) -> Result<(Self, Vec<PathBuf>)> {
1773 if explicit.is_none() && is_git_worktree(repo) {
1774 // A checkout that was never cloned from the remote has no
1775 // `<remote>/HEAD`; learn it here (refs/remotes only) so an
1776 // ordinary start recovers instead of failing in `discover`.
1777 let (remote, cfg_base) = probe_remote_base(repo);
1778 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref()).await?;
1779 let out = crate::git::fetch(repo, &remote, &base)
1780 .await
1781 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))?;
1782 if !out.ok() {
1783 bail!(
1784 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
1785 out.stderr.lines().next().unwrap_or("").trim()
1786 );
1787 }
1788 if cfg_base.is_none() {
1789 crate::git::ensure_remote_head(repo, &remote, &base).await;
1790 }
1791 }
1792 Self::discover(repo, explicit)
1793 }
1794
1795 /// [`Config::layers`], but an unreadable remote ref is an error.
1796 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
1797 if !is_git_worktree(repo) {
1798 return Ok(Self::layers(repo));
1799 }
1800 let mut paths: Vec<PathBuf> = Self::machine_layer()
1801 .into_iter()
1802 .filter(|p| p.is_file())
1803 .collect();
1804 paths.extend(Self::repo_layers(repo)?);
1805 Ok(paths)
1806 }
1807
1808 /// Describe a repository layer without directing the operator to its cache.
1809 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
1810 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
1811 if let Some(root) = cached {
1812 let relative = path.strip_prefix(root).unwrap_or(path);
1813 let reference = resolve_remote_base(repo)
1814 .map(|(remote, base)| format!("{remote}/{base}"))
1815 .unwrap_or_else(|_| "remote base".to_owned());
1816 format!(
1817 "{} at {reference} (including its includes)",
1818 repo.join(relative).display()
1819 )
1820 } else {
1821 format!("{} (including its includes)", path.display())
1822 }
1823 }
1824
1825 /// Only the repository layers (lowest first), from `<remote>/<base>` in a
1826 /// git working tree and from disk elsewhere.
1827 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
1828 if !is_git_worktree(repo) {
1829 return Ok([
1830 repo.join(".magi").join("config.toml"),
1831 repo.join("magi.toml"),
1832 ]
1833 .into_iter()
1834 .filter(|p| p.is_file())
1835 .collect());
1836 }
1837 remote_layers(repo)
1838 }
1839
1840 /// Environment variable that relocates the machine-wide config layer.
1841 ///
1842 /// Set it to a directory and magi reads `<dir>/magi/config.toml` instead
1843 /// of the one under [`dirs::config_dir`]; set it to the empty string and
1844 /// magi reads no machine layer at all.
1845 ///
1846 /// This exists because the machine layer is otherwise unavoidable, and a
1847 /// test that builds a config fixture is not asking for the operator's
1848 /// preferences to be merged into it. Adding `[repos] roots` to the real
1849 /// machine config on a development box turned two passing tests red -
1850 /// `repos_list_returns_name_and_path_for_every_configured_root` and
1851 /// `repos_list_only_rescans_within_the_ttl_when_asked_to`, whose fixtures
1852 /// declare `[repos] roots` of their own, which [`Config::layers`] then
1853 /// found in two layers and [`Config::refuse_split_arrays`] correctly
1854 /// refused. CI never saw it: a runner has no machine config, so the suite
1855 /// was green there and red only where somebody actually uses magi.
1856 ///
1857 /// An operator gets the same escape hatch for free: a second machine
1858 /// config, or none, without moving files about.
1859 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
1860
1861 /// Every config layer that applies to `repo`, in increasing precedence.
1862 ///
1863 /// The machine layer is whatever [`Config::machine_layer`] resolves to,
1864 /// which is nothing at all in a test build.
1865 pub fn layers(repo: &Path) -> Vec<PathBuf> {
1866 let mut paths = Vec::new();
1867 paths.extend(Self::machine_layer());
1868 paths.push(repo.join(".magi").join("config.toml"));
1869 paths.push(repo.join("magi.toml"));
1870 paths.retain(|p| p.is_file());
1871 paths
1872 }
1873
1874 /// The machine-wide layer's path, when there is one.
1875 ///
1876 /// **A test build has none unless it names one.** A fixture is a complete
1877 /// statement of the config under test, and the operator's own preferences
1878 /// have no business being merged into it - least of all silently, on one
1879 /// machine, in a suite that is green everywhere else.
1880 #[cfg(test)]
1881 pub(crate) fn machine_layer() -> Option<PathBuf> {
1882 std::env::var(Self::CONFIG_DIR_ENV)
1883 .ok()
1884 .filter(|dir| !dir.trim().is_empty())
1885 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
1886 }
1887
1888 /// The machine-wide layer's path, when there is one.
1889 #[cfg(not(test))]
1890 pub(crate) fn machine_layer() -> Option<PathBuf> {
1891 match std::env::var(Self::CONFIG_DIR_ENV) {
1892 // Named, and empty on purpose: no machine layer.
1893 Ok(dir) if dir.trim().is_empty() => None,
1894 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
1895 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
1896 }
1897 }
1898
1899 /// Built-in config whose roster is the agent CLIs found on `PATH`.
1900 pub fn autodetected() -> Self {
1901 let mut cfg = Self::default();
1902 for (kind, id, model) in [
1903 (AgentKind::Claude, "opus", Some("opus")),
1904 (AgentKind::Claude, "sonnet", Some("sonnet")),
1905 (AgentKind::Antigravity, "antigravity", None),
1906 (AgentKind::Opencode, "opencode", None),
1907 (AgentKind::Codex, "codex", None),
1908 (AgentKind::Omp, "omp", None),
1909 ] {
1910 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
1911 cfg.agents.push(AgentSpec {
1912 id: id.to_owned(),
1913 kind,
1914 model: model.map(str::to_owned),
1915 command: Vec::new(),
1916 extra_args: Vec::new(),
1917 env: BTreeMap::new(),
1918 prompt_delivery: None,
1919 });
1920 }
1921 }
1922 cfg
1923 }
1924
1925 /// The shared build cache the verify commands and the agents both build
1926 /// into, when the config declares one. See [`Verify::cache_dir`].
1927 pub fn cache_dir(&self) -> Option<PathBuf> {
1928 self.verify.cache_dir()
1929 }
1930
1931 /// Look an agent up by id.
1932 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
1933 self.agents
1934 .iter()
1935 .find(|a| a.id == id)
1936 .with_context(|| format!("no agent with id `{id}` in the roster"))
1937 }
1938
1939 /// Rotate `count` seats out of `ids`, or out of the whole roster at
1940 /// `offset` when `ids` is empty.
1941 ///
1942 /// The one rotation rule - explicit ids cycle, an empty list rotates the
1943 /// roster - shared by every seat count [`Config::resolve_roles`] fills in,
1944 /// rather than each seat reimplementing it and drifting apart.
1945 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
1946 let mut out = Vec::with_capacity(count);
1947 for i in 0..count {
1948 let spec = if ids.is_empty() {
1949 self.agents[(i + offset) % self.agents.len()].clone()
1950 } else {
1951 self.agent(&ids[i % ids.len()])?.clone()
1952 };
1953 out.push(spec);
1954 }
1955 Ok(out)
1956 }
1957
1958 /// `ids`, resolved to specs in the order named, or the whole `[[agents]]`
1959 /// roster in file order when `ids` is empty — the same "explicit ids
1960 /// stand alone, an empty list means the whole roster" rule [`Self::rotate`]
1961 /// applies, but with no `count` to truncate to and no `offset` to wrap by.
1962 /// See [`ResolvedRoles::implementer_roster`] for why a truncated, rotated
1963 /// list cannot answer the question this exists for.
1964 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
1965 if ids.is_empty() {
1966 Ok(self.agents.clone())
1967 } else {
1968 ids.iter().map(|id| self.agent(id).cloned()).collect()
1969 }
1970 }
1971
1972 /// Fill the roles out to the configured widths.
1973 ///
1974 /// An empty role list rotates through the whole roster, so a three-agent
1975 /// roster with `implementers = 3` gives one implementation per agent, and
1976 /// `judges = 3` rotates the judge seats by one so that judge *i* is not the
1977 /// author of candidate *i* whenever the roster has more than one agent.
1978 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
1979 if self.agents.is_empty() {
1980 bail!(
1981 "agent roster is empty: no agent CLI found on PATH and no \
1982 [[agents]] in the config. Run `magi init` to write a starter \
1983 magi.toml."
1984 );
1985 }
1986 Ok(ResolvedRoles {
1987 implementers: self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
1988 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
1989 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
1990 fixer: match self.roles.fixer.as_ref() {
1991 // Ids are validated against the roster here; whether the CLI
1992 // is installed is left to invocation, like every other seat.
1993 Some(choice) => Some(crate::agent::pick_chain(
1994 &self.agents,
1995 Some(choice),
1996 &|_| true,
1997 "fixer",
1998 )?),
1999 None => None,
2000 },
2001 // Role resolution validates roster shape, but deliberately does
2002 // not preflight a CLI. The other graph seats have always deferred
2003 // that failure to invocation; doing it only for the conductor
2004 // made otherwise usable graph commands and `doctor` fail as one.
2005 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2006 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2007 // A fallback chain: the first id the roster knows. The rest
2008 // are `agent::pick_chain`'s business at invocation.
2009 Some(ids) if !ids.is_empty() => ids
2010 .iter()
2011 .find_map(|id| self.agent(id).ok())
2012 .cloned()
2013 .with_context(|| {
2014 format!("[roles] conductor names no agent in the roster: {ids:?}")
2015 })?,
2016 // Keep the normal standalone-seat preference when something
2017 // is installed, but retain a roster fallback when it is not.
2018 // Invocation then reports the unavailable CLI in the same
2019 // place it does for every other graph role.
2020 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2021 .unwrap_or_else(|_| self.agents[0].clone()),
2022 },
2023 implementer_roster: self.full_roster(&self.roles.implementers)?,
2024 judge_roster: self.full_roster(&self.roles.judges)?,
2025 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2026 })
2027 }
2028
2029 /// Advisor seats for the design-deliberation stage (see
2030 /// `graph::Runner::advise`): `[roles] advisors` when set, otherwise the
2031 /// judge roster - see [`Roles::advisors`] for why that fallback and not
2032 /// the whole roster.
2033 ///
2034 /// The fallback rotates with `offset = 1`, matching the judges line in
2035 /// [`Config::resolve_roles`] exactly, `ids` and offset both - not just
2036 /// `roles.judges`, which is empty whenever judges themselves are
2037 /// unconfigured and rotating the whole roster. Falling back with
2038 /// `offset = 0` there would silently hand the advisors a *different*
2039 /// agent set than the judges an unconfigured run would actually get,
2040 /// which is the one thing [`Roles::advisors`]'s doc promises will not
2041 /// happen.
2042 ///
2043 /// Called lazily from the graph node itself rather than folded into
2044 /// [`Config::resolve_roles`]: unlike the other roles, a failure here must
2045 /// not stop a run from starting at all - the deliberation stage is an
2046 /// enrichment `[graph] advise` can turn off, not a seat later nodes
2047 /// cannot proceed without - and at the point `resolve_roles` runs (before
2048 /// [`crate::run::RunState`] exists, on `Runner::start`) there would be no
2049 /// run yet for a resolution failure to be reported against.
2050 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2051 if self.agents.is_empty() {
2052 bail!(
2053 "agent roster is empty: no agent CLI found on PATH and no \
2054 [[agents]] in the config. Run `magi init` to write a starter \
2055 magi.toml."
2056 );
2057 }
2058 if !self.roles.advisors.is_empty() {
2059 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2060 }
2061 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2062 }
2063
2064 /// The untruncated roster advisor seats hand over along: `[roles]
2065 /// advisors` when set, otherwise the judges' roster, exactly as
2066 /// [`Self::advisors`] chooses its own list.
2067 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2068 if self.roles.advisors.is_empty() {
2069 self.full_roster(&self.roles.judges)
2070 } else {
2071 self.full_roster(&self.roles.advisors)
2072 }
2073 }
2074
2075 /// Shell prefix for [`Verify`] commands.
2076 pub fn shell(&self) -> Vec<String> {
2077 if let Some(s) = &self.verify.shell {
2078 return s.clone();
2079 }
2080 if which("sh") {
2081 vec!["sh".to_owned(), "-c".to_owned()]
2082 } else {
2083 vec!["cmd".to_owned(), "/C".to_owned()]
2084 }
2085 }
2086
2087 /// Starter config, as written by `magi init`.
2088 pub fn starter_toml() -> String {
2089 let detected = Self::autodetected();
2090 let mut s = String::from(
2091 "# magi — blind multi-agent implementation competition.\n\
2092 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2093 # -> blind judging -> deliberation -> private final vote\n\
2094 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2095 #\n\
2096 # Rendered by teravars: a `[vars]` table, env\n\
2097 # and system lookups, and `include = [...]` all work. Tera\n\
2098 # braces are live everywhere in this file, but comments are\n\
2099 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2100 # may quote `{{ ... }}` freely.\n\
2101 #\n\
2102 # Layers deep-merge in increasing\n\
2103 # precedence, so the roster can live once per machine in\n\
2104 # <config_dir>/magi/config.toml and each repo only states its own\n\
2105 # gate:\n\
2106 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2107 [vars]\n\
2108 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2109 # Single quotes inside the braces: teravars renders the raw file\n\
2110 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2111 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2112 );
2113 if detected.agents.is_empty() {
2114 s.push_str(
2115 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2116 # kind = claude | opencode | antigravity | codex | command\n\
2117 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2118 );
2119 } else {
2120 for a in &detected.agents {
2121 s.push_str("[[agents]]\n");
2122 s.push_str(&format!("id = {:?}\n", a.id));
2123 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2124 if let Some(m) = &a.model {
2125 s.push_str(&format!("model = {m:?}\n"));
2126 }
2127 s.push('\n');
2128 }
2129 }
2130 s.push_str(
2131 "# Leave a role list empty to rotate through the roster.\n\
2132 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2133 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2134 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2135 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2136 [roles]\n\
2137 implementers = []\n\
2138 judges = []\n\
2139 reviewers = []\n\
2140 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2141 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2142 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2143 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2144 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2145 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2146 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2147 [graph]\n\
2148 # Gate GitHub prose; secret redaction is always enabled.\n\
2149 github_text_guard = true\n\
2150 implementers = 3\n\
2151 judges = 3\n\
2152 deliberate_rounds = 1\n\
2153 reviewers = 3\n\
2154 review_rounds = 6\n\
2155 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2156 gate_fix_rounds = 1\n\
2157 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2158 rerun_flaky_checks = true\n\
2159 # Port the strengths judges named in the losing candidates onto the\n\
2160 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2161 graft_runner_up = true\n\
2162 max_parallel = 4\n\
2163 language = \"en\"\n\
2164 # One CLI conversation per seat: judges keep their own argument\n\
2165 # across deliberation, the fixer keeps its implementation context.\n\
2166 sessions = true\n\
2167 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2168 # the final gate inherit this value for compatibility.\n\
2169 timeout_review = 1200\n\
2170 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2171 # verification independent if timeout_review changes later.\n\
2172 # timeout_verify = 1200\n\n\
2173 # What the chat calls you (persona address and the Chat's turn label).\n\
2174 # [talk]\n\
2175 # operator_name = \"Commander\"\n\n\
2176 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2177 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2178 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2179 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2180 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2181 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2182 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2183 # [[talk.personas]]\n\
2184 # id = \"gendo\"\n\
2185 # name = \"Gendo Ikari\"\n\
2186 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2187 # icon = \"~/pictures/gendo.png\"\n\n\
2188 [verify]\n\
2189 # Run once per review round in the winner's worktree; failures are\n\
2190 # fed back to the fixer.\n\
2191 e2e = []\n\
2192 # Final gate. Every command must exit 0 before a merge.\n\
2193 gate = []\n\
2194 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2195 # before the gate; whatever they change becomes one commit. A failing\n\
2196 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2197 # gate (timeout_verify). Keep it light and idempotent.\n\
2198 # pre_gate = []\n\n\
2199 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2200 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2201 # before any agent or verify command touches it. `copy` reads from the\n\
2202 # primary checkout and never overwrites; `optional` skips a missing\n\
2203 # source. `run` goes through the shell with the worktree as cwd and\n\
2204 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2205 # the verify timeout). Setup must not edit tracked files, and what it\n\
2206 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2207 # layer only.\n\
2208 # [worktree]\n\
2209 # setup = [\n\
2210 # { copy = \".env.example -> .env\" },\n\
2211 # { copy = \".env.local\", optional = true },\n\
2212 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2213 # ]\n\n\
2214 [merge]\n\
2215 # none | local | pr\n\
2216 mode = \"none\"\n\
2217 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2218 [update]\n\
2219 # off | notify | install — checked in the background, throttled.\n\
2220 mode = \"notify\"\n\
2221 # interval = \"24h\"\n\n\
2222 [daemon]\n\
2223 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2224 # no new commit and no check changing state before `magi serve`\n\
2225 # notices and asks you. A failed check is rerun once on its own;\n\
2226 # still red after that escalates at once. 0 turns the watcher off.\n\
2227 # release_stall_minutes = 60\n\n\
2228 [release]\n\
2229 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2230 # Actions never run (private, no minutes): the release pull request\n\
2231 # does not wait for CI, you approve the merge in magi, and then\n\
2232 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2233 # runs `commands` from a clean checkout of the merge commit. A\n\
2234 # failure holds the release with a notice; it is never retried blind.\n\
2235 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2236 # mode = \"actions\"\n\
2237 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2238 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2239 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2240 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2241 # timeout_minutes = 30\n",
2242 );
2243 s
2244 }
2245}
2246
2247/// Is `program` on `PATH`?
2248pub fn which(program: &str) -> bool {
2249 find_program(program).is_some()
2250}
2251
2252/// The file a bare `program` name resolves to on `PATH`, the way the OS shell
2253/// would find it.
2254///
2255/// Spawn agents through this, not by bare name: on Windows Rust's std
2256/// only tries `name.exe`, so a CLI installed as an npm `.cmd` shim (codex
2257/// since its 2026-09-23 reinstall) is "not found" even though a shell runs it.
2258/// On Windows an extensionless file is never a match: npm writes an `sh`
2259/// script beside every `.cmd` shim, and spawning that fails with os error 193.
2260pub fn find_program(program: &str) -> Option<PathBuf> {
2261 find_program_on(program, &std::env::var_os("PATH")?)
2262}
2263
2264/// [`find_program`] against an explicit `PATH`, for a child whose environment
2265/// overrides it.
2266pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2267 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2268 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2269}
2270
2271fn find_program_in(
2272 program: &str,
2273 paths: &std::ffi::OsStr,
2274 pathext: Option<&str>,
2275) -> Option<PathBuf> {
2276 let p = Path::new(program);
2277 if p.components().count() > 1 {
2278 return p.is_file().then(|| p.to_path_buf());
2279 }
2280 std::env::split_paths(paths).find_map(|dir| match pathext {
2281 Some(exts) => {
2282 let bare = dir.join(program);
2283 if p.extension().is_some() && bare.is_file() {
2284 return Some(bare);
2285 }
2286 exts.split(';')
2287 .filter(|e| !e.is_empty())
2288 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2289 .find(|c| c.is_file())
2290 }
2291 None => Some(dir.join(program)).filter(|c| c.is_file()),
2292 })
2293}
2294
2295/// Sidecar naming the checkout an extracted layer stands for.
2296const REPO_MARKER: &str = ".magi-repo";
2297
2298fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2299 use crate::proc::Quiet as _;
2300 let out = std::process::Command::new("git")
2301 .args(args)
2302 .quiet()
2303 .current_dir(repo)
2304 .stdin(std::process::Stdio::null())
2305 .output()
2306 .ok()?;
2307 out.status
2308 .success()
2309 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2310}
2311
2312/// Is `repo` inside a git working tree? A directory that is not has no branch
2313/// to be stale against, so its files are read as they are.
2314fn is_git_worktree(repo: &Path) -> bool {
2315 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2316}
2317
2318#[derive(Deserialize, Default)]
2319struct ProbeMerge {
2320 base: Option<String>,
2321 remote: Option<String>,
2322}
2323
2324#[derive(Deserialize, Default)]
2325struct Probe {
2326 merge: Option<ProbeMerge>,
2327}
2328
2329/// `[merge]` base / remote from one file, nothing else. The file is rendered
2330/// (env templates, includes) exactly as a real load would, so a machine layer
2331/// saying `base = "{{ env.X }}"` locates the same ref; when rendering fails
2332/// (a checkout file that needs its own repo context) the plain TOML is read
2333/// instead. Unreadable is `None`: the real load reports it.
2334fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2335 if !path.is_file() {
2336 return None;
2337 }
2338 let paths = [path.to_path_buf()];
2339 let mut engine = teravars::Engine::default();
2340 let mut ctx = Config::render_ctx(&paths);
2341 // The layered load renders every layer for the checkout being resolved;
2342 // so does this, or `{{ repo_name }}` would name the file's own directory.
2343 ctx.insert("repo", &repo.to_string_lossy());
2344 ctx.insert(
2345 "repo_name",
2346 &repo.file_name().unwrap_or_default().to_string_lossy(),
2347 );
2348 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2349 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2350 {
2351 return probe.merge;
2352 }
2353 let text = std::fs::read_to_string(path).ok()?;
2354 toml::from_str::<Probe>(&text).ok()?.merge
2355}
2356
2357/// The `[merge] remote` / `base` the layers name, before any git lookup.
2358fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2359 let mut remote = None;
2360 let mut base = None;
2361 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2362 sources.push(repo.join("magi.toml"));
2363 sources.push(repo.join(".magi").join("config.toml"));
2364 for path in sources {
2365 if let Some(m) = probe_merge(&path, repo) {
2366 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2367 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2368 }
2369 }
2370 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2371}
2372
2373/// Where the remote ref is: see the module doc for the order.
2374fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2375 let (remote, base) = probe_remote_base(repo);
2376 let base = match base {
2377 Some(b) => b,
2378 None => {
2379 let head = format!("refs/remotes/{remote}/HEAD");
2380 git_out(repo, &["symbolic-ref", "--quiet", &head])
2381 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2382 .with_context(|| {
2383 format!(
2384 "cannot tell which branch of `{remote}` holds magi.toml: \
2385 set [merge] base, or run `git remote set-head {remote} -a`"
2386 )
2387 })?
2388 }
2389 };
2390 Ok((remote, base))
2391}
2392
2393fn fnv_hex(text: &str) -> String {
2394 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2395 for b in text.bytes() {
2396 hash ^= u64::from(b);
2397 hash = hash.wrapping_mul(0x0100_0000_01b3);
2398 }
2399 format!("{hash:016x}")
2400}
2401
2402/// Does the text declare an `include` directive in any form teravars accepts
2403/// (root `include`, bare or quoted, or `[teravars] include`, as a table or an
2404/// inline table)? Parsed as TOML when it parses; a templated file that does
2405/// not parse is judged by a plain search for the word, because over-detecting
2406/// only costs an extra extraction while missing one fails the load.
2407fn declares_include(text: &str) -> bool {
2408 match toml::from_str::<toml::Table>(text) {
2409 Ok(table) => {
2410 table.contains_key("include")
2411 || table
2412 .get("teravars")
2413 .and_then(toml::Value::as_table)
2414 .is_some_and(|t| t.contains_key("include"))
2415 }
2416 Err(_) => text.contains("include"),
2417 }
2418}
2419
2420/// Unpack the whole tree of `sha` into `dest`, so relative `include`s of a
2421/// repository layer resolve against the same commit.
2422fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2423 use crate::proc::Quiet as _;
2424 let mut archive = std::process::Command::new("git")
2425 .args(["archive", "--format=tar", sha])
2426 .quiet()
2427 .current_dir(repo)
2428 .stdin(std::process::Stdio::null())
2429 .stdout(std::process::Stdio::piped())
2430 .stderr(std::process::Stdio::null())
2431 .spawn()
2432 .context("running git archive")?;
2433 let tar = std::process::Command::new("tar")
2434 .arg("-x")
2435 .arg("-C")
2436 .arg(dest)
2437 .quiet()
2438 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2439 .output()
2440 .context("running tar")?;
2441 let status = archive.wait().context("waiting for git archive")?;
2442 if !status.success() || !tar.status.success() {
2443 bail!(
2444 "cannot unpack {sha} for the config's includes: {}",
2445 String::from_utf8_lossy(&tar.stderr).trim()
2446 );
2447 }
2448 Ok(())
2449}
2450
2451/// The repository layers (`.magi/config.toml`, `magi.toml`; lowest first) of
2452/// `<remote>/<base>`, extracted from one commit so both files agree.
2453fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2454 let (remote, base) = resolve_remote_base(repo)?;
2455 let tracking = format!("refs/remotes/{remote}/{base}");
2456 let spec = format!("{tracking}^{{commit}}");
2457 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2458 .map(|s| s.trim().to_owned())
2459 .filter(|s| !s.is_empty())
2460 .with_context(|| {
2461 format!(
2462 "`{remote}/{base}` does not exist in this checkout; fetch it \
2463 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2464 a possibly stale local magi.toml instead"
2465 )
2466 })?;
2467 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2468 let rels = [".magi/config.toml", "magi.toml"];
2469 let mut texts: Vec<(&str, String)> = Vec::new();
2470 for rel in rels {
2471 let object = format!("{sha}:{rel}");
2472 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2473 continue;
2474 }
2475 let Some(text) = git_out(repo, &["show", &object]) else {
2476 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2477 };
2478 texts.push((rel, text));
2479 }
2480 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2481 // Content-addressed and built beside the final name, then renamed in: a
2482 // concurrent `discover` sees the whole directory or none of it, never a
2483 // half-written file.
2484 let build = |root: &Path| -> Result<PathBuf> {
2485 let final_dir = root.join(&key);
2486 if !final_dir.is_dir() {
2487 std::fs::create_dir_all(root)?;
2488 let tmp = root.join(format!(
2489 "{key}.tmp-{}-{}",
2490 std::process::id(),
2491 std::time::SystemTime::now()
2492 .duration_since(std::time::UNIX_EPOCH)
2493 .map(|d| d.as_nanos())
2494 .unwrap_or_default()
2495 ));
2496 let filled = (|| -> Result<()> {
2497 std::fs::create_dir_all(&tmp)?;
2498 if wants_tree {
2499 extract_tree(repo, &sha, &tmp)?;
2500 }
2501 for (rel, text) in &texts {
2502 let file = tmp.join(rel);
2503 let parent = file.parent().unwrap_or(&tmp);
2504 std::fs::create_dir_all(parent)?;
2505 std::fs::write(&file, text)?;
2506 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2507 }
2508 Ok(())
2509 })();
2510 if let Err(e) = filled {
2511 let _ = std::fs::remove_dir_all(&tmp);
2512 return Err(e);
2513 }
2514 if std::fs::rename(&tmp, &final_dir).is_err() {
2515 // Lost the race to another process building the same commit.
2516 let _ = std::fs::remove_dir_all(&tmp);
2517 if !final_dir.is_dir() {
2518 bail!("cannot place {}", final_dir.display());
2519 }
2520 }
2521 }
2522 Ok(final_dir)
2523 };
2524 let common = git_out(
2525 repo,
2526 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2527 )
2528 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2529 let dir = match common.map(|c| build(&c)) {
2530 Some(Ok(d)) => d,
2531 _ => build(&std::env::temp_dir().join("magi-config"))
2532 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2533 };
2534 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2535}
2536
2537#[cfg(test)]
2538mod tests {
2539 #[test]
2540 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
2541 let mut cfg = Config::default();
2542 assert_eq!(
2543 cfg.context_window("claude-sonnet-4-5-20250929"),
2544 Some(200_000)
2545 );
2546 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
2547 assert_eq!(cfg.context_window("mystery-model"), None);
2548 cfg.context_windows
2549 .insert("claude-sonnet-4-5".into(), 1_000_000);
2550 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
2551 cfg.context_windows.insert("mystery".into(), 32_768);
2552 // Longest user prefix beats a shorter one and the built-in table.
2553 assert_eq!(
2554 cfg.context_window("claude-sonnet-4-5-20250929"),
2555 Some(1_000_000)
2556 );
2557 // An exact name beats any prefix.
2558 cfg.context_windows
2559 .insert("claude-sonnet-4-5-20250929".into(), 7);
2560 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
2561 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
2562 }
2563
2564 use super::*;
2565
2566 /// npm writes an extensionless `sh` script beside `codex.cmd`; on Windows
2567 /// the `.cmd` is the spawnable one (os error 193 otherwise, 2026-09-23).
2568 #[test]
2569 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
2570 let dir = tempfile::tempdir().unwrap();
2571 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
2572 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
2573 let paths = dir.path().as_os_str();
2574 assert_eq!(
2575 find_program_in("codex", paths, Some(".EXE;.CMD")),
2576 Some(dir.path().join("codex.cmd"))
2577 );
2578 assert_eq!(
2579 find_program_in("codex", paths, None),
2580 Some(dir.path().join("codex"))
2581 );
2582 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
2583 }
2584
2585 fn spec(id: &str) -> AgentSpec {
2586 AgentSpec {
2587 id: id.to_owned(),
2588 kind: AgentKind::Command,
2589 model: None,
2590 command: vec!["true".to_owned()],
2591 extra_args: Vec::new(),
2592 env: BTreeMap::new(),
2593 prompt_delivery: None,
2594 }
2595 }
2596
2597 #[test]
2598 fn github_text_guard_defaults_on_and_can_be_disabled() {
2599 let default: Graph = toml::from_str("").unwrap();
2600 assert!(default.github_text_guard);
2601 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
2602 assert!(!disabled.github_text_guard);
2603 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
2604 assert!(!config.graph.github_text_guard);
2605 assert!(Config::starter_toml().contains("github_text_guard = true"));
2606 }
2607
2608 #[test]
2609 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
2610 assert!(Graph::default().rerun_flaky_checks);
2611 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
2612 assert!(!off.rerun_flaky_checks);
2613 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
2614 }
2615
2616 #[test]
2617 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
2618 // `timeout_verify` used to not exist: `verify.e2e`/`verify.gate` ran
2619 // under `timeout_review`. A config written before this field existed
2620 // must run exactly as before, which means its default has to be the
2621 // same 1200s `timeout_review` has always defaulted to.
2622 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
2623 assert_eq!(g.timeout_verify, None);
2624 assert_eq!(g.verify_timeout(), 3600);
2625 }
2626
2627 #[test]
2628 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
2629 // The bug this field exists to close: `[graph] timeout_review = 45`
2630 // used to shrink the real-machine `verify.e2e`/`verify.gate` budget
2631 // along with the reviewer seats' own timeout, because both read the
2632 // same field.
2633 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
2634 assert_eq!(g.timeout_review, 45);
2635 assert_eq!(
2636 g.verify_timeout(),
2637 45,
2638 "an omitted legacy value follows review"
2639 );
2640 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
2641 .expect("parse explicit override");
2642 assert_eq!(explicit.verify_timeout(), 1200);
2643 }
2644
2645 #[test]
2646 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
2647 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
2648 assert_eq!(g.implementers, 4);
2649 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
2650 assert_eq!(g.implementers, 5);
2651 }
2652
2653 fn layered(lower: &str, upper: &str) -> Result<Config> {
2654 let dir = tempfile::tempdir().unwrap();
2655 let a = dir.path().join("a.toml");
2656 let b = dir.path().join("b.toml");
2657 std::fs::write(&a, lower).unwrap();
2658 std::fs::write(&b, upper).unwrap();
2659 Config::load_layers(&[a, b])
2660 }
2661
2662 #[test]
2663 fn graph_implementers_higher_layer_wins_across_spellings() {
2664 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
2665 assert_eq!(c.graph.implementers, 5);
2666 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
2667 assert_eq!(c.graph.implementers, 5);
2668 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
2669 assert_eq!(c.graph.implementers, 2);
2670 }
2671
2672 #[test]
2673 fn graph_implementers_both_keys_in_one_layer_is_refused() {
2674 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
2675 .unwrap_err()
2676 .to_string();
2677 assert!(
2678 err.contains("candidates") && err.contains("implementers"),
2679 "{err}"
2680 );
2681 assert!(err.contains("b.toml"), "{err}");
2682 }
2683
2684 #[test]
2685 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
2686 // `deny_unknown_fields` cuts both ways: a config from before
2687 // `timeout_verify`/`e2e_every_round` existed must still parse, with
2688 // both defaulted rather than refused as unknown-in-reverse.
2689 let g: Graph =
2690 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
2691 .expect("an old-shaped [graph] table must still parse");
2692 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
2693 assert!(
2694 !g.e2e_every_round,
2695 "off by default, same as before this field existed"
2696 );
2697 }
2698
2699 #[test]
2700 fn empty_roles_rotate_judges_off_their_own_candidate() {
2701 // Three seats, said out loud: this is a test about *rotation*, and it
2702 // has nothing to say about how many candidates a task buys by default.
2703 let cfg = Config {
2704 agents: vec![spec("a"), spec("b"), spec("c")],
2705 graph: Graph {
2706 implementers: 3,
2707 ..Graph::default()
2708 },
2709 ..Config::default()
2710 };
2711 let roles = cfg.resolve_roles().unwrap();
2712 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
2713 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
2714 assert_eq!(impls, ["a", "b", "c"]);
2715 assert_eq!(judges, ["b", "c", "a"]);
2716 for (i, j) in judges.iter().enumerate() {
2717 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
2718 }
2719 }
2720
2721 #[test]
2722 fn single_agent_roster_fills_every_seat() {
2723 let cfg = Config {
2724 agents: vec![spec("solo")],
2725 graph: Graph {
2726 implementers: 3,
2727 ..Graph::default()
2728 },
2729 ..Config::default()
2730 };
2731 let roles = cfg.resolve_roles().unwrap();
2732 assert_eq!(roles.implementers.len(), 3);
2733 assert!(roles.judges.iter().all(|a| a.id == "solo"));
2734 }
2735
2736 #[test]
2737 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
2738 // `implementers = 1` (a solo run) still resolves `implementers` down to
2739 // one slot, but `implementer_roster` must carry every agent in the
2740 // roster, in file order, for `graph::Runner`'s quota fallback to walk
2741 // forward through once that one slot's agent runs out of quota.
2742 let cfg = Config {
2743 agents: vec![spec("a"), spec("b"), spec("c")],
2744 graph: Graph {
2745 implementers: 1,
2746 ..Graph::default()
2747 },
2748 ..Config::default()
2749 };
2750 let roles = cfg.resolve_roles().unwrap();
2751 assert_eq!(roles.implementers.len(), 1);
2752 let roster: Vec<&str> = roles
2753 .implementer_roster
2754 .iter()
2755 .map(|a| a.id.as_str())
2756 .collect();
2757 assert_eq!(roster, ["a", "b", "c"]);
2758 }
2759
2760 #[test]
2761 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
2762 let cfg = Config {
2763 agents: vec![spec("a"), spec("b"), spec("c")],
2764 roles: Roles {
2765 implementers: vec!["c".to_owned(), "a".to_owned()],
2766 ..Roles::default()
2767 },
2768 graph: Graph {
2769 implementers: 1,
2770 ..Graph::default()
2771 },
2772 ..Config::default()
2773 };
2774 let roles = cfg.resolve_roles().unwrap();
2775 // Unaffected by the new field: still just the first named id.
2776 assert_eq!(roles.implementers.len(), 1);
2777 assert_eq!(roles.implementers[0].id, "c");
2778 let roster: Vec<&str> = roles
2779 .implementer_roster
2780 .iter()
2781 .map(|a| a.id.as_str())
2782 .collect();
2783 assert_eq!(roster, ["c", "a"]);
2784 }
2785
2786 #[test]
2787 fn explicit_roles_win() {
2788 let cfg = Config {
2789 agents: vec![spec("a"), spec("b")],
2790 roles: Roles {
2791 implementers: vec!["b".to_owned()],
2792 judges: vec!["a".to_owned()],
2793 reviewers: Vec::new(),
2794 fixer: Some("a".into()),
2795 ..Roles::default()
2796 },
2797 ..Config::default()
2798 };
2799 let roles = cfg.resolve_roles().unwrap();
2800 assert!(roles.implementers.iter().all(|a| a.id == "b"));
2801 assert!(roles.judges.iter().all(|a| a.id == "a"));
2802 let fixer = roles.fixer.unwrap();
2803 assert_eq!(fixer.len(), 1);
2804 assert_eq!(fixer[0].id, "a");
2805 assert_eq!(roles.conductor.id, "a");
2806 }
2807
2808 #[test]
2809 fn fixer_takes_a_string_or_an_ordered_chain() {
2810 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
2811 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
2812 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
2813 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
2814
2815 let resolve = |fixer: Option<AgentChoice>| {
2816 Config {
2817 agents: vec![spec("a"), spec("b"), spec("c")],
2818 roles: Roles {
2819 fixer,
2820 ..Roles::default()
2821 },
2822 ..Config::default()
2823 }
2824 .resolve_roles()
2825 };
2826 let ids = |r: &ResolvedRoles| -> Vec<String> {
2827 r.fixer
2828 .as_ref()
2829 .unwrap()
2830 .iter()
2831 .map(|s| s.id.clone())
2832 .collect()
2833 };
2834 // The string form is a chain of one; unset stays unset (the winner's author).
2835 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
2836 assert!(resolve(None).unwrap().fixer.is_none());
2837 // Order kept, an unknown id skipped, a duplicate keeps its first place.
2838 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
2839 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
2840 // Nothing resolving names the role.
2841 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
2842 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
2843 }
2844
2845 #[test]
2846 fn unknown_agent_id_is_an_error() {
2847 let cfg = Config {
2848 agents: vec![spec("a")],
2849 roles: Roles {
2850 judges: vec!["nope".to_owned()],
2851 ..Roles::default()
2852 },
2853 ..Config::default()
2854 };
2855 assert!(cfg.resolve_roles().is_err());
2856 }
2857
2858 #[test]
2859 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
2860 let mut cfg = Config {
2861 agents: vec![spec("a"), spec("b")],
2862 ..Config::default()
2863 };
2864 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
2865
2866 cfg.roles.conductor = Some("b".into());
2867 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
2868
2869 cfg.roles.conductor = Some("missing".into());
2870 assert!(cfg.resolve_roles().is_err());
2871 }
2872
2873 #[test]
2874 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
2875 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
2876 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
2877 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
2878
2879 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
2880 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
2881 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
2882
2883 for roles in [one, chain] {
2884 let text = toml::to_string(&roles).unwrap();
2885 let back: Roles = toml::from_str(&text).unwrap();
2886 assert_eq!(back.synthesizer, roles.synthesizer);
2887 assert_eq!(back.chatter, roles.chatter);
2888 }
2889 let text = toml::to_string(&Roles {
2890 conductor: Some("x".into()),
2891 ..Roles::default()
2892 })
2893 .unwrap();
2894 assert!(
2895 text.contains("conductor = \"x\""),
2896 "string stays a string: {text}"
2897 );
2898 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
2899 }
2900
2901 #[test]
2902 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
2903 for (text, ids) in [
2904 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
2905 (
2906 r#"dupes_judge = ["first", "second"]"#,
2907 vec!["first", "second"],
2908 ),
2909 ("dupes_judge = []", vec![]),
2910 ] {
2911 let roles: Roles = toml::from_str(text).unwrap();
2912 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
2913 let serialized = toml::to_string(&roles).unwrap();
2914 let back: Roles = toml::from_str(&serialized).unwrap();
2915 assert_eq!(back.dupes_judge, roles.dupes_judge);
2916 assert!(serialized.contains(text));
2917 }
2918 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
2919 assert!(Roles::default().dupes_judge.is_none());
2920 assert!(Config::starter_toml().contains("# dupes_judge ="));
2921
2922 // Standalone roles are resolved lazily, just like chatter.
2923 let mut cfg = Config {
2924 agents: vec![spec("a")],
2925 ..Config::default()
2926 };
2927 cfg.roles.dupes_judge = Some("missing".into());
2928 assert!(cfg.resolve_roles().is_ok());
2929 }
2930
2931 #[test]
2932 fn an_empty_choice_counts_as_unset() {
2933 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
2934 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
2935 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
2936 }
2937
2938 #[test]
2939 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
2940 // Unlike `conductor`, `synthesizer` is never validated by
2941 // `resolve_roles` — it is looked up lazily by
2942 // `graph::Runner::synthesize_brief` the same way `[roles] chatter`
2943 // is looked up by `talk::begin`, so this exercises `agent::pick`
2944 // directly instead of going through `resolve_roles`.
2945 let mut cfg = Config {
2946 agents: vec![spec("a"), spec("b")],
2947 ..Config::default()
2948 };
2949 let want = primary(cfg.roles.synthesizer.as_ref());
2950 assert_eq!(
2951 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2952 .unwrap()
2953 .id,
2954 "a",
2955 "unset falls back to agent::pick's own default order"
2956 );
2957
2958 cfg.roles.synthesizer = Some("b".into());
2959 let want = primary(cfg.roles.synthesizer.as_ref());
2960 assert_eq!(
2961 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
2962 .unwrap()
2963 .id,
2964 "b",
2965 "the named agent wins over the default order"
2966 );
2967 }
2968
2969 #[test]
2970 fn empty_roster_is_an_error() {
2971 assert!(Config::default().resolve_roles().is_err());
2972 }
2973
2974 #[test]
2975 fn advise_defaults_to_on_with_three_proposals() {
2976 let g = Graph::default();
2977 assert!(g.advise);
2978 assert!(g.graft_runner_up, "graft is on by default");
2979 assert_eq!(g.advisors, 3);
2980 }
2981
2982 #[test]
2983 fn unset_advisors_falls_back_to_the_judge_roster() {
2984 let cfg = Config {
2985 agents: vec![spec("a"), spec("b")],
2986 roles: Roles {
2987 judges: vec!["b".to_owned()],
2988 ..Roles::default()
2989 },
2990 graph: Graph {
2991 advisors: 2,
2992 ..Graph::default()
2993 },
2994 ..Config::default()
2995 };
2996 let advisors = cfg.advisors().expect("advisors resolve");
2997 assert_eq!(advisors.len(), 2);
2998 assert!(
2999 advisors.iter().all(|a| a.id == "b"),
3000 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3001 );
3002 }
3003
3004 #[test]
3005 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3006 let cfg = Config {
3007 agents: vec![spec("a"), spec("b")],
3008 roles: Roles {
3009 judges: vec!["b".to_owned()],
3010 advisors: vec!["a".to_owned()],
3011 ..Roles::default()
3012 },
3013 graph: Graph {
3014 advisors: 2,
3015 ..Graph::default()
3016 },
3017 ..Config::default()
3018 };
3019 let advisors = cfg.advisors().expect("advisors resolve");
3020 assert!(advisors.iter().all(|a| a.id == "a"));
3021 }
3022
3023 /// Neither `[roles] advisors` nor `[roles] judges` set: an unconfigured
3024 /// advisor roster must resolve to the exact same agents an unconfigured
3025 /// judge panel would get - same ids, same rotation offset - or the
3026 /// promise in [`Roles::advisors`]'s doc ("advisor diversity for free")
3027 /// does not actually hold.
3028 #[test]
3029 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3030 let cfg = Config {
3031 agents: vec![spec("a"), spec("b"), spec("c")],
3032 graph: Graph {
3033 advisors: 3,
3034 judges: 3,
3035 ..Graph::default()
3036 },
3037 ..Config::default()
3038 };
3039 let advisors = cfg.advisors().expect("advisors resolve");
3040 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3041 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3042 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3043 assert_eq!(
3044 advisor_ids, judge_ids,
3045 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3046 );
3047 }
3048
3049 #[test]
3050 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3051 let cfg = Config {
3052 agents: vec![spec("a")],
3053 roles: Roles {
3054 advisors: vec!["nope".to_owned()],
3055 ..Roles::default()
3056 },
3057 graph: Graph {
3058 advisors: 1,
3059 ..Graph::default()
3060 },
3061 ..Config::default()
3062 };
3063 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3064 assert!(format!("{err:#}").contains("nope"));
3065 }
3066
3067 #[test]
3068 fn repos_default_to_no_roots_and_a_day_of_trust() {
3069 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3070 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3071 assert_eq!(Config::default().repos.fetch_interval, 600);
3072 }
3073
3074 #[test]
3075 fn a_config_file_with_no_repos_table_still_loads() {
3076 let dir = tempfile::tempdir().unwrap();
3077 let path = dir.path().join("magi.toml");
3078 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3079 let cfg = Config::load(&path).expect("must load without [repos]");
3080 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3081 assert_eq!(cfg.repos.scan_ttl, 86_400);
3082 }
3083
3084 /// A fixture is the whole config under test.
3085 ///
3086 /// `layers` used to reach for `dirs::config_dir()` unconditionally, so on
3087 /// a machine where somebody had written `<config_dir>/magi/config.toml`
3088 /// the suite silently loaded it as the lowest layer. Adding `[repos]
3089 /// roots` there turned two web tests red - their fixtures declare
3090 /// `[repos] roots` too, and `refuse_split_arrays` rightly refuses one
3091 /// array key spread across two layers. CI stayed green throughout,
3092 /// because a runner has no such file: the suite failed only where magi is
3093 /// actually used.
3094 ///
3095 /// So a test build has no machine layer unless it asks for one, and this
3096 /// is that promise. Written against a real file at the real location so
3097 /// it fails if `machine_layer` starts reading it again.
3098 #[test]
3099 fn a_test_build_does_not_read_the_operators_machine_config() {
3100 let repo = tempfile::tempdir().unwrap();
3101 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3102
3103 let layers = Config::layers(repo.path());
3104 assert_eq!(
3105 layers,
3106 vec![repo.path().join("magi.toml")],
3107 "only the fixture's own file may be a layer"
3108 );
3109 if let Some(real) = dirs::config_dir() {
3110 let machine = real.join("magi").join("config.toml");
3111 assert!(
3112 !layers.contains(&machine),
3113 "the operator's {} must not be a layer in a test build",
3114 machine.display()
3115 );
3116 }
3117 }
3118
3119 #[test]
3120 fn starter_toml_loads_through_teravars() {
3121 let dir = tempfile::tempdir().unwrap();
3122 let path = dir.path().join("magi.toml");
3123 std::fs::write(&path, Config::starter_toml()).unwrap();
3124 let parsed = Config::load(&path).expect("starter config must load");
3125 assert_eq!(parsed.graph.implementers, 3);
3126 assert_eq!(parsed.merge.mode, MergeMode::None);
3127 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3128 assert!(parsed.graph.sessions);
3129 assert!(parsed.graph.github_text_guard);
3130 assert_eq!(parsed.graph.timeout_review, 1200);
3131 assert_eq!(parsed.graph.verify_timeout(), 1200);
3132 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3133 }
3134
3135 #[test]
3136 fn release_defaults_to_actions_and_the_starter_documents_it() {
3137 let dir = tempfile::tempdir().unwrap();
3138 let path = dir.path().join("magi.toml");
3139 std::fs::write(&path, Config::starter_toml()).unwrap();
3140 let r = Config::load(&path).unwrap().release;
3141 assert_eq!(r.mode, ReleaseMode::Actions);
3142 assert!(!r.is_local());
3143 assert!(r.commands.is_empty());
3144 assert_eq!(r.timeout_minutes, 30);
3145 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3146 }
3147
3148 #[test]
3149 fn release_local_parses_and_unknown_keys_are_refused() {
3150 let dir = tempfile::tempdir().unwrap();
3151 let path = dir.path().join("magi.toml");
3152 std::fs::write(
3153 &path,
3154 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3155 )
3156 .unwrap();
3157 let r = Config::load(&path).unwrap().release;
3158 assert!(r.is_local());
3159 assert_eq!(r.commands.len(), 2);
3160 assert_eq!(r.timeout_minutes, 5);
3161 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3162 assert!(Config::load(&path).is_err());
3163 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3164 assert!(Config::load(&path).is_err());
3165 }
3166
3167 #[test]
3168 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3169 let dir = tempfile::tempdir().unwrap();
3170 let path = dir.path().join("magi.toml");
3171 std::fs::write(&path, Config::starter_toml()).unwrap();
3172 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3173 assert!(Config::starter_toml().contains("# pre_gate = []"));
3174 }
3175
3176 #[test]
3177 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3178 let starter = Config::starter_toml();
3179 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3180 assert!(starter.contains("verification independent if timeout_review changes later"));
3181 assert!(starter.contains("# timeout_verify = 1200"));
3182 }
3183
3184 #[test]
3185 fn starter_toml_documents_chat_personas() {
3186 let starter = Config::starter_toml();
3187 assert!(starter.contains("# [[talk.personas]]"));
3188 assert!(starter.contains("tone only"));
3189 }
3190
3191 #[test]
3192 fn talk_personas_parse_and_are_validated() {
3193 let dir = tempfile::tempdir().unwrap();
3194 let path = dir.path().join("magi.toml");
3195 std::fs::write(
3196 &path,
3197 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3198 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3199 )
3200 .unwrap();
3201 let cfg = Config::load(&path).expect("loads");
3202 assert_eq!(cfg.talk.personas.len(), 2);
3203 let catalog = crate::persona::catalog(&cfg.talk.personas);
3204 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3205 assert_eq!(
3206 (rei.name.as_str(), rei.prompt.as_str()),
3207 ("Quiet", "Be brief.")
3208 );
3209 assert_eq!(catalog.last().unwrap().id, "gendo");
3210
3211 for (body, needle) in [
3212 (
3213 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3214 "empty `id`",
3215 ),
3216 (
3217 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3218 "empty `prompt`",
3219 ),
3220 (
3221 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3222 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3223 "more than once",
3224 ),
3225 (
3226 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3227 "cannot be redefined",
3228 ),
3229 ] {
3230 std::fs::write(&path, body).unwrap();
3231 let err = format!("{:#}", Config::load(&path).unwrap_err());
3232 assert!(err.contains(needle), "{needle}: {err}");
3233 }
3234 }
3235
3236 #[test]
3237 fn talk_operator_name_is_trimmed_and_validated() {
3238 let dir = tempfile::tempdir().unwrap();
3239 let path = dir.path().join("magi.toml");
3240 let load = |body: &str| {
3241 std::fs::write(&path, body).unwrap();
3242 Config::load(&path)
3243 };
3244 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3245 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3246 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3247 assert_eq!(blank.talk.operator_name(), None);
3248 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3249 let long = "x".repeat(65);
3250 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3251 }
3252
3253 #[test]
3254 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3255 let dir = tempfile::tempdir().unwrap();
3256 let load = |body: &str| {
3257 let path = dir.path().join("c.toml");
3258 std::fs::write(&path, body).unwrap();
3259 Config::load(&path)
3260 };
3261 let ok = load(
3262 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3263 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3264 )
3265 .unwrap();
3266 let c = crate::persona::catalog(&ok.talk.personas);
3267 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3268 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3269 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3270 let oversized = format!(
3271 "data:image/png;base64,{}",
3272 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3273 );
3274 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3275 for (id, fields) in [
3276 ("rei", ""),
3277 ("default", ""),
3278 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3279 ] {
3280 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3281 let cfg = load(&body).expect("bad icon must not invalidate config");
3282 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3283 assert_eq!(persona.id, id);
3284 assert!(crate::persona_icon::load(bad).is_err());
3285 }
3286 }
3287 let doc = Config::starter_toml();
3288 assert!(doc.contains("# icon = "));
3289 }
3290
3291 #[test]
3292 fn talk_personas_in_two_layers_are_refused() {
3293 let dir = tempfile::tempdir().unwrap();
3294 let machine = dir.path().join("machine.toml");
3295 let repo = dir.path().join("repo.toml");
3296 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3297 std::fs::write(&machine, one).unwrap();
3298 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3299 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3300 assert!(err.contains("talk.personas"), "{err}");
3301 }
3302
3303 #[test]
3304 fn starter_toml_documents_role_lists_as_backup_order() {
3305 let starter = Config::starter_toml();
3306 assert!(starter.contains("also an ordered backup list"));
3307 assert!(starter.contains("codex then sonnet are spares"));
3308 }
3309
3310 /// A repository whose ruleset forbids merge commits declares that once,
3311 /// here, rather than magi asking GitHub about it on every render (see
3312 /// [`MergeStyle`]'s own doc for why).
3313 #[test]
3314 fn a_repository_can_declare_a_linear_history_merge_style() {
3315 let dir = tempfile::tempdir().unwrap();
3316 let path = dir.path().join("magi.toml");
3317 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3318 let parsed = Config::load(&path).expect("config must load");
3319 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3320 }
3321
3322 #[test]
3323 fn later_layers_win_and_vars_render() {
3324 let dir = tempfile::tempdir().unwrap();
3325 let machine = dir.path().join("machine.toml");
3326 let project = dir.path().join("magi.toml");
3327 // The machine layer owns the roster...
3328 std::fs::write(
3329 &machine,
3330 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3331 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3332 )
3333 .unwrap();
3334 // ...and the project layer only states what is repo-specific, plus a
3335 // `[vars]` value interpolated into a command.
3336 std::fs::write(
3337 &project,
3338 "[vars]\ncache = \"/shared\"\n\n\
3339 [graph]\ncandidates = 2\n\n\
3340 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3341 )
3342 .unwrap();
3343
3344 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3345 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3346 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3347 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3348 assert_eq!(
3349 cfg.verify.gate,
3350 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3351 );
3352 // The rendered command is where the cache path is read back from.
3353 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3354 }
3355
3356 #[test]
3357 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3358 // An operator who writes no `[graph]` timeout keys at all must still
3359 // land on the hour, not on the five/fifteen minutes this turn used
3360 // to hardcode before it read from config.
3361 let g = Graph::default();
3362 assert_eq!(g.timeout_talk, 3600);
3363
3364 let dir = tempfile::tempdir().unwrap();
3365 let path = dir.path().join("magi.toml");
3366 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3367 let cfg = Config::load(&path).expect("must load without timeout_talk set");
3368 assert_eq!(cfg.graph.timeout_talk, 3600);
3369 }
3370
3371 #[test]
3372 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3373 let dir = tempfile::tempdir().unwrap();
3374 let path = dir.path().join("magi.toml");
3375 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3376 let cfg = Config::load(&path).expect("must load");
3377 assert_eq!(cfg.graph.timeout_talk, 120);
3378 }
3379
3380 #[test]
3381 fn the_disk_defaults_are_the_measurements_made_up_front() {
3382 let cfg = Config::default();
3383 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3384 assert!(cfg.disk.auto_fold);
3385 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
3386 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
3387 }
3388
3389 #[test]
3390 fn an_unset_disk_section_is_the_safe_default() {
3391 let dir = tempfile::tempdir().unwrap();
3392 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
3393 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
3394 assert_eq!(cfg.disk, Disk::default());
3395 }
3396
3397 #[test]
3398 fn env_is_available_to_templates_with_a_default() {
3399 let dir = tempfile::tempdir().unwrap();
3400 let path = dir.path().join("magi.toml");
3401 // teravars ships no `env`; magi adds it, and the `default` filter has
3402 // to cover the unset case or every machine would need the variable.
3403 //
3404 // Deliberately no named variable: `env` is keyed by the exact spelling
3405 // the OS reports, and Windows says `Path` where POSIX says `PATH`, so a
3406 // test asserting `env.PATH` passes on one runner and fails on another.
3407 // The map's non-emptiness is the platform-neutral claim.
3408 std::fs::write(
3409 &path,
3410 "[verify]\n\
3411 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3412 \"populated={{ env | length > 0 }}\"]\n",
3413 )
3414 .unwrap();
3415 let cfg = Config::load(&path).expect("env lookup must render");
3416 assert_eq!(cfg.verify.gate[0], "cache=fallback");
3417 assert_eq!(cfg.verify.gate[1], "populated=true");
3418 }
3419
3420 #[test]
3421 fn a_broken_template_names_the_file() {
3422 let dir = tempfile::tempdir().unwrap();
3423 let path = dir.path().join("magi.toml");
3424 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
3425 let err = Config::load(&path).expect_err("must not silently ignore");
3426 assert!(err.to_string().contains("teravars"), "{err}");
3427 }
3428
3429 #[test]
3430 fn tera_syntax_in_comments_is_inert() {
3431 // teravars >= 0.2.2 strips `#` comments before Tera sees the file, so a
3432 // comment may quote template syntax without rendering. Before 0.2.2 this
3433 // load failed: the commented-out braces reached the template parser.
3434 let dir = tempfile::tempdir().unwrap();
3435 let path = dir.path().join("magi.toml");
3436 std::fs::write(
3437 &path,
3438 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
3439 [graph]\ncandidates = 2\n",
3440 )
3441 .unwrap();
3442 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
3443 assert_eq!(cfg.graph.implementers, 2);
3444 }
3445
3446 #[test]
3447 fn opencode_defaults_to_file_delivery() {
3448 let mut s = spec("oc");
3449 s.kind = AgentKind::Opencode;
3450 assert_eq!(s.delivery(), Delivery::File);
3451 s.prompt_delivery = Some(Delivery::Argv);
3452 assert_eq!(s.delivery(), Delivery::Argv);
3453 }
3454 #[test]
3455 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
3456 // Both default on, and that pair is the safety property: `land` takes
3457 // over the watching an operator was doing by hand, `land_approval`
3458 // keeps the irreversible step a human decision. An unattended merge
3459 // needs BOTH flipped, which has to be chosen deliberately twice.
3460 let g = Graph::default();
3461 assert!(
3462 g.land,
3463 "stopping at an open PR left the watching to a human"
3464 );
3465 assert!(
3466 g.land_approval,
3467 "on-by-default land is only defensible while this is also on"
3468 );
3469 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
3470 assert!(
3471 g.hold_contested_merge,
3472 "a contested hand-off must still reach a human when approvals are off"
3473 );
3474 }
3475 #[test]
3476 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
3477 // teravars appends arrays. For an ordered list of seats, or an argv,
3478 // the concatenation is something neither file says - and the operator
3479 // pays for the extra seats by the token.
3480 let dir = tempfile::tempdir().unwrap();
3481 let machine = dir.path().join("machine.toml");
3482 let repo = dir.path().join("magi.toml");
3483 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
3484 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
3485
3486 let err = Config::load_layers(&[machine.clone(), repo.clone()])
3487 .expect_err("two layers naming one array must not merge silently")
3488 .to_string();
3489 assert!(err.contains("roles.implementers"), "{err}");
3490 // Both files are named: the fix is to delete one of them, and the
3491 // operator has to know which two to choose between.
3492 assert!(err.contains("machine.toml"), "{err}");
3493 assert!(err.contains("magi.toml"), "{err}");
3494 }
3495
3496 #[test]
3497 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
3498 // The split the layering exists for: state a preference machine-wide,
3499 // let the repository own its own lists.
3500 let dir = tempfile::tempdir().unwrap();
3501 let machine = dir.path().join("machine.toml");
3502 let repo = dir.path().join("magi.toml");
3503 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
3504 std::fs::write(
3505 &repo,
3506 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
3507 [roles]\nimplementers = [\"oc\"]\n",
3508 )
3509 .unwrap();
3510
3511 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
3512 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
3513 assert_eq!(cfg.roles.implementers, ["oc"]);
3514 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
3515 }
3516
3517 #[test]
3518 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
3519 // The `editorconfig-checker` distribution problem: a shared layer
3520 // wants to add a gate command without erasing the repository's own.
3521 let dir = tempfile::tempdir().unwrap();
3522 let machine = dir.path().join("machine.toml");
3523 let repo = dir.path().join("magi.toml");
3524 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3525 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3526
3527 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3528 assert_eq!(
3529 cfg.verify.gate,
3530 [
3531 "editorconfig-checker".to_owned(),
3532 "cargo make check".to_owned()
3533 ],
3534 "low-priority (machine) command first, high-priority (repo) command after"
3535 );
3536 }
3537
3538 fn load_one(body: &str) -> Result<Config> {
3539 let dir = tempfile::tempdir().unwrap();
3540 let path = dir.path().join("magi.toml");
3541 std::fs::write(&path, body).unwrap();
3542 Config::load_layers(&[path])
3543 }
3544
3545 #[test]
3546 fn worktree_setup_defaults_to_empty_and_parses_steps() {
3547 assert!(Config::default().worktree.setup.is_empty());
3548 let cfg = load_one(
3549 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
3550 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
3551 )
3552 .unwrap();
3553 assert_eq!(cfg.worktree.setup.len(), 3);
3554 assert!(cfg.worktree.setup[1].optional);
3555 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
3556 }
3557
3558 #[test]
3559 fn worktree_setup_rejects_malformed_steps() {
3560 for bad in [
3561 "{ copy = \"a\", run = \"b\" }",
3562 "{ optional = true }",
3563 "{ copy = \"a -> ../b\" }",
3564 "{ copy = \"a -> /abs\" }",
3565 "{ copy = \"a -> .git/config\" }",
3566 "{ run = \"b\", optional = true }",
3567 "{ copy = \"a\", timeout_secs = 3 }",
3568 "{ run = \"b\", bogus = 1 }",
3569 ] {
3570 let body = format!("[worktree]\nsetup = [{bad}]\n");
3571 assert!(load_one(&body).is_err(), "{bad}");
3572 }
3573 }
3574
3575 #[test]
3576 fn worktree_setup_in_two_layers_is_refused() {
3577 let dir = tempfile::tempdir().unwrap();
3578 let machine = dir.path().join("machine.toml");
3579 let repo = dir.path().join("magi.toml");
3580 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
3581 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
3582 assert!(Config::load_layers(&[machine, repo]).is_err());
3583 }
3584
3585 #[test]
3586 fn starter_toml_documents_worktree_setup() {
3587 let starter = Config::starter_toml();
3588 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
3589 // The commented example must be valid once uncommented.
3590 let body = starter.replace("# [worktree]", "[worktree]");
3591 let mut out = String::new();
3592 let mut live = false;
3593 for line in body.lines() {
3594 if line == "[worktree]" {
3595 live = true;
3596 } else if live && !line.starts_with("# ") {
3597 live = false;
3598 }
3599 out.push_str(&if live {
3600 line.replacen("# ", "", 1)
3601 } else {
3602 line.to_owned()
3603 });
3604 out.push('\n');
3605 }
3606 let cfg = load_one(&out).expect("uncommented example loads");
3607 assert_eq!(cfg.worktree.setup.len(), 3);
3608 }
3609
3610 #[test]
3611 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
3612 let dir = tempfile::tempdir().unwrap();
3613 let machine = dir.path().join("machine.toml");
3614 let repo = dir.path().join("magi.toml");
3615 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
3616 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
3617
3618 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3619 assert_eq!(
3620 cfg.verify.e2e,
3621 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
3622 );
3623 }
3624
3625 #[test]
3626 fn two_layers_declaring_repos_roots_are_both_scanned() {
3627 let dir = tempfile::tempdir().unwrap();
3628 let machine = dir.path().join("machine.toml");
3629 let repo = dir.path().join("magi.toml");
3630 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
3631 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
3632
3633 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3634 assert_eq!(
3635 cfg.repos.roots,
3636 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
3637 );
3638 }
3639
3640 #[test]
3641 fn duplicate_gate_commands_across_layers_both_run() {
3642 // Dropping the duplicate would be a silent surprise; the operator
3643 // sees a slower gate, never a missing one.
3644 let dir = tempfile::tempdir().unwrap();
3645 let machine = dir.path().join("machine.toml");
3646 let repo = dir.path().join("magi.toml");
3647 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3648 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
3649
3650 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3651 assert_eq!(
3652 cfg.verify.gate,
3653 ["same-command".to_owned(), "same-command".to_owned()]
3654 );
3655 }
3656
3657 #[test]
3658 fn notify_command_is_still_refused_across_two_layers() {
3659 // An argv, not a set: concatenating two of them is not a program.
3660 let dir = tempfile::tempdir().unwrap();
3661 let machine = dir.path().join("machine.toml");
3662 let repo = dir.path().join("magi.toml");
3663 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
3664 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
3665
3666 let err = Config::load_layers(&[machine.clone(), repo.clone()])
3667 .expect_err("an argv split across layers must not concatenate")
3668 .to_string();
3669 assert!(err.contains("notify.command"), "{err}");
3670 assert!(err.contains("machine.toml"), "{err}");
3671 assert!(err.contains("magi.toml"), "{err}");
3672 }
3673
3674 #[test]
3675 fn one_layer_declaring_verify_gate_runs_unchanged() {
3676 // The classification must not change behaviour for the configuration
3677 // this very repository has today: exactly one layer names the gate.
3678 let dir = tempfile::tempdir().unwrap();
3679 let path = dir.path().join("magi.toml");
3680 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3681
3682 let cfg = Config::load(&path).expect("single layer must still load");
3683 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
3684 }
3685
3686 #[test]
3687 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
3688 let dir = tempfile::tempdir().unwrap();
3689 let machine = dir.path().join("machine.toml");
3690 let repo = dir.path().join("magi.toml");
3691 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3692 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3693 let paths = vec![machine.clone(), repo.clone()];
3694
3695 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
3696 let described =
3697 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
3698 assert!(described.contains("editorconfig-checker && cargo make check"));
3699 assert!(
3700 described.contains(&machine.display().to_string()),
3701 "{described}"
3702 );
3703 assert!(
3704 described.contains(&repo.display().to_string()),
3705 "{described}"
3706 );
3707
3708 // A single contributing layer stays the plain one-line summary.
3709 let single = vec![repo.clone()];
3710 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
3711 let solo_described =
3712 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
3713 assert_eq!(solo_described, "cargo make check");
3714 }
3715
3716 mod remote_layers {
3717 use super::*;
3718
3719 fn git(dir: &Path, args: &[&str]) {
3720 use crate::proc::Quiet as _;
3721 let out = std::process::Command::new("git")
3722 .args(args)
3723 .quiet()
3724 .current_dir(dir)
3725 .output()
3726 .unwrap();
3727 assert!(out.status.success(), "git {args:?}: {out:?}");
3728 }
3729
3730 /// A checkout whose origin/main carries `remote` as magi.toml and whose
3731 /// working tree carries `disk`.
3732 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
3733 let tmp = tempfile::tempdir().unwrap();
3734 let bare = tmp.path().join("o.git");
3735 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
3736 let repo = tmp.path().join("repo");
3737 std::fs::create_dir_all(&repo).unwrap();
3738 git(&repo, &["init", "-b", "trunk"]);
3739 git(&repo, &["config", "user.name", "t"]);
3740 git(&repo, &["config", "user.email", "t@example.com"]);
3741 std::fs::write(repo.join("magi.toml"), remote).unwrap();
3742 git(&repo, &["add", "-A"]);
3743 git(&repo, &["commit", "-m", "x"]);
3744 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
3745 git(&repo, &["push", "origin", "trunk"]);
3746 git(&repo, &["fetch", "origin"]);
3747 git(&repo, &["remote", "set-head", "origin", "trunk"]);
3748 std::fs::write(repo.join("magi.toml"), disk).unwrap();
3749 (tmp, repo)
3750 }
3751
3752 #[test]
3753 fn reads_the_remote_blob_not_the_working_tree() {
3754 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3755 let (cfg, _) = Config::discover(&repo, None).unwrap();
3756 assert_eq!(cfg.graph.implementers, 2);
3757 }
3758
3759 #[test]
3760 fn detached_head_still_reads_the_remote() {
3761 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3762 git(&repo, &["checkout", "--detach"]);
3763 let (cfg, _) = Config::discover(&repo, None).unwrap();
3764 assert_eq!(cfg.graph.implementers, 2);
3765 }
3766
3767 #[test]
3768 fn a_missing_ref_is_an_error_not_a_fallback() {
3769 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
3770 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
3771 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
3772 assert!(err.contains("origin"), "{err}");
3773 }
3774
3775 #[test]
3776 fn merge_base_in_the_checkout_locates_the_ref() {
3777 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
3778 assert!(Config::discover(&repo, None).is_err());
3779 }
3780
3781 #[test]
3782 fn the_magi_dir_layer_is_read_too() {
3783 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3784 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3785 std::fs::create_dir_all(repo.join(".magi")).unwrap();
3786 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
3787 git(&repo, &["add", "-A"]);
3788 git(&repo, &["commit", "-m", "y"]);
3789 git(&repo, &["push", "origin", "trunk"]);
3790 git(&repo, &["fetch", "origin"]);
3791 let (cfg, layers) = Config::discover(&repo, None).unwrap();
3792 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
3793 assert_eq!(layers.len(), 2);
3794 }
3795
3796 #[test]
3797 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
3798 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
3799 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
3800 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
3801 git(&repo, &["add", "-A"]);
3802 git(&repo, &["commit", "-m", "inc"]);
3803 git(&repo, &["push", "origin", "trunk"]);
3804 git(&repo, &["fetch", "origin"]);
3805 // The working tree's copy differs and must not be used.
3806 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
3807 let (cfg, _) = Config::discover(&repo, None).unwrap();
3808 assert_eq!(cfg.graph.implementers, 2);
3809 }
3810
3811 #[test]
3812 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
3813 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
3814 let m = t.path().join("machine.toml");
3815 std::fs::write(
3816 &m,
3817 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
3818 )
3819 .unwrap();
3820 let (remote, base) = {
3821 let probe = probe_merge(&m, &repo).unwrap();
3822 (probe.remote, probe.base)
3823 };
3824 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
3825 }
3826
3827 #[test]
3828 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
3829 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3830 let m = t.path().join("machine.toml");
3831 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
3832 let probe = probe_merge(&m, &repo).unwrap();
3833 assert_eq!(probe.base.as_deref(), Some("repo"));
3834 }
3835
3836 #[test]
3837 fn every_include_form_is_recognised() {
3838 assert!(declares_include("include = [\"a.toml\"]\n"));
3839 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
3840 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
3841 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
3842 assert!(!declares_include("[graph]\ncandidates = 2\n"));
3843 }
3844
3845 #[test]
3846 fn an_explicit_config_is_read_as_named() {
3847 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3848 let own = t.path().join("own.toml");
3849 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
3850 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
3851 assert_eq!(cfg.graph.implementers, 4);
3852 }
3853
3854 #[test]
3855 fn discover_fetched_fails_when_the_fetch_does() {
3856 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3857 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
3858 let rt = tokio::runtime::Builder::new_current_thread()
3859 .enable_all()
3860 .build()
3861 .unwrap();
3862 let err = rt
3863 .block_on(Config::discover_fetched(&repo, None))
3864 .unwrap_err();
3865 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
3866 }
3867
3868 #[test]
3869 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
3870 // Never-fetched remote + followRemoteHEAD=never: fetch creates
3871 // origin/trunk but not origin/HEAD, which discovery then re-reads.
3872 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
3873 git(&repo, &["remote", "set-head", "origin", "-d"]);
3874 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
3875 git(
3876 &repo,
3877 &["config", "remote.origin.followRemoteHEAD", "never"],
3878 );
3879 let rt = tokio::runtime::Builder::new_current_thread()
3880 .enable_all()
3881 .build()
3882 .unwrap();
3883 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
3884 assert_eq!(cfg.graph.implementers, 2);
3885 }
3886
3887 #[test]
3888 fn a_non_git_directory_reads_its_files() {
3889 let dir = tempfile::tempdir().unwrap();
3890 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
3891 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
3892 assert_eq!(cfg.graph.implementers, 4);
3893 }
3894 }
3895}