1use std::collections::BTreeMap;
44use std::path::{Path, PathBuf};
45
46use anyhow::{Context as _, Result, bail};
47use serde::{Deserialize, Serialize};
48
49#[derive(Debug, thiserror::Error)]
52#[error("{stage}: {target}")]
53pub(crate) struct ConfigFailure {
54 pub(crate) stage: &'static str,
55 pub(crate) target: String,
56}
57
58impl ConfigFailure {
59 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
60 let stage = match error {
61 teravars::Error::Io(_) => "config-read",
62 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
63 teravars::Error::Render(_) => "config-template",
64 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
65 "config-include"
66 }
67 _ => "config-render",
68 };
69 Self::layers(stage, paths)
70 }
71
72 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
73 let targets: Vec<_> = paths
74 .iter()
75 .map(|path| {
76 path.ancestors()
79 .find(|p| p.join(REPO_MARKER).is_file())
80 .and_then(|root| path.strip_prefix(root).ok())
81 .unwrap_or(path)
82 .to_string_lossy()
83 .into_owned()
84 })
85 .collect();
86 Self {
87 stage,
88 target: serde_json::to_string(&targets).expect("config paths"),
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
95#[serde(rename_all = "lowercase")]
96pub enum AgentKind {
97 Claude,
99 Opencode,
101 Antigravity,
105 Codex,
109 Omp,
115 Command,
117}
118
119impl AgentKind {
120 pub fn program(self) -> Option<&'static str> {
122 match self {
123 Self::Claude => Some("claude"),
124 Self::Opencode => Some("opencode"),
125 Self::Antigravity => Some("agy"),
126 Self::Codex => Some("codex"),
127 Self::Omp => Some("omp"),
128 Self::Command => None,
129 }
130 }
131
132 pub fn as_str(self) -> &'static str {
134 match self {
135 Self::Claude => "claude",
136 Self::Opencode => "opencode",
137 Self::Antigravity => "antigravity",
138 Self::Codex => "codex",
139 Self::Omp => "omp",
140 Self::Command => "command",
141 }
142 }
143
144 pub const ALL: [Self; 6] = [
152 Self::Claude,
153 Self::Opencode,
154 Self::Antigravity,
155 Self::Codex,
156 Self::Omp,
157 Self::Command,
158 ];
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
163#[serde(rename_all = "lowercase")]
164pub enum Delivery {
165 Stdin,
167 Argv,
169 File,
171}
172
173#[derive(Debug, Clone, Deserialize, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct AgentSpec {
177 pub id: String,
179 pub kind: AgentKind,
181 #[serde(default)]
183 pub model: Option<String>,
184 #[serde(default)]
187 pub command: Vec<String>,
188 #[serde(default)]
190 pub extra_args: Vec<String>,
191 #[serde(default)]
193 pub env: BTreeMap<String, String>,
194 #[serde(default)]
196 pub prompt_delivery: Option<Delivery>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub max_turn_secs: Option<u64>,
201}
202
203impl AgentSpec {
204 pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
206 self.max_turn_secs.map_or(budget, |secs| {
207 budget.min(std::time::Duration::from_secs(secs))
208 })
209 }
210
211 pub fn delivery(&self) -> Delivery {
217 self.prompt_delivery.unwrap_or(match self.kind {
218 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
219 AgentKind::Codex => Delivery::Stdin,
223 AgentKind::Omp => Delivery::Stdin,
227 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
228 })
229 }
230
231 pub fn display(&self) -> String {
233 match &self.model {
234 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
235 None => format!("{} ({})", self.id, self.kind.as_str()),
236 }
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
247#[serde(untagged)]
248pub enum AgentChoice {
249 One(String),
251 Chain(Vec<String>),
253}
254
255impl AgentChoice {
256 pub fn ids(&self) -> Vec<&str> {
258 let all: Vec<&str> = match self {
259 Self::One(id) => vec![id.as_str()],
260 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
261 };
262 all.into_iter()
263 .map(str::trim)
264 .filter(|id| !id.is_empty())
265 .collect()
266 }
267
268 pub fn primary(&self) -> Option<&str> {
270 self.ids().into_iter().next()
271 }
272}
273
274impl From<&str> for AgentChoice {
275 fn from(id: &str) -> Self {
276 Self::One(id.to_owned())
277 }
278}
279
280pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
282 choice.and_then(AgentChoice::primary)
283}
284
285#[derive(Debug, Clone, Default, Deserialize, Serialize)]
288#[serde(deny_unknown_fields, default)]
289pub struct Roles {
290 pub implementers: Vec<String>,
292 pub judges: Vec<String>,
294 pub reviewers: Vec<String>,
296 pub fixer: Option<AgentChoice>,
305 pub chatter: Option<AgentChoice>,
319 pub dupes_judge: Option<AgentChoice>,
323 pub conductor: Option<AgentChoice>,
336 pub advisors: Vec<String>,
347 pub synthesizer: Option<AgentChoice>,
360 pub language_judge: Option<AgentChoice>,
369}
370
371#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
376#[serde(rename_all = "snake_case")]
377pub enum EditingNetwork {
378 Restricted,
381 #[default]
383 Enabled,
384}
385
386#[derive(Debug, Clone, Deserialize, Serialize)]
388#[serde(deny_unknown_fields, default)]
389pub struct Graph {
390 pub editing_network: EditingNetwork,
392 pub github_text_guard: bool,
394 pub github_language: String,
400 #[serde(alias = "candidates")]
432 pub implementers: usize,
433 #[serde(default)]
435 pub selected_implementer: Option<String>,
436 pub judges: usize,
438 pub deliberate_rounds: usize,
440 pub reviewers: usize,
448 pub review_rounds: usize,
450 pub gate_fix_rounds: usize,
456 pub max_parallel: usize,
458 pub language: String,
460 pub sessions: bool,
468 pub timeout_implement: u64,
470 pub timeout_judge: u64,
472 pub timeout_review: u64,
474 pub timeout_verify: Option<u64>,
483 pub timeout_fix: u64,
485 pub timeout_talk: u64,
493 pub timeout_resource_wait: u64,
502 pub retries: usize,
504 pub worktree_root: Option<PathBuf>,
506 pub land: bool,
519 pub land_rounds: usize,
521 pub rerun_flaky_checks: bool,
529 pub land_approval: bool,
540 pub hold_contested_merge: bool,
551 pub question_routing: bool,
556 pub file_followups: bool,
563 pub release_deputy_followups: bool,
571 pub answer_timeout: u64,
575 pub incomplete_review: IncompleteReviewPolicy,
578 pub e2e_every_round: bool,
596 pub advise: bool,
610 pub advisors: usize,
615 pub graft_runner_up: bool,
624}
625
626impl Default for Graph {
627 fn default() -> Self {
628 Self {
629 editing_network: EditingNetwork::default(),
630 github_text_guard: true,
631 github_language: "en".into(),
632 implementers: 1,
633 selected_implementer: None,
634 judges: 3,
635 deliberate_rounds: 1,
636 reviewers: 3,
637 review_rounds: 6,
638 gate_fix_rounds: 1,
639 max_parallel: 4,
640 language: "en".to_owned(),
641 sessions: true,
642 timeout_implement: 3600,
643 timeout_judge: 1200,
644 timeout_review: 1200,
645 timeout_verify: None,
646 timeout_fix: 1800,
647 timeout_talk: 3600,
648 timeout_resource_wait: 1800,
649 retries: 1,
650 worktree_root: None,
651 land: true,
652 land_rounds: 4,
653 rerun_flaky_checks: true,
654 land_approval: true,
655 hold_contested_merge: true,
656 question_routing: true,
657 file_followups: true,
658 release_deputy_followups: true,
659 answer_timeout: 86_400,
660 incomplete_review: IncompleteReviewPolicy::Block,
661 e2e_every_round: false,
662 advise: true,
663 advisors: 3,
664 graft_runner_up: true,
665 }
666 }
667}
668
669impl Graph {
670 pub fn verify_timeout(&self) -> u64 {
674 self.timeout_verify.unwrap_or(self.timeout_review)
675 }
676
677 pub fn language_gate(&self) -> bool {
680 self.github_text_guard && self.github_english()
681 }
682
683 pub fn github_english(&self) -> bool {
685 crate::lang::is_english(&self.github_language)
686 }
687}
688
689#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
696#[serde(rename_all = "lowercase")]
697pub enum IncompleteReviewPolicy {
698 Block,
702 Warn,
707}
708
709#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
711#[serde(rename_all = "lowercase")]
712pub enum LeakPolicy {
713 Warn,
715 Redact,
717 Fail,
719}
720
721#[derive(Debug, Clone, Deserialize, Serialize)]
728#[serde(deny_unknown_fields, default)]
729pub struct Blind {
730 pub commit_msg_hook: bool,
733 pub strip_lines: Vec<String>,
737 pub vendor_tokens: Vec<String>,
739 pub on_leak: LeakPolicy,
741 pub seed: Option<u64>,
744}
745
746impl Default for Blind {
747 fn default() -> Self {
748 Self {
749 commit_msg_hook: true,
750 strip_lines: [
751 "Co-Authored-By:",
752 "Signed-off-by:",
753 "Assisted-by:",
754 "Generated-by:",
755 "Generated with",
756 "\u{1f916}",
757 ]
758 .iter()
759 .map(|s| (*s).to_owned())
760 .collect(),
761 vendor_tokens: [
762 "claude",
763 "anthropic",
764 "codex",
765 "openai",
766 "chatgpt",
767 "gemini",
768 "grok",
769 "xai",
770 "copilot",
771 "opencode",
772 "qoder",
773 "cursor",
774 "\u{1f916}",
775 ]
776 .iter()
777 .map(|s| (*s).to_owned())
778 .collect(),
779 on_leak: LeakPolicy::Warn,
780 seed: None,
781 }
782 }
783}
784
785#[derive(Debug, Clone, Default, Deserialize, Serialize)]
787#[serde(deny_unknown_fields, default)]
788pub struct Verify {
789 pub e2e: Vec<String>,
792 pub gate: Vec<String>,
794 #[serde(default)]
803 pub pre_gate: Vec<String>,
804 pub shell: Option<Vec<String>>,
807}
808
809impl Verify {
810 pub fn cache_dir(&self) -> Option<PathBuf> {
816 self.e2e
817 .iter()
818 .chain(self.gate.iter())
819 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
820 }
821
822 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
825 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
826 crate::cache::extract_manifest_paths(&all)
827 }
828}
829
830#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
832#[serde(deny_unknown_fields, default)]
833pub struct Worktree {
834 pub setup: Vec<SetupStep>,
837}
838
839#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
841#[serde(deny_unknown_fields, default)]
842pub struct SetupStep {
843 pub copy: Option<String>,
846 pub optional: bool,
848 pub run: Option<String>,
850 pub timeout_secs: Option<u64>,
853}
854
855impl Worktree {
856 pub fn validate(&self) -> Result<()> {
858 for (i, step) in self.setup.iter().enumerate() {
859 let n = i + 1;
860 match (&step.copy, &step.run) {
861 (Some(c), None) => {
862 if step.timeout_secs.is_some() {
863 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
864 }
865 crate::worktree_setup::validate_copy(c)
866 .with_context(|| format!("[worktree] setup step {n}"))?;
867 }
868 (None, Some(r)) => {
869 if r.trim().is_empty() {
870 bail!("[worktree] setup step {n}: `run` is empty");
871 }
872 if step.optional {
873 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
874 }
875 }
876 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
877 }
878 }
879 Ok(())
880 }
881}
882
883#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
893#[serde(deny_unknown_fields, default)]
894pub struct Disk {
895 pub min_free_bytes: u64,
904 pub auto_fold: bool,
910 pub fold_grace_secs: u64,
918 pub cache_limit_bytes: u64,
930 pub worktree_limit_bytes: u64,
932 pub worktree_reclaim_bytes: u64,
934 pub retained_attempt_limit: usize,
938}
939
940impl Default for Disk {
941 fn default() -> Self {
942 Self {
943 min_free_bytes: 8 * 1024 * 1024 * 1024,
944 auto_fold: true,
945 fold_grace_secs: 6 * 60 * 60,
946 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
947 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
948 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
949 retained_attempt_limit: 8,
950 }
951 }
952}
953
954#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
956#[serde(rename_all = "lowercase")]
957pub enum MergeMode {
958 None,
961 Local,
964 Pr,
968}
969
970#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
984#[serde(rename_all = "lowercase")]
985pub enum MergeStyle {
986 #[default]
991 Merge,
992 Squash,
998 Rebase,
1004}
1005
1006#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1008#[serde(rename_all = "lowercase")]
1009pub enum MergeCi {
1010 #[default]
1012 Expected,
1013 None,
1015}
1016
1017impl MergeCi {
1018 pub fn expectation(self) -> crate::land::CiExpectation {
1020 match self {
1021 Self::Expected => crate::land::CiExpectation::Expected,
1022 Self::None => crate::land::CiExpectation::Absent,
1023 }
1024 }
1025}
1026
1027#[derive(Debug, Clone, Deserialize, Serialize)]
1029#[serde(deny_unknown_fields, default)]
1030pub struct Merge {
1031 pub mode: MergeMode,
1034 pub ci: MergeCi,
1036 pub base: Option<String>,
1038 pub style: MergeStyle,
1041 pub remote: String,
1043 pub release_bump: bool,
1056}
1057
1058impl Default for Merge {
1059 fn default() -> Self {
1060 Self {
1061 mode: MergeMode::None,
1062 ci: MergeCi::Expected,
1063 base: None,
1064 style: MergeStyle::default(),
1065 remote: "origin".to_owned(),
1066 release_bump: true,
1067 }
1068 }
1069}
1070
1071#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1073#[serde(rename_all = "lowercase")]
1074pub enum UpdateMode {
1075 Off,
1077 Notify,
1080 Install,
1082}
1083
1084#[derive(Debug, Clone, Deserialize, Serialize)]
1086#[serde(deny_unknown_fields, default)]
1087pub struct Update {
1088 pub mode: UpdateMode,
1090 pub interval: Option<String>,
1092 pub auto_restart: bool,
1094}
1095
1096impl Default for Update {
1097 fn default() -> Self {
1098 Self {
1099 mode: UpdateMode::Notify,
1100 interval: None,
1101 auto_restart: false,
1102 }
1103 }
1104}
1105
1106#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1108#[serde(rename_all = "lowercase")]
1109pub enum ReleaseMode {
1110 #[default]
1113 Actions,
1114 Local,
1119}
1120
1121#[derive(Debug, Clone, Deserialize, Serialize)]
1123#[serde(deny_unknown_fields, default)]
1124pub struct Release {
1125 pub mode: ReleaseMode,
1128 pub commands: Vec<String>,
1135 pub timeout_minutes: u64,
1137 pub version_files: Vec<VersionFile>,
1145}
1146
1147#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1149#[serde(rename_all = "lowercase")]
1150pub enum VersionKind {
1151 Cargo,
1153 Json,
1155}
1156
1157#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1159#[serde(deny_unknown_fields)]
1160pub struct VersionFile {
1161 pub path: String,
1163 pub kind: VersionKind,
1165}
1166
1167impl Default for Release {
1168 fn default() -> Self {
1169 Self {
1170 mode: ReleaseMode::Actions,
1171 commands: Vec::new(),
1172 timeout_minutes: 30,
1173 version_files: Vec::new(),
1174 }
1175 }
1176}
1177
1178impl Release {
1179 pub fn validate(&self) -> Result<()> {
1181 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1182 }
1183
1184 pub fn is_local(&self) -> bool {
1186 self.mode == ReleaseMode::Local
1187 }
1188}
1189
1190#[derive(Debug, Clone, Deserialize, Serialize)]
1192#[serde(try_from = "CoordinationFields")]
1193pub struct Coordination {
1194 pub contract_file: String,
1196 pub contract_token: String,
1198 pub lock_file: String,
1200}
1201
1202#[derive(Deserialize, Default)]
1203#[serde(deny_unknown_fields, default)]
1204struct CoordinationFields {
1205 contract_file: String,
1206 contract_token: String,
1207 lock_file: String,
1208}
1209
1210impl TryFrom<CoordinationFields> for Coordination {
1211 type Error = anyhow::Error;
1212
1213 fn try_from(fields: CoordinationFields) -> Result<Self> {
1214 for (key, name) in [
1215 ("coordination.contract_file", &fields.contract_file),
1216 ("coordination.lock_file", &fields.lock_file),
1217 ] {
1218 if name.trim().is_empty()
1219 || name != name.trim()
1220 || name == "."
1221 || name.contains("..")
1222 || name.contains(['/', '\\', ':', '\0'])
1223 {
1224 bail!(
1225 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1226 );
1227 }
1228 }
1229 let token = &fields.contract_token;
1230 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1231 bail!(
1232 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1233 );
1234 }
1235 Ok(Self {
1236 contract_file: fields.contract_file,
1237 contract_token: fields.contract_token,
1238 lock_file: fields.lock_file,
1239 })
1240 }
1241}
1242
1243#[cfg(test)]
1244pub(crate) fn test_coordination() -> Option<Coordination> {
1245 Some(Coordination {
1246 contract_file: "updater.contract".into(),
1247 contract_token: "test-protocol-v1".into(),
1248 lock_file: "updater.lock".into(),
1249 })
1250}
1251
1252#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1254#[serde(deny_unknown_fields, default)]
1255pub struct Config {
1256 pub coordination: Option<Coordination>,
1258 pub agents: Vec<AgentSpec>,
1260 pub roles: Roles,
1262 pub graph: Graph,
1264 pub blind: Blind,
1266 pub verify: Verify,
1268 pub worktree: Worktree,
1270 pub disk: Disk,
1272 pub merge: Merge,
1274 pub update: Update,
1276 pub prompts: Prompts,
1278 pub notify: Notify,
1280 pub repos: Repos,
1283 pub talk: Talk,
1285 pub daemon: Daemon,
1287 pub release: Release,
1289 pub context_windows: BTreeMap<String, u64>,
1292}
1293
1294const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1304 ("claude-opus-4", 200_000),
1305 ("claude-sonnet-4", 200_000),
1306 ("claude-haiku-4", 200_000),
1307 ("claude-3", 200_000),
1308 ("opus", 200_000),
1309 ("sonnet", 200_000),
1310 ("haiku", 200_000),
1311 ("gpt-5", 400_000),
1312 ("gpt-4.1", 1_000_000),
1313 ("gpt-4o", 128_000),
1314 ("o3", 200_000),
1315 ("o4-mini", 200_000),
1316 ("gemini-2.5", 1_000_000),
1317 ("deepseek", 128_000),
1318];
1319
1320impl Config {
1321 pub fn context_window(&self, model: &str) -> Option<u64> {
1326 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1327 let mut best: Option<(usize, u64)> = None;
1328 for (key, window) in entries {
1329 if key == model {
1330 return Some(window);
1331 }
1332 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1333 best = Some((key.len(), window));
1334 }
1335 }
1336 best.map(|(_, w)| w)
1337 }
1338 lookup(
1339 model,
1340 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1341 )
1342 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1343 }
1344}
1345
1346#[derive(Debug, Clone, Deserialize, Serialize)]
1356#[serde(deny_unknown_fields, default)]
1357pub struct Daemon {
1358 pub max_concurrent_runs: usize,
1379 pub pause_for_interrupts: bool,
1395 pub max_deputies: usize,
1402 pub release_stall_minutes: u64,
1409}
1410
1411impl Default for Daemon {
1412 fn default() -> Self {
1413 Self {
1414 max_concurrent_runs: 1,
1415 pause_for_interrupts: false,
1416 max_deputies: 2,
1417 release_stall_minutes: 60,
1418 }
1419 }
1420}
1421
1422#[derive(Debug, Clone, Deserialize, Serialize)]
1434#[serde(deny_unknown_fields, default)]
1435pub struct Repos {
1436 pub roots: Vec<PathBuf>,
1440 pub scan_ttl: u64,
1447 pub fetch_interval: u64,
1452}
1453
1454impl Default for Repos {
1455 fn default() -> Self {
1456 Self {
1457 roots: Vec::new(),
1458 scan_ttl: 86_400,
1459 fetch_interval: 600,
1460 }
1461 }
1462}
1463
1464#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1480#[serde(deny_unknown_fields, default)]
1481pub struct Prompts {
1482 pub all: String,
1484 pub implement: String,
1486 pub judge: String,
1488 pub review: String,
1490 pub fix: String,
1492}
1493
1494impl Prompts {
1495 pub fn overlay(&self, node: &str) -> Option<String> {
1500 let specific = match node {
1501 "implement" => &self.implement,
1502 "judge" | "vote" | "deliberate" => &self.judge,
1503 "review" => &self.review,
1504 "fix" => &self.fix,
1505 _ => "",
1506 };
1507 let mut parts: Vec<&str> = Vec::new();
1508 for p in [self.all.trim(), specific.trim()] {
1509 if !p.is_empty() {
1510 parts.push(p);
1511 }
1512 }
1513 if parts.is_empty() {
1514 return None;
1515 }
1516 Some(parts.join("\n\n"))
1517 }
1518}
1519
1520#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1527#[serde(deny_unknown_fields, default)]
1528pub struct Notify {
1529 pub command: Vec<String>,
1532}
1533
1534#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1536#[serde(deny_unknown_fields, default)]
1537pub struct Talk {
1538 pub allow_write: bool,
1547 pub personas: Vec<PersonaSpec>,
1552 pub operator_name: Option<String>,
1556}
1557
1558pub const OPERATOR_NAME_MAX: usize = 64;
1560
1561impl Talk {
1562 pub fn operator_name(&self) -> Option<&str> {
1564 self.operator_name
1565 .as_deref()
1566 .map(str::trim)
1567 .filter(|n| !n.is_empty())
1568 }
1569}
1570
1571#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1573#[serde(deny_unknown_fields)]
1574pub struct PersonaSpec {
1575 pub id: String,
1577 #[serde(default)]
1580 pub name: String,
1581 #[serde(default)]
1584 pub prompt: String,
1585 #[serde(default, skip_serializing_if = "Option::is_none")]
1589 pub icon: Option<String>,
1590}
1591
1592#[derive(Debug, Clone)]
1594pub struct ResolvedRoles {
1595 pub implementers: Vec<AgentSpec>,
1597 pub judges: Vec<AgentSpec>,
1599 pub reviewers: Vec<AgentSpec>,
1601 pub fixer: Option<Vec<AgentSpec>>,
1606 pub conductor: AgentSpec,
1608 pub implementer_roster: Vec<AgentSpec>,
1616 pub judge_roster: Vec<AgentSpec>,
1620 pub reviewer_roster: Vec<AgentSpec>,
1622}
1623
1624fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1631 let mut out = Vec::new();
1632 for (k, v) in table {
1633 if prefix.is_empty() && k == "vars" {
1634 continue;
1635 }
1636 let path = if prefix.is_empty() {
1637 k.clone()
1638 } else {
1639 format!("{prefix}.{k}")
1640 };
1641 match v {
1642 toml::Value::Array(_) => out.push(path),
1643 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1644 _ => {}
1645 }
1646 }
1647 out
1648}
1649
1650#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1652enum ArrayMerge {
1653 Append,
1657 Replace,
1660}
1661
1662fn array_merge_policy(key: &str) -> ArrayMerge {
1701 match key {
1702 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1703 _ => ArrayMerge::Replace,
1704 }
1705}
1706
1707impl Config {
1708 pub fn load(path: &Path) -> Result<Self> {
1711 Self::load_layers(&[path.to_path_buf()])
1712 }
1713
1714 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1724 let mut ctx = teravars::system_context();
1725 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1726 ctx.insert("env", &env);
1727 if let Some(last) = paths.last()
1728 && let Some(dir) = last.parent()
1729 {
1730 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1733 .map(|s| PathBuf::from(s.trim()))
1734 .unwrap_or_else(|_| dir.to_path_buf());
1735 ctx.insert("repo", &dir.to_string_lossy());
1736 ctx.insert(
1737 "repo_name",
1738 &dir.file_name().unwrap_or_default().to_string_lossy(),
1739 );
1740 }
1741 ctx
1742 }
1743
1744 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1752 let mut engine = teravars::Engine::default();
1753 let ctx = Self::render_ctx(paths);
1754 if paths.len() > 1 {
1755 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1756 if error.downcast_ref::<ConfigFailure>().is_some() {
1757 error
1758 } else {
1759 let message = error.to_string();
1762 error
1763 .context(ConfigFailure::layers("config-merge", paths))
1764 .context(message)
1765 }
1766 })?;
1767 }
1768 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1769 .map_err(|error| {
1770 let cause = ConfigFailure::render(&error, paths);
1771 anyhow::Error::new(error).context(cause)
1772 })
1773 .with_context(|| {
1774 format!(
1775 "rendering config via teravars: {}",
1776 paths
1777 .iter()
1778 .map(|p| p.display().to_string())
1779 .collect::<Vec<_>>()
1780 .join(", ")
1781 )
1782 })?;
1783 let mut table = merged.config;
1784 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1785 table.remove("vars");
1788 let detect_agents = !table.contains_key("agents");
1792 let mut cfg: Self = toml::Value::Table(table)
1793 .try_into()
1794 .context("deserializing magi config")
1795 .context(ConfigFailure::layers("config-deserialize", paths))?;
1796 crate::persona::validate(&cfg.talk.personas)?;
1797 cfg.worktree.validate()?;
1798 cfg.release.validate()?;
1799 if let Some(name) = cfg.talk.operator_name() {
1800 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1801 bail!(
1802 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1803 );
1804 }
1805 }
1806 if detect_agents {
1807 cfg.agents = Self::autodetected().agents;
1808 }
1809 Ok(cfg)
1810 }
1811
1812 fn normalize_renamed_keys(
1820 paths: &[PathBuf],
1821 engine: &mut teravars::Engine,
1822 ctx: &teravars::Context,
1823 table: &mut toml::map::Map<String, toml::Value>,
1824 ) -> Result<()> {
1825 let both = matches!(
1826 table.get("graph"),
1827 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1828 );
1829 if !both {
1830 return Ok(());
1831 }
1832 let mut winner: Option<toml::Value> = None;
1833 for path in paths {
1834 let one = teravars::load_merged([path], engine, ctx)
1835 .map_err(|error| {
1836 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1837 anyhow::Error::new(error).context(cause)
1838 })
1839 .with_context(|| format!("rendering {}", path.display()))?;
1840 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1841 continue;
1842 };
1843 if g.contains_key("candidates") && g.contains_key("implementers") {
1844 bail!(
1845 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1846 path.display()
1847 );
1848 }
1849 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1850 winner = Some(v.clone());
1851 }
1852 }
1853 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1854 g.remove("candidates");
1855 if let Some(v) = winner {
1856 g.insert("implementers".to_owned(), v);
1857 }
1858 }
1859 Ok(())
1860 }
1861
1862 fn refuse_split_arrays(
1886 paths: &[PathBuf],
1887 engine: &mut teravars::Engine,
1888 ctx: &teravars::Context,
1889 ) -> Result<()> {
1890 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1891 for path in paths {
1892 let one = teravars::load_merged([path], engine, ctx)
1893 .map_err(|error| {
1894 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1895 anyhow::Error::new(error).context(cause)
1896 })
1897 .with_context(|| format!("rendering {}", path.display()))?;
1898 for key in array_keys(&one.config, "") {
1899 if array_merge_policy(&key) == ArrayMerge::Append {
1900 continue;
1901 }
1902 if let Some(first) = seen.get(&key) {
1903 bail!(
1904 "`{key}` is an array declared in two config layers:\n \
1905 {}\n {}\nteravars appends arrays when it merges, so \
1906 magi would run the concatenation of both - which is \
1907 not what either file says. Declare `{key}` in exactly \
1908 one of them.",
1909 first.display(),
1910 path.display()
1911 );
1912 }
1913 seen.insert(key, path.clone());
1914 }
1915 }
1916 Ok(())
1917 }
1918
1919 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1941 let mut engine = teravars::Engine::default();
1942 let ctx = Self::render_ctx(paths);
1943 let mut out = Vec::new();
1944 for path in paths {
1945 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1946 continue;
1947 };
1948 let mut cur = &one.config;
1949 let mut found = None;
1950 let parts: Vec<&str> = key.split('.').collect();
1951 for (i, part) in parts.iter().enumerate() {
1952 match cur.get(*part) {
1953 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1954 found = Some(a);
1955 break;
1956 }
1957 Some(toml::Value::Table(t)) => cur = t,
1958 _ => break,
1959 }
1960 }
1961 let Some(values) = found else { continue };
1962 let strings: Vec<String> = values
1963 .iter()
1964 .filter_map(|v| v.as_str().map(str::to_owned))
1965 .collect();
1966 if !strings.is_empty() {
1967 out.push((path.clone(), strings));
1968 }
1969 }
1970 out
1971 }
1972
1973 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1979 let mut engine = teravars::Engine::default();
1980 let ctx = Self::render_ctx(paths);
1981 paths
1982 .iter()
1983 .map(|path| {
1984 let one = teravars::load_merged([path], &mut engine, &ctx)
1985 .map(|m| m.config)
1986 .with_context(|| format!("rendering {}", path.display()));
1987 (path.clone(), one)
1988 })
1989 .collect()
1990 }
1991
1992 pub fn describe_composed(
2002 paths: &[PathBuf],
2003 commands: &[String],
2004 key: &str,
2005 empty: &str,
2006 ) -> String {
2007 if commands.is_empty() {
2008 return empty.to_owned();
2009 }
2010 let joined = commands.join(" && ");
2011 let provenance = Self::array_provenance(paths, key);
2012 if provenance.len() <= 1 {
2013 return joined;
2014 }
2015 let mut out = joined;
2016 for (path, cmds) in &provenance {
2017 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2018 }
2019 out
2020 }
2021
2022 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2029 #[cfg(test)]
2030 crate::web::request_cost::discovery();
2031 if let Some(p) = explicit {
2032 let paths = vec![p.to_path_buf()];
2033 return Ok((Self::load_layers(&paths)?, paths));
2034 }
2035 let paths = Self::layers_checked(repo)?;
2036 if paths.is_empty() {
2037 return Ok((Self::autodetected(), paths));
2038 }
2039 Ok((Self::load_layers(&paths)?, paths))
2040 }
2041
2042 pub async fn discover_fetched(
2045 repo: &Path,
2046 explicit: Option<&Path>,
2047 ) -> Result<(Self, Vec<PathBuf>)> {
2048 if explicit.is_none() && is_git_worktree(repo) {
2049 let (remote, cfg_base) = probe_remote_base(repo);
2053 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2054 .await
2055 .with_context(|| ConfigFailure {
2056 stage: "config-base",
2057 target: remote.clone(),
2058 })?;
2059 let out = crate::git::fetch(repo, &remote, &base)
2060 .await
2061 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2062 .with_context(|| ConfigFailure {
2063 stage: "config-fetch",
2064 target: format!("{remote}/{base}"),
2065 })?;
2066 if !out.ok() {
2067 return Err(anyhow::anyhow!(
2068 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2069 out.stderr.lines().next().unwrap_or("").trim()
2070 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2071 }
2072 if cfg_base.is_none() {
2073 crate::git::ensure_remote_head(repo, &remote, &base).await;
2074 }
2075 }
2076 Self::discover(repo, explicit).map_err(|error| {
2077 if error.downcast_ref::<ConfigFailure>().is_some() {
2078 error
2079 } else {
2080 error.context(ConfigFailure {
2081 stage: "config-load",
2082 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2083 })
2084 }
2085 })
2086 }
2087
2088 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2090 if !is_git_worktree(repo) {
2091 return Ok(Self::layers(repo));
2092 }
2093 let mut paths: Vec<PathBuf> = Self::machine_layer()
2094 .into_iter()
2095 .filter(|p| p.is_file())
2096 .collect();
2097 paths.extend(Self::repo_layers(repo)?);
2098 Ok(paths)
2099 }
2100
2101 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2103 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2104 if let Some(root) = cached {
2105 let relative = path.strip_prefix(root).unwrap_or(path);
2106 let reference = resolve_remote_base(repo)
2107 .map(|(remote, base)| format!("{remote}/{base}"))
2108 .unwrap_or_else(|_| "remote base".to_owned());
2109 format!(
2110 "{} at {reference} (including its includes)",
2111 repo.join(relative).display()
2112 )
2113 } else {
2114 format!("{} (including its includes)", path.display())
2115 }
2116 }
2117
2118 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2121 if !is_git_worktree(repo) {
2122 return Ok([
2123 repo.join(".magi").join("config.toml"),
2124 repo.join("magi.toml"),
2125 ]
2126 .into_iter()
2127 .filter(|p| p.is_file())
2128 .collect());
2129 }
2130 remote_layers(repo)
2131 }
2132
2133 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2153
2154 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2159 let mut paths = Vec::new();
2160 paths.extend(Self::machine_layer());
2161 paths.push(repo.join(".magi").join("config.toml"));
2162 paths.push(repo.join("magi.toml"));
2163 paths.retain(|p| p.is_file());
2164 paths
2165 }
2166
2167 #[cfg(test)]
2174 pub(crate) fn machine_layer() -> Option<PathBuf> {
2175 std::env::var(Self::CONFIG_DIR_ENV)
2176 .ok()
2177 .filter(|dir| !dir.trim().is_empty())
2178 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2179 }
2180
2181 #[cfg(not(test))]
2183 pub(crate) fn machine_layer() -> Option<PathBuf> {
2184 match std::env::var(Self::CONFIG_DIR_ENV) {
2185 Ok(dir) if dir.trim().is_empty() => None,
2187 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2188 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2189 }
2190 }
2191
2192 pub fn autodetected() -> Self {
2194 let mut cfg = Self::default();
2195 for (kind, id, model) in [
2196 (AgentKind::Claude, "opus", Some("opus")),
2197 (AgentKind::Claude, "sonnet", Some("sonnet")),
2198 (AgentKind::Antigravity, "antigravity", None),
2199 (AgentKind::Opencode, "opencode", None),
2200 (AgentKind::Codex, "codex", None),
2201 (AgentKind::Omp, "omp", None),
2202 ] {
2203 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2204 cfg.agents.push(AgentSpec {
2205 id: id.to_owned(),
2206 kind,
2207 model: model.map(str::to_owned),
2208 command: Vec::new(),
2209 extra_args: Vec::new(),
2210 env: BTreeMap::new(),
2211 prompt_delivery: None,
2212 max_turn_secs: None,
2213 });
2214 }
2215 }
2216 cfg
2217 }
2218
2219 pub fn cache_dir(&self) -> Option<PathBuf> {
2222 self.verify.cache_dir()
2223 }
2224
2225 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2227 self.agents
2228 .iter()
2229 .find(|a| a.id == id)
2230 .with_context(|| format!("no agent with id `{id}` in the roster"))
2231 }
2232
2233 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2240 let mut out = Vec::with_capacity(count);
2241 for i in 0..count {
2242 let spec = if ids.is_empty() {
2243 self.agents[(i + offset) % self.agents.len()].clone()
2244 } else {
2245 self.agent(&ids[i % ids.len()])?.clone()
2246 };
2247 out.push(spec);
2248 }
2249 Ok(out)
2250 }
2251
2252 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2259 if ids.is_empty() {
2260 Ok(self.agents.clone())
2261 } else {
2262 ids.iter().map(|id| self.agent(id).cloned()).collect()
2263 }
2264 }
2265
2266 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2273 if self.agents.is_empty() {
2274 bail!(
2275 "agent roster is empty: no agent CLI found on PATH and no \
2276 [[agents]] in the config. Run `magi init` to write a starter \
2277 magi.toml."
2278 );
2279 }
2280 let pinned = self
2281 .graph
2282 .selected_implementer
2283 .as_ref()
2284 .map(|id| self.agent(id).cloned())
2285 .transpose()?;
2286 Ok(ResolvedRoles {
2287 implementers: match &pinned {
2288 Some(agent) => vec![agent.clone()],
2289 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2290 },
2291 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2292 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2293 fixer: match self.roles.fixer.as_ref() {
2294 Some(choice) => Some(crate::agent::pick_chain(
2297 &self.agents,
2298 Some(choice),
2299 &|_| true,
2300 "fixer",
2301 )?),
2302 None => None,
2303 },
2304 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2309 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2310 Some(ids) if !ids.is_empty() => ids
2313 .iter()
2314 .find_map(|id| self.agent(id).ok())
2315 .cloned()
2316 .with_context(|| {
2317 format!("[roles] conductor names no agent in the roster: {ids:?}")
2318 })?,
2319 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2324 .unwrap_or_else(|_| self.agents[0].clone()),
2325 },
2326 implementer_roster: match pinned {
2327 Some(agent) => vec![agent],
2328 None => self.full_roster(&self.roles.implementers)?,
2329 },
2330 judge_roster: self.full_roster(&self.roles.judges)?,
2331 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2332 })
2333 }
2334
2335 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2357 if self.agents.is_empty() {
2358 bail!(
2359 "agent roster is empty: no agent CLI found on PATH and no \
2360 [[agents]] in the config. Run `magi init` to write a starter \
2361 magi.toml."
2362 );
2363 }
2364 if !self.roles.advisors.is_empty() {
2365 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2366 }
2367 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2368 }
2369
2370 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2374 if self.roles.advisors.is_empty() {
2375 self.full_roster(&self.roles.judges)
2376 } else {
2377 self.full_roster(&self.roles.advisors)
2378 }
2379 }
2380
2381 pub fn shell(&self) -> Vec<String> {
2383 if let Some(s) = &self.verify.shell {
2384 return s.clone();
2385 }
2386 if which("sh") {
2387 vec!["sh".to_owned(), "-c".to_owned()]
2388 } else {
2389 vec!["cmd".to_owned(), "/C".to_owned()]
2390 }
2391 }
2392
2393 pub fn starter_toml() -> String {
2395 let detected = Self::autodetected();
2396 let mut s = String::from(
2397 "# magi — blind multi-agent implementation competition.\n\
2398 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2399 # -> blind judging -> deliberation -> private final vote\n\
2400 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2401 #\n\
2402 # Rendered by teravars: a `[vars]` table, env\n\
2403 # and system lookups, and `include = [...]` all work. Tera\n\
2404 # braces are live everywhere in this file, but comments are\n\
2405 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2406 # may quote `{{ ... }}` freely.\n\
2407 #\n\
2408 # Layers deep-merge in increasing\n\
2409 # precedence, so the roster can live once per machine in\n\
2410 # <config_dir>/magi/config.toml and each repo only states its own\n\
2411 # gate:\n\
2412 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2413 [vars]\n\
2414 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2415 # Single quotes inside the braces: teravars renders the raw file\n\
2416 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2417 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2418 );
2419 if detected.agents.is_empty() {
2420 s.push_str(
2421 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2422 # kind = claude | opencode | antigravity | codex | command\n\
2423 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2424 );
2425 } else {
2426 for a in &detected.agents {
2427 s.push_str("[[agents]]\n");
2428 s.push_str(&format!("id = {:?}\n", a.id));
2429 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2430 if let Some(m) = &a.model {
2431 s.push_str(&format!("model = {m:?}\n"));
2432 }
2433 s.push('\n');
2434 }
2435 }
2436 s.push_str(
2437 "# Leave a role list empty to rotate through the roster.\n\
2438 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2439 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2440 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2441 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2442 [roles]\n\
2443 implementers = []\n\
2444 judges = []\n\
2445 reviewers = []\n\
2446 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2447 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2448 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2449 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2450 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2451 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2452 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2453 [graph]\n\
2454 # Gate GitHub prose; secret redaction is always enabled.\n\
2455 github_text_guard = true\n\
2456 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2457 github_language = \"en\"\n\
2458 implementers = 3\n\
2459 judges = 3\n\
2460 deliberate_rounds = 1\n\
2461 reviewers = 3\n\
2462 review_rounds = 6\n\
2463 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2464 gate_fix_rounds = 1\n\
2465 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2466 rerun_flaky_checks = true\n\
2467 # Port the strengths judges named in the losing candidates onto the\n\
2468 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2469 graft_runner_up = true\n\
2470 max_parallel = 4\n\
2471 language = \"en\"\n\
2472 # One CLI conversation per seat: judges keep their own argument\n\
2473 # across deliberation, the fixer keeps its implementation context.\n\
2474 sessions = true\n\
2475 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2476 # the final gate inherit this value for compatibility.\n\
2477 timeout_review = 1200\n\
2478 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2479 # verification independent if timeout_review changes later.\n\
2480 # timeout_verify = 1200\n\
2481 # Longest a seat waits for the shared build cache before it is\n\
2482 # spawned. Never counted against an agent's own timeout; expiry\n\
2483 # holds the run (resumable) instead of failing the agent.\n\
2484 # timeout_resource_wait = 1800\n\n\
2485 # What the chat calls you (persona address and the Chat's turn label).\n\
2486 # [talk]\n\
2487 # operator_name = \"Commander\"\n\n\
2488 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2489 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2490 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2491 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2492 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2493 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2494 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2495 # [[talk.personas]]\n\
2496 # id = \"gendo\"\n\
2497 # name = \"Gendo Ikari\"\n\
2498 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2499 # icon = \"~/pictures/gendo.png\"\n\n\
2500 [verify]\n\
2501 # Run once per review round in the winner's worktree; failures are\n\
2502 # fed back to the fixer.\n\
2503 e2e = []\n\
2504 # Final gate. Every command must exit 0 before a merge.\n\
2505 gate = []\n\
2506 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2507 # before the gate; whatever they change becomes one commit. A failing\n\
2508 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2509 # gate (timeout_verify). Keep it light and idempotent.\n\
2510 # pre_gate = []\n\n\
2511 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2512 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2513 # before any agent or verify command touches it. `copy` reads from the\n\
2514 # primary checkout and never overwrites; `optional` skips a missing\n\
2515 # source. `run` goes through the shell with the worktree as cwd and\n\
2516 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2517 # the verify timeout). Setup must not edit tracked files, and what it\n\
2518 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2519 # layer only.\n\
2520 # [worktree]\n\
2521 # setup = [\n\
2522 # { copy = \".env.example -> .env\" },\n\
2523 # { copy = \".env.local\", optional = true },\n\
2524 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2525 # ]\n\n\
2526 [merge]\n\
2527 # none | local | pr\n\
2528 mode = \"none\"\n\
2529 # expected (default) | none. Set none only in repository config without CI.\n\
2530 # Ignores all check statuses; reviews and approval still apply.\n\
2531 # ci = \"expected\"\n\
2532 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2533 [update]\n\
2534 # off | notify | install — checked in the background, throttled.\n\
2535 mode = \"notify\"\n\
2536 # interval = \"24h\"\n\n\
2537 # Opt-in: magi web updates and restarts only after runs/chats finish.\n\
2538 # auto_restart = false\n\
2539 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2540 # Standalone magi serve cannot restart. Busy work waits indefinitely.\n\
2541 # Failed tags are skipped until process restart or a different tag.\n\
2542 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2543 [daemon]\n\
2544 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2545 # no new commit and no check changing state before `magi serve`\n\
2546 # notices and asks you. A failed check is rerun once on its own;\n\
2547 # still red after that escalates at once. 0 turns the watcher off.\n\
2548 # release_stall_minutes = 60\n\n\
2549 [release]\n\
2550 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2551 # Actions never run (private, no minutes): the release pull request\n\
2552 # does not wait for CI, you approve the merge in magi, and then\n\
2553 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2554 # runs `commands` from a clean checkout of the merge commit. A\n\
2555 # failure holds the release with a notice; it is never retried blind.\n\
2556 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2557 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2558 # mode = \"actions\"\n\
2559 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2560 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2561 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2562 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2563 # timeout_minutes = 30\n\
2564 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2565 # The first entry is the version of record and must be the file the\n\
2566 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2567 # rewritten to the same version. Paths are relative to the repository\n\
2568 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2569 # is not touched.\n\
2570 # version_files = [\n\
2571 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2572 # { path = \"package.json\", kind = \"json\" },\n\
2573 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2574 # ]\n",
2575 );
2576 s
2577 }
2578}
2579
2580pub fn which(program: &str) -> bool {
2582 find_program(program).is_some()
2583}
2584
2585pub fn find_program(program: &str) -> Option<PathBuf> {
2594 find_program_on(program, &std::env::var_os("PATH")?)
2595}
2596
2597pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2600 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2601 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2602}
2603
2604fn find_program_in(
2605 program: &str,
2606 paths: &std::ffi::OsStr,
2607 pathext: Option<&str>,
2608) -> Option<PathBuf> {
2609 let p = Path::new(program);
2610 if p.components().count() > 1 {
2611 return p.is_file().then(|| p.to_path_buf());
2612 }
2613 std::env::split_paths(paths).find_map(|dir| match pathext {
2614 Some(exts) => {
2615 let bare = dir.join(program);
2616 if p.extension().is_some() && bare.is_file() {
2617 return Some(bare);
2618 }
2619 exts.split(';')
2620 .filter(|e| !e.is_empty())
2621 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2622 .find(|c| c.is_file())
2623 }
2624 None => Some(dir.join(program)).filter(|c| c.is_file()),
2625 })
2626}
2627
2628const REPO_MARKER: &str = ".magi-repo";
2630
2631fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2632 use crate::proc::Quiet as _;
2633 #[cfg(test)]
2634 crate::web::request_cost::git();
2635 let out = std::process::Command::new("git")
2636 .args(args)
2637 .quiet()
2638 .current_dir(repo)
2639 .stdin(std::process::Stdio::null())
2640 .output()
2641 .ok()?;
2642 out.status
2643 .success()
2644 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2645}
2646
2647fn is_git_worktree(repo: &Path) -> bool {
2650 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2651}
2652
2653#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2656pub enum OwnerHold {
2657 LandApproval,
2659 HoldContestedMerge,
2661}
2662
2663impl OwnerHold {
2664 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2666
2667 pub fn key(self) -> &'static str {
2669 match self {
2670 Self::LandApproval => "land_approval",
2671 Self::HoldContestedMerge => "hold_contested_merge",
2672 }
2673 }
2674
2675 pub fn base_value(self, graph: &Graph) -> bool {
2677 match self {
2678 Self::LandApproval => graph.land_approval,
2679 Self::HoldContestedMerge => graph.hold_contested_merge,
2680 }
2681 }
2682}
2683
2684pub async fn branch_owner_holds(
2687 repo: &Path,
2688 head: &str,
2689) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2690 let mut holds = Vec::new();
2691 let mut diagnostics = Vec::new();
2692 if let Err(error) =
2695 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2696 {
2697 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2698 return (holds, diagnostics);
2699 }
2700 for file in ["magi.toml", ".magi/config.toml"] {
2701 let object = format!("{head}:{file}");
2702 let text = match crate::git::git(repo, &["show", &object]).await {
2703 Ok(text) => text,
2704 Err(error) => {
2705 let error = format!("{error:#}");
2707 if !error.contains("does not exist in")
2708 && !error.contains("exists on disk, but not in")
2709 {
2710 diagnostics.push(format!(
2711 "cannot read reviewed branch {file} at {head}: {error}"
2712 ));
2713 }
2714 continue;
2715 }
2716 };
2717 let value = match toml::from_str::<toml::Value>(&text) {
2718 Ok(value) => value,
2719 Err(error) => {
2720 diagnostics.push(format!(
2721 "cannot parse reviewed branch {file} at {head}: {error}"
2722 ));
2723 continue;
2724 }
2725 };
2726 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2727 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2728 }
2729 for hold in OwnerHold::ALL {
2730 if value
2731 .get("graph")
2732 .and_then(|g| g.get(hold.key()))
2733 .and_then(toml::Value::as_bool)
2734 == Some(true)
2735 {
2736 holds.push((hold, file.to_owned()));
2737 }
2738 }
2739 }
2740 (holds, diagnostics)
2741}
2742
2743#[derive(Deserialize, Default)]
2744struct ProbeMerge {
2745 base: Option<String>,
2746 remote: Option<String>,
2747}
2748
2749#[derive(Deserialize, Default)]
2750struct Probe {
2751 merge: Option<ProbeMerge>,
2752}
2753
2754fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2760 if !path.is_file() {
2761 return None;
2762 }
2763 let paths = [path.to_path_buf()];
2764 let mut engine = teravars::Engine::default();
2765 let mut ctx = Config::render_ctx(&paths);
2766 ctx.insert("repo", &repo.to_string_lossy());
2769 ctx.insert(
2770 "repo_name",
2771 &repo.file_name().unwrap_or_default().to_string_lossy(),
2772 );
2773 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2774 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2775 {
2776 return probe.merge;
2777 }
2778 let text = std::fs::read_to_string(path).ok()?;
2779 toml::from_str::<Probe>(&text).ok()?.merge
2780}
2781
2782fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2784 let mut remote = None;
2785 let mut base = None;
2786 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2787 sources.push(repo.join("magi.toml"));
2788 sources.push(repo.join(".magi").join("config.toml"));
2789 for path in sources {
2790 if let Some(m) = probe_merge(&path, repo) {
2791 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2792 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2793 }
2794 }
2795 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2796}
2797
2798fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2800 let (remote, base) = probe_remote_base(repo);
2801 let base = match base {
2802 Some(b) => b,
2803 None => {
2804 let head = format!("refs/remotes/{remote}/HEAD");
2805 git_out(repo, &["symbolic-ref", "--quiet", &head])
2806 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2807 .with_context(|| {
2808 format!(
2809 "cannot tell which branch of `{remote}` holds magi.toml: \
2810 set [merge] base, or run `git remote set-head {remote} -a`"
2811 )
2812 })?
2813 }
2814 };
2815 Ok((remote, base))
2816}
2817
2818fn fnv_hex(text: &str) -> String {
2819 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2820 for b in text.bytes() {
2821 hash ^= u64::from(b);
2822 hash = hash.wrapping_mul(0x0100_0000_01b3);
2823 }
2824 format!("{hash:016x}")
2825}
2826
2827fn declares_include(text: &str) -> bool {
2833 match toml::from_str::<toml::Table>(text) {
2834 Ok(table) => {
2835 table.contains_key("include")
2836 || table
2837 .get("teravars")
2838 .and_then(toml::Value::as_table)
2839 .is_some_and(|t| t.contains_key("include"))
2840 }
2841 Err(_) => text.contains("include"),
2842 }
2843}
2844
2845fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2848 use crate::proc::Quiet as _;
2849 #[cfg(test)]
2850 crate::web::request_cost::git();
2851 let mut archive = std::process::Command::new("git")
2852 .args(["archive", "--format=tar", sha])
2853 .quiet()
2854 .current_dir(repo)
2855 .stdin(std::process::Stdio::null())
2856 .stdout(std::process::Stdio::piped())
2857 .stderr(std::process::Stdio::null())
2858 .spawn()
2859 .context("running git archive")?;
2860 let tar = std::process::Command::new("tar")
2861 .arg("-x")
2862 .arg("-C")
2863 .arg(dest)
2864 .quiet()
2865 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2866 .output()
2867 .context("running tar")?;
2868 let status = archive.wait().context("waiting for git archive")?;
2869 if !status.success() || !tar.status.success() {
2870 bail!(
2871 "cannot unpack {sha} for the config's includes: {}",
2872 String::from_utf8_lossy(&tar.stderr).trim()
2873 );
2874 }
2875 Ok(())
2876}
2877
2878fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2881 let (remote, base) = resolve_remote_base(repo)?;
2882 let tracking = format!("refs/remotes/{remote}/{base}");
2883 let spec = format!("{tracking}^{{commit}}");
2884 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2885 .map(|s| s.trim().to_owned())
2886 .filter(|s| !s.is_empty())
2887 .with_context(|| {
2888 format!(
2889 "`{remote}/{base}` does not exist in this checkout; fetch it \
2890 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2891 a possibly stale local magi.toml instead"
2892 )
2893 })?;
2894 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2895 let rels = [".magi/config.toml", "magi.toml"];
2896 let mut texts: Vec<(&str, String)> = Vec::new();
2897 for rel in rels {
2898 let object = format!("{sha}:{rel}");
2899 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2900 continue;
2901 }
2902 let Some(text) = git_out(repo, &["show", &object]) else {
2903 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2904 };
2905 texts.push((rel, text));
2906 }
2907 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2908 let build = |root: &Path| -> Result<PathBuf> {
2912 let final_dir = root.join(&key);
2913 if !final_dir.is_dir() {
2914 std::fs::create_dir_all(root)?;
2915 let tmp = root.join(format!(
2916 "{key}.tmp-{}-{}",
2917 std::process::id(),
2918 std::time::SystemTime::now()
2919 .duration_since(std::time::UNIX_EPOCH)
2920 .map(|d| d.as_nanos())
2921 .unwrap_or_default()
2922 ));
2923 let filled = (|| -> Result<()> {
2924 std::fs::create_dir_all(&tmp)?;
2925 if wants_tree {
2926 extract_tree(repo, &sha, &tmp)?;
2927 }
2928 for (rel, text) in &texts {
2929 let file = tmp.join(rel);
2930 let parent = file.parent().unwrap_or(&tmp);
2931 std::fs::create_dir_all(parent)?;
2932 std::fs::write(&file, text)?;
2933 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2934 }
2935 Ok(())
2936 })();
2937 if let Err(e) = filled {
2938 let _ = std::fs::remove_dir_all(&tmp);
2939 return Err(e);
2940 }
2941 if std::fs::rename(&tmp, &final_dir).is_err() {
2942 let _ = std::fs::remove_dir_all(&tmp);
2944 if !final_dir.is_dir() {
2945 bail!("cannot place {}", final_dir.display());
2946 }
2947 }
2948 }
2949 Ok(final_dir)
2950 };
2951 let common = git_out(
2952 repo,
2953 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2954 )
2955 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2956 let dir = match common.map(|c| build(&c)) {
2957 Some(Ok(d)) => d,
2958 _ => build(&std::env::temp_dir().join("magi-config"))
2959 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2960 };
2961 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2962}
2963
2964#[cfg(test)]
2965mod tests {
2966 #[test]
2967 fn editing_network_defaults_enabled_and_can_be_restricted() {
2968 assert_eq!(Graph::default().editing_network, EditingNetwork::Enabled);
2969 let dir = tempfile::tempdir().unwrap();
2970 let path = dir.path().join("policy.toml");
2971 for (value, expected) in [
2972 ("restricted", EditingNetwork::Restricted),
2973 ("enabled", EditingNetwork::Enabled),
2974 ] {
2975 std::fs::write(&path, format!("[graph]\nediting_network = {value:?}\n")).unwrap();
2976 let cfg = Config::load(&path).unwrap();
2977 assert_eq!(cfg.graph.editing_network, expected);
2978 let restored: Graph = toml::from_str(&toml::to_string(&cfg.graph).unwrap()).unwrap();
2979 assert_eq!(restored.editing_network, expected);
2980 }
2981 std::fs::write(&path, "[graph]\nediting_network = 'loopback'\n").unwrap();
2982 assert!(Config::load(&path).is_err());
2983 }
2984
2985 #[test]
2986 fn coordination_defaults_off_and_validates_rendered_layer_values() {
2987 let dir = tempfile::tempdir().unwrap();
2988 let machine = dir.path().join("machine.toml");
2989 let repo = dir.path().join("repo.toml");
2990 std::fs::write(&machine, "").unwrap();
2991 assert!(Config::default().coordination.is_none());
2992 assert!(Config::load(&machine).unwrap().coordination.is_none());
2993 std::fs::write(
2994 &machine,
2995 r#"
2996[vars]
2997contract = "updater.contract"
2998[coordination]
2999contract_file = "{{ vars.contract }}"
3000contract_token = "protocol-v1"
3001lock_file = "updater.lock"
3002"#,
3003 )
3004 .unwrap();
3005 let cfg = Config::load(&machine).unwrap();
3006 let policy = cfg.coordination.unwrap();
3007 assert_eq!(policy.contract_file, "updater.contract");
3008 assert_eq!(policy.contract_token, "protocol-v1");
3009 assert_eq!(policy.lock_file, "updater.lock");
3010 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
3011 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
3012 let policy = cfg.coordination.unwrap();
3013 assert_eq!(policy.contract_file, "updater.contract");
3014 assert_eq!(policy.lock_file, "repository.lock");
3015 std::fs::write(
3016 &repo,
3017 r#"
3018[vars]
3019bad = "../escape"
3020[coordination]
3021lock_file = "{{ vars.bad }}"
3022"#,
3023 )
3024 .unwrap();
3025 let error = Config::load_layers(&[machine, repo]).unwrap_err();
3026 assert!(format!("{error:#}").contains("coordination.lock_file"));
3027 }
3028
3029 #[test]
3030 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
3031 let dir = tempfile::tempdir().unwrap();
3032 let path = dir.path().join("config.toml");
3033 let valid = toml::toml! {
3034 [coordination]
3035 contract_file = "updater.contract"
3036 contract_token = "protocol-v1"
3037 lock_file = "updater.lock"
3038 };
3039 for key in ["contract_file", "lock_file"] {
3040 for bad in [
3041 "",
3042 " ",
3043 " file",
3044 "file ",
3045 "\tfile",
3046 "file\t",
3047 ".",
3048 "..",
3049 "file..name",
3050 "../escape",
3051 "a/b",
3052 "a\\b",
3053 "/absolute",
3054 "C:drive",
3055 "C:\\absolute",
3056 "nul\0name",
3057 ] {
3058 let mut table = valid.clone();
3059 table["coordination"][key] = bad.into();
3060 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3061 let error = Config::load(&path).unwrap_err();
3062 assert!(
3063 format!("{error:#}").contains(&format!("coordination.{key}")),
3064 "{bad:?}: {error:#}"
3065 );
3066 }
3067 }
3068 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
3069 let mut table = valid.clone();
3070 table["coordination"]["contract_token"] = bad.into();
3071 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3072 let error = Config::load(&path).unwrap_err();
3073 assert!(
3074 format!("{error:#}").contains("coordination.contract_token"),
3075 "{error:#}"
3076 );
3077 }
3078 for key in ["contract_file", "contract_token", "lock_file"] {
3079 let mut table = valid.clone();
3080 table["coordination"].as_table_mut().unwrap().remove(key);
3081 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3082 let error = Config::load(&path).unwrap_err();
3083 assert!(
3084 format!("{error:#}").contains(&format!("coordination.{key}")),
3085 "{error:#}"
3086 );
3087 }
3088 let mut table = valid;
3089 table["coordination"]
3090 .as_table_mut()
3091 .unwrap()
3092 .insert("typo".into(), "value".into());
3093 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3094 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3095 }
3096
3097 #[test]
3098 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3099 let mut cfg = Config::default();
3100 assert_eq!(
3101 cfg.context_window("claude-sonnet-4-5-20250929"),
3102 Some(200_000)
3103 );
3104 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3105 assert_eq!(cfg.context_window("mystery-model"), None);
3106 cfg.context_windows
3107 .insert("claude-sonnet-4-5".into(), 1_000_000);
3108 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3109 cfg.context_windows.insert("mystery".into(), 32_768);
3110 assert_eq!(
3112 cfg.context_window("claude-sonnet-4-5-20250929"),
3113 Some(1_000_000)
3114 );
3115 cfg.context_windows
3117 .insert("claude-sonnet-4-5-20250929".into(), 7);
3118 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3119 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3120 }
3121
3122 use super::*;
3123
3124 #[test]
3127 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3128 let dir = tempfile::tempdir().unwrap();
3129 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3130 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3131 let paths = dir.path().as_os_str();
3132 assert_eq!(
3133 find_program_in("codex", paths, Some(".EXE;.CMD")),
3134 Some(dir.path().join("codex.cmd"))
3135 );
3136 assert_eq!(
3137 find_program_in("codex", paths, None),
3138 Some(dir.path().join("codex"))
3139 );
3140 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3141 }
3142
3143 fn spec(id: &str) -> AgentSpec {
3144 AgentSpec {
3145 id: id.to_owned(),
3146 kind: AgentKind::Command,
3147 model: None,
3148 command: vec!["true".to_owned()],
3149 extra_args: Vec::new(),
3150 env: BTreeMap::new(),
3151 prompt_delivery: None,
3152 max_turn_secs: None,
3153 }
3154 }
3155
3156 #[test]
3157 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
3158 let default: Merge = toml::from_str("").unwrap();
3159 assert_eq!(default.ci, MergeCi::Expected);
3160 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
3161 assert_eq!(
3162 config.merge.ci.expectation(),
3163 crate::land::CiExpectation::Absent
3164 );
3165 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
3166 assert!(Config::starter_toml().contains("# ci = \"expected\""));
3167 }
3168
3169 #[test]
3170 fn github_text_guard_defaults_on_and_can_be_disabled() {
3171 let default: Graph = toml::from_str("").unwrap();
3172 assert!(default.github_text_guard);
3173 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3174 assert!(!disabled.github_text_guard);
3175 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3176 assert!(!config.graph.github_text_guard);
3177 assert!(Config::starter_toml().contains("github_text_guard = true"));
3178 }
3179
3180 #[test]
3181 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3182 assert!(Graph::default().rerun_flaky_checks);
3183 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3184 assert!(!off.rerun_flaky_checks);
3185 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3186 }
3187
3188 #[test]
3189 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3190 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3195 assert_eq!(g.timeout_verify, None);
3196 assert_eq!(g.verify_timeout(), 3600);
3197 }
3198
3199 #[test]
3200 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3201 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3206 assert_eq!(g.timeout_review, 45);
3207 assert_eq!(
3208 g.verify_timeout(),
3209 45,
3210 "an omitted legacy value follows review"
3211 );
3212 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3213 .expect("parse explicit override");
3214 assert_eq!(explicit.verify_timeout(), 1200);
3215 }
3216
3217 #[test]
3218 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3219 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3220 assert_eq!(g.implementers, 4);
3221 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3222 assert_eq!(g.implementers, 5);
3223 }
3224
3225 fn layered(lower: &str, upper: &str) -> Result<Config> {
3226 let dir = tempfile::tempdir().unwrap();
3227 let a = dir.path().join("a.toml");
3228 let b = dir.path().join("b.toml");
3229 std::fs::write(&a, lower).unwrap();
3230 std::fs::write(&b, upper).unwrap();
3231 Config::load_layers(&[a, b])
3232 }
3233
3234 #[test]
3235 fn graph_implementers_higher_layer_wins_across_spellings() {
3236 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3237 assert_eq!(c.graph.implementers, 5);
3238 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3239 assert_eq!(c.graph.implementers, 5);
3240 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3241 assert_eq!(c.graph.implementers, 2);
3242 }
3243
3244 #[test]
3245 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3246 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3247 .unwrap_err()
3248 .to_string();
3249 assert!(
3250 err.contains("candidates") && err.contains("implementers"),
3251 "{err}"
3252 );
3253 assert!(err.contains("b.toml"), "{err}");
3254 }
3255
3256 #[test]
3257 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3258 let g: Graph =
3262 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3263 .expect("an old-shaped [graph] table must still parse");
3264 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3265 assert!(
3266 !g.e2e_every_round,
3267 "off by default, same as before this field existed"
3268 );
3269 }
3270
3271 #[test]
3272 fn empty_roles_rotate_judges_off_their_own_candidate() {
3273 let cfg = Config {
3276 agents: vec![spec("a"), spec("b"), spec("c")],
3277 graph: Graph {
3278 implementers: 3,
3279 ..Graph::default()
3280 },
3281 ..Config::default()
3282 };
3283 let roles = cfg.resolve_roles().unwrap();
3284 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3285 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3286 assert_eq!(impls, ["a", "b", "c"]);
3287 assert_eq!(judges, ["b", "c", "a"]);
3288 for (i, j) in judges.iter().enumerate() {
3289 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3290 }
3291 }
3292
3293 #[test]
3294 fn single_agent_roster_fills_every_seat() {
3295 let cfg = Config {
3296 agents: vec![spec("solo")],
3297 graph: Graph {
3298 implementers: 3,
3299 ..Graph::default()
3300 },
3301 ..Config::default()
3302 };
3303 let roles = cfg.resolve_roles().unwrap();
3304 assert_eq!(roles.implementers.len(), 3);
3305 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3306 }
3307
3308 #[test]
3309 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3310 let cfg = Config {
3315 agents: vec![spec("a"), spec("b"), spec("c")],
3316 graph: Graph {
3317 implementers: 1,
3318 ..Graph::default()
3319 },
3320 ..Config::default()
3321 };
3322 let roles = cfg.resolve_roles().unwrap();
3323 assert_eq!(roles.implementers.len(), 1);
3324 let roster: Vec<&str> = roles
3325 .implementer_roster
3326 .iter()
3327 .map(|a| a.id.as_str())
3328 .collect();
3329 assert_eq!(roster, ["a", "b", "c"]);
3330 }
3331
3332 #[test]
3333 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3334 let cfg = Config {
3335 agents: vec![spec("a"), spec("b"), spec("c")],
3336 roles: Roles {
3337 implementers: vec!["c".to_owned(), "a".to_owned()],
3338 ..Roles::default()
3339 },
3340 graph: Graph {
3341 implementers: 1,
3342 ..Graph::default()
3343 },
3344 ..Config::default()
3345 };
3346 let roles = cfg.resolve_roles().unwrap();
3347 assert_eq!(roles.implementers.len(), 1);
3349 assert_eq!(roles.implementers[0].id, "c");
3350 let roster: Vec<&str> = roles
3351 .implementer_roster
3352 .iter()
3353 .map(|a| a.id.as_str())
3354 .collect();
3355 assert_eq!(roster, ["c", "a"]);
3356 }
3357
3358 #[test]
3359 fn explicit_roles_win() {
3360 let cfg = Config {
3361 agents: vec![spec("a"), spec("b")],
3362 roles: Roles {
3363 implementers: vec!["b".to_owned()],
3364 judges: vec!["a".to_owned()],
3365 reviewers: Vec::new(),
3366 fixer: Some("a".into()),
3367 ..Roles::default()
3368 },
3369 ..Config::default()
3370 };
3371 let roles = cfg.resolve_roles().unwrap();
3372 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3373 assert!(roles.judges.iter().all(|a| a.id == "a"));
3374 let fixer = roles.fixer.unwrap();
3375 assert_eq!(fixer.len(), 1);
3376 assert_eq!(fixer[0].id, "a");
3377 assert_eq!(roles.conductor.id, "a");
3378 }
3379
3380 #[test]
3381 fn fixer_takes_a_string_or_an_ordered_chain() {
3382 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3383 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3384 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3385 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3386
3387 let resolve = |fixer: Option<AgentChoice>| {
3388 Config {
3389 agents: vec![spec("a"), spec("b"), spec("c")],
3390 roles: Roles {
3391 fixer,
3392 ..Roles::default()
3393 },
3394 ..Config::default()
3395 }
3396 .resolve_roles()
3397 };
3398 let ids = |r: &ResolvedRoles| -> Vec<String> {
3399 r.fixer
3400 .as_ref()
3401 .unwrap()
3402 .iter()
3403 .map(|s| s.id.clone())
3404 .collect()
3405 };
3406 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3408 assert!(resolve(None).unwrap().fixer.is_none());
3409 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3411 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3412 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3414 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3415 }
3416
3417 #[test]
3418 fn unknown_agent_id_is_an_error() {
3419 let cfg = Config {
3420 agents: vec![spec("a")],
3421 roles: Roles {
3422 judges: vec!["nope".to_owned()],
3423 ..Roles::default()
3424 },
3425 ..Config::default()
3426 };
3427 assert!(cfg.resolve_roles().is_err());
3428 }
3429
3430 #[test]
3431 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3432 let mut cfg = Config {
3433 agents: vec![spec("a"), spec("b")],
3434 ..Config::default()
3435 };
3436 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3437
3438 cfg.roles.conductor = Some("b".into());
3439 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3440
3441 cfg.roles.conductor = Some("missing".into());
3442 assert!(cfg.resolve_roles().is_err());
3443 }
3444
3445 #[test]
3446 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3447 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3448 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3449 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3450
3451 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3452 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3453 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3454
3455 for roles in [one, chain] {
3456 let text = toml::to_string(&roles).unwrap();
3457 let back: Roles = toml::from_str(&text).unwrap();
3458 assert_eq!(back.synthesizer, roles.synthesizer);
3459 assert_eq!(back.chatter, roles.chatter);
3460 }
3461 let text = toml::to_string(&Roles {
3462 conductor: Some("x".into()),
3463 ..Roles::default()
3464 })
3465 .unwrap();
3466 assert!(
3467 text.contains("conductor = \"x\""),
3468 "string stays a string: {text}"
3469 );
3470 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3471 }
3472
3473 #[test]
3474 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3475 for (text, ids) in [
3476 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3477 (
3478 r#"dupes_judge = ["first", "second"]"#,
3479 vec!["first", "second"],
3480 ),
3481 ("dupes_judge = []", vec![]),
3482 ] {
3483 let roles: Roles = toml::from_str(text).unwrap();
3484 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3485 let serialized = toml::to_string(&roles).unwrap();
3486 let back: Roles = toml::from_str(&serialized).unwrap();
3487 assert_eq!(back.dupes_judge, roles.dupes_judge);
3488 assert!(serialized.contains(text));
3489 }
3490 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3491 assert!(Roles::default().dupes_judge.is_none());
3492 assert!(Config::starter_toml().contains("# dupes_judge ="));
3493
3494 let mut cfg = Config {
3496 agents: vec![spec("a")],
3497 ..Config::default()
3498 };
3499 cfg.roles.dupes_judge = Some("missing".into());
3500 assert!(cfg.resolve_roles().is_ok());
3501 }
3502
3503 #[test]
3504 fn an_empty_choice_counts_as_unset() {
3505 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3506 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3507 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3508 }
3509
3510 #[test]
3511 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3512 let mut cfg = Config {
3518 agents: vec![spec("a"), spec("b")],
3519 ..Config::default()
3520 };
3521 let want = primary(cfg.roles.synthesizer.as_ref());
3522 assert_eq!(
3523 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3524 .unwrap()
3525 .id,
3526 "a",
3527 "unset falls back to agent::pick's own default order"
3528 );
3529
3530 cfg.roles.synthesizer = Some("b".into());
3531 let want = primary(cfg.roles.synthesizer.as_ref());
3532 assert_eq!(
3533 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3534 .unwrap()
3535 .id,
3536 "b",
3537 "the named agent wins over the default order"
3538 );
3539 }
3540
3541 #[test]
3542 fn empty_roster_is_an_error() {
3543 assert!(Config::default().resolve_roles().is_err());
3544 }
3545
3546 #[test]
3547 fn advise_defaults_to_on_with_three_proposals() {
3548 let g = Graph::default();
3549 assert!(g.advise);
3550 assert!(g.graft_runner_up, "graft is on by default");
3551 assert_eq!(g.advisors, 3);
3552 }
3553
3554 #[test]
3555 fn unset_advisors_falls_back_to_the_judge_roster() {
3556 let cfg = Config {
3557 agents: vec![spec("a"), spec("b")],
3558 roles: Roles {
3559 judges: vec!["b".to_owned()],
3560 ..Roles::default()
3561 },
3562 graph: Graph {
3563 advisors: 2,
3564 ..Graph::default()
3565 },
3566 ..Config::default()
3567 };
3568 let advisors = cfg.advisors().expect("advisors resolve");
3569 assert_eq!(advisors.len(), 2);
3570 assert!(
3571 advisors.iter().all(|a| a.id == "b"),
3572 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3573 );
3574 }
3575
3576 #[test]
3577 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3578 let cfg = Config {
3579 agents: vec![spec("a"), spec("b")],
3580 roles: Roles {
3581 judges: vec!["b".to_owned()],
3582 advisors: vec!["a".to_owned()],
3583 ..Roles::default()
3584 },
3585 graph: Graph {
3586 advisors: 2,
3587 ..Graph::default()
3588 },
3589 ..Config::default()
3590 };
3591 let advisors = cfg.advisors().expect("advisors resolve");
3592 assert!(advisors.iter().all(|a| a.id == "a"));
3593 }
3594
3595 #[test]
3601 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3602 let cfg = Config {
3603 agents: vec![spec("a"), spec("b"), spec("c")],
3604 graph: Graph {
3605 advisors: 3,
3606 judges: 3,
3607 ..Graph::default()
3608 },
3609 ..Config::default()
3610 };
3611 let advisors = cfg.advisors().expect("advisors resolve");
3612 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3613 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3614 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3615 assert_eq!(
3616 advisor_ids, judge_ids,
3617 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3618 );
3619 }
3620
3621 #[test]
3622 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3623 let cfg = Config {
3624 agents: vec![spec("a")],
3625 roles: Roles {
3626 advisors: vec!["nope".to_owned()],
3627 ..Roles::default()
3628 },
3629 graph: Graph {
3630 advisors: 1,
3631 ..Graph::default()
3632 },
3633 ..Config::default()
3634 };
3635 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3636 assert!(format!("{err:#}").contains("nope"));
3637 }
3638
3639 #[test]
3640 fn repos_default_to_no_roots_and_a_day_of_trust() {
3641 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3642 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3643 assert_eq!(Config::default().repos.fetch_interval, 600);
3644 }
3645
3646 #[test]
3647 fn a_config_file_with_no_repos_table_still_loads() {
3648 let dir = tempfile::tempdir().unwrap();
3649 let path = dir.path().join("magi.toml");
3650 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3651 let cfg = Config::load(&path).expect("must load without [repos]");
3652 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3653 assert_eq!(cfg.repos.scan_ttl, 86_400);
3654 }
3655
3656 #[test]
3671 fn a_test_build_does_not_read_the_operators_machine_config() {
3672 let repo = tempfile::tempdir().unwrap();
3673 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3674
3675 let layers = Config::layers(repo.path());
3676 assert_eq!(
3677 layers,
3678 vec![repo.path().join("magi.toml")],
3679 "only the fixture's own file may be a layer"
3680 );
3681 if let Some(real) = dirs::config_dir() {
3682 let machine = real.join("magi").join("config.toml");
3683 assert!(
3684 !layers.contains(&machine),
3685 "the operator's {} must not be a layer in a test build",
3686 machine.display()
3687 );
3688 }
3689 }
3690
3691 #[test]
3692 fn auto_upgrade_config_defaults_and_opt_in() {
3693 let default: Update = toml::from_str("").unwrap();
3694 assert!(!default.auto_restart);
3695 assert_eq!(default.mode, UpdateMode::Notify);
3696 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
3697 assert!(enabled.auto_restart);
3698 assert_eq!(enabled.interval.as_deref(), Some("2h"));
3699 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
3700 }
3701
3702 #[test]
3703 fn starter_toml_loads_through_teravars() {
3704 let dir = tempfile::tempdir().unwrap();
3705 let path = dir.path().join("magi.toml");
3706 std::fs::write(&path, Config::starter_toml()).unwrap();
3707 let parsed = Config::load(&path).expect("starter config must load");
3708 assert_eq!(parsed.graph.implementers, 3);
3709 assert_eq!(parsed.merge.mode, MergeMode::None);
3710 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3711 assert!(parsed.graph.sessions);
3712 assert!(parsed.graph.github_text_guard);
3713 assert_eq!(parsed.graph.timeout_review, 1200);
3714 assert_eq!(parsed.graph.verify_timeout(), 1200);
3715 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3716 }
3717
3718 #[test]
3719 fn release_defaults_to_actions_and_the_starter_documents_it() {
3720 let dir = tempfile::tempdir().unwrap();
3721 let path = dir.path().join("magi.toml");
3722 std::fs::write(&path, Config::starter_toml()).unwrap();
3723 let r = Config::load(&path).unwrap().release;
3724 assert_eq!(r.mode, ReleaseMode::Actions);
3725 assert!(!r.is_local());
3726 assert!(r.commands.is_empty());
3727 assert_eq!(r.timeout_minutes, 30);
3728 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3729 }
3730
3731 #[test]
3732 fn release_local_parses_and_unknown_keys_are_refused() {
3733 let dir = tempfile::tempdir().unwrap();
3734 let path = dir.path().join("magi.toml");
3735 std::fs::write(
3736 &path,
3737 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3738 )
3739 .unwrap();
3740 let r = Config::load(&path).unwrap().release;
3741 assert!(r.is_local());
3742 assert_eq!(r.commands.len(), 2);
3743 assert_eq!(r.timeout_minutes, 5);
3744 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3745 assert!(Config::load(&path).is_err());
3746 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3747 assert!(Config::load(&path).is_err());
3748 }
3749
3750 #[test]
3751 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3752 let dir = tempfile::tempdir().unwrap();
3753 let path = dir.path().join("magi.toml");
3754 std::fs::write(&path, Config::starter_toml()).unwrap();
3755 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3756 assert!(Config::starter_toml().contains("# pre_gate = []"));
3757 }
3758
3759 #[test]
3760 fn release_version_files_parse_default_empty_and_are_validated() {
3761 let dir = tempfile::tempdir().unwrap();
3762 let path = dir.path().join("magi.toml");
3763 std::fs::write(&path, "").unwrap();
3764 assert!(
3765 Config::load(&path)
3766 .unwrap()
3767 .release
3768 .version_files
3769 .is_empty()
3770 );
3771 std::fs::write(
3772 &path,
3773 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3774 )
3775 .unwrap();
3776 let files = Config::load(&path).unwrap().release.version_files;
3777 assert_eq!(files.len(), 2);
3778 assert_eq!(files[1].kind, VersionKind::Json);
3779 for bad in [
3780 "{ path = \"package.json\", kind = \"json\" }",
3781 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3782 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3783 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3784 ] {
3785 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3786 assert!(Config::load(&path).is_err(), "{bad}");
3787 }
3788 assert!(Config::starter_toml().contains("# version_files = ["));
3789 }
3790
3791 #[test]
3792 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3793 let starter = Config::starter_toml();
3794 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3795 assert!(starter.contains("verification independent if timeout_review changes later"));
3796 assert!(starter.contains("# timeout_verify = 1200"));
3797 }
3798
3799 #[test]
3800 fn starter_toml_documents_chat_personas() {
3801 let starter = Config::starter_toml();
3802 assert!(starter.contains("# [[talk.personas]]"));
3803 assert!(starter.contains("tone only"));
3804 }
3805
3806 #[test]
3807 fn talk_personas_parse_and_are_validated() {
3808 let dir = tempfile::tempdir().unwrap();
3809 let path = dir.path().join("magi.toml");
3810 std::fs::write(
3811 &path,
3812 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3813 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3814 )
3815 .unwrap();
3816 let cfg = Config::load(&path).expect("loads");
3817 assert_eq!(cfg.talk.personas.len(), 2);
3818 let catalog = crate::persona::catalog(&cfg.talk.personas);
3819 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3820 assert_eq!(
3821 (rei.name.as_str(), rei.prompt.as_str()),
3822 ("Quiet", "Be brief.")
3823 );
3824 assert_eq!(catalog.last().unwrap().id, "gendo");
3825
3826 for (body, needle) in [
3827 (
3828 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3829 "empty `id`",
3830 ),
3831 (
3832 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3833 "empty `prompt`",
3834 ),
3835 (
3836 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3837 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3838 "more than once",
3839 ),
3840 (
3841 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3842 "cannot be redefined",
3843 ),
3844 ] {
3845 std::fs::write(&path, body).unwrap();
3846 let err = format!("{:#}", Config::load(&path).unwrap_err());
3847 assert!(err.contains(needle), "{needle}: {err}");
3848 }
3849 }
3850
3851 #[test]
3852 fn talk_operator_name_is_trimmed_and_validated() {
3853 let dir = tempfile::tempdir().unwrap();
3854 let path = dir.path().join("magi.toml");
3855 let load = |body: &str| {
3856 std::fs::write(&path, body).unwrap();
3857 Config::load(&path)
3858 };
3859 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3860 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3861 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3862 assert_eq!(blank.talk.operator_name(), None);
3863 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3864 let long = "x".repeat(65);
3865 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3866 }
3867
3868 #[test]
3869 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3870 let dir = tempfile::tempdir().unwrap();
3871 let load = |body: &str| {
3872 let path = dir.path().join("c.toml");
3873 std::fs::write(&path, body).unwrap();
3874 Config::load(&path)
3875 };
3876 let ok = load(
3877 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3878 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3879 )
3880 .unwrap();
3881 let c = crate::persona::catalog(&ok.talk.personas);
3882 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3883 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3884 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3885 let oversized = format!(
3886 "data:image/png;base64,{}",
3887 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3888 );
3889 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3890 for (id, fields) in [
3891 ("rei", ""),
3892 ("default", ""),
3893 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3894 ] {
3895 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3896 let cfg = load(&body).expect("bad icon must not invalidate config");
3897 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3898 assert_eq!(persona.id, id);
3899 assert!(crate::persona_icon::load(bad).is_err());
3900 }
3901 }
3902 let doc = Config::starter_toml();
3903 assert!(doc.contains("# icon = "));
3904 }
3905
3906 #[test]
3907 fn talk_personas_in_two_layers_are_refused() {
3908 let dir = tempfile::tempdir().unwrap();
3909 let machine = dir.path().join("machine.toml");
3910 let repo = dir.path().join("repo.toml");
3911 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3912 std::fs::write(&machine, one).unwrap();
3913 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3914 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3915 assert!(err.contains("talk.personas"), "{err}");
3916 }
3917
3918 #[test]
3919 fn starter_toml_documents_role_lists_as_backup_order() {
3920 let starter = Config::starter_toml();
3921 assert!(starter.contains("also an ordered backup list"));
3922 assert!(starter.contains("codex then sonnet are spares"));
3923 }
3924
3925 #[test]
3929 fn a_repository_can_declare_a_linear_history_merge_style() {
3930 let dir = tempfile::tempdir().unwrap();
3931 let path = dir.path().join("magi.toml");
3932 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3933 let parsed = Config::load(&path).expect("config must load");
3934 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3935 }
3936
3937 #[test]
3938 fn later_layers_win_and_vars_render() {
3939 let dir = tempfile::tempdir().unwrap();
3940 let machine = dir.path().join("machine.toml");
3941 let project = dir.path().join("magi.toml");
3942 std::fs::write(
3944 &machine,
3945 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3946 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3947 )
3948 .unwrap();
3949 std::fs::write(
3952 &project,
3953 "[vars]\ncache = \"/shared\"\n\n\
3954 [graph]\ncandidates = 2\n\n\
3955 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3956 )
3957 .unwrap();
3958
3959 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3960 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3961 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3962 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3963 assert_eq!(
3964 cfg.verify.gate,
3965 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3966 );
3967 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3969 }
3970
3971 #[test]
3972 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3973 let g = Graph::default();
3977 assert_eq!(g.timeout_talk, 3600);
3978
3979 let dir = tempfile::tempdir().unwrap();
3980 let path = dir.path().join("magi.toml");
3981 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3982 let cfg = Config::load(&path).expect("must load without timeout_talk set");
3983 assert_eq!(cfg.graph.timeout_talk, 3600);
3984 }
3985
3986 #[test]
3987 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3988 let dir = tempfile::tempdir().unwrap();
3989 let path = dir.path().join("magi.toml");
3990 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3991 let cfg = Config::load(&path).expect("must load");
3992 assert_eq!(cfg.graph.timeout_talk, 120);
3993 }
3994
3995 #[test]
3996 fn the_disk_defaults_are_the_measurements_made_up_front() {
3997 let cfg = Config::default();
3998 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3999 assert!(cfg.disk.auto_fold);
4000 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
4001 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
4002 }
4003
4004 #[test]
4005 fn an_unset_disk_section_is_the_safe_default() {
4006 let dir = tempfile::tempdir().unwrap();
4007 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
4008 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
4009 assert_eq!(cfg.disk, Disk::default());
4010 }
4011
4012 #[test]
4013 fn env_is_available_to_templates_with_a_default() {
4014 let dir = tempfile::tempdir().unwrap();
4015 let path = dir.path().join("magi.toml");
4016 std::fs::write(
4024 &path,
4025 "[verify]\n\
4026 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
4027 \"populated={{ env | length > 0 }}\"]\n",
4028 )
4029 .unwrap();
4030 let cfg = Config::load(&path).expect("env lookup must render");
4031 assert_eq!(cfg.verify.gate[0], "cache=fallback");
4032 assert_eq!(cfg.verify.gate[1], "populated=true");
4033 }
4034
4035 #[test]
4036 fn a_broken_template_names_the_file() {
4037 let dir = tempfile::tempdir().unwrap();
4038 let path = dir.path().join("magi.toml");
4039 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
4040 let err = Config::load(&path).expect_err("must not silently ignore");
4041 assert!(err.to_string().contains("teravars"), "{err}");
4042 }
4043
4044 #[test]
4045 fn tera_syntax_in_comments_is_inert() {
4046 let dir = tempfile::tempdir().unwrap();
4050 let path = dir.path().join("magi.toml");
4051 std::fs::write(
4052 &path,
4053 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
4054 [graph]\ncandidates = 2\n",
4055 )
4056 .unwrap();
4057 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
4058 assert_eq!(cfg.graph.implementers, 2);
4059 }
4060
4061 #[test]
4062 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
4063 use std::time::Duration;
4064
4065 let mut s: AgentSpec =
4066 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
4067 let budget = Duration::from_millis(1500);
4068 assert_eq!(s.max_turn_secs, None);
4069 assert_eq!(s.turn_timeout(budget), budget);
4070 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
4071 for (cap, expected) in [
4072 (1, Duration::from_secs(1)),
4073 (2, budget),
4074 (0, Duration::ZERO),
4075 ] {
4076 s.max_turn_secs = Some(cap);
4077 let saved = toml::to_string(&s).unwrap();
4078 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
4079 assert_eq!(loaded.max_turn_secs, Some(cap));
4080 assert_eq!(loaded.turn_timeout(budget), expected);
4081 }
4082 }
4083
4084 #[test]
4085 fn opencode_defaults_to_file_delivery() {
4086 let mut s = spec("oc");
4087 s.kind = AgentKind::Opencode;
4088 assert_eq!(s.delivery(), Delivery::File);
4089 s.prompt_delivery = Some(Delivery::Argv);
4090 assert_eq!(s.delivery(), Delivery::Argv);
4091 }
4092 #[test]
4093 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
4094 let g = Graph::default();
4099 assert!(
4100 g.land,
4101 "stopping at an open PR left the watching to a human"
4102 );
4103 assert!(
4104 g.land_approval,
4105 "on-by-default land is only defensible while this is also on"
4106 );
4107 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4108 assert!(
4109 g.hold_contested_merge,
4110 "a contested hand-off must still reach a human when approvals are off"
4111 );
4112 }
4113 #[test]
4114 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4115 let dir = tempfile::tempdir().unwrap();
4119 let machine = dir.path().join("machine.toml");
4120 let repo = dir.path().join("magi.toml");
4121 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4122 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4123
4124 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4125 .expect_err("two layers naming one array must not merge silently");
4126 assert_eq!(
4127 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4128 "config-merge"
4129 );
4130 let err = err.to_string();
4131 assert!(err.contains("roles.implementers"), "{err}");
4132 assert!(err.contains("machine.toml"), "{err}");
4135 assert!(err.contains("magi.toml"), "{err}");
4136 }
4137
4138 #[test]
4139 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4140 let dir = tempfile::tempdir().unwrap();
4143 let machine = dir.path().join("machine.toml");
4144 let repo = dir.path().join("magi.toml");
4145 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4146 std::fs::write(
4147 &repo,
4148 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4149 [roles]\nimplementers = [\"oc\"]\n",
4150 )
4151 .unwrap();
4152
4153 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4154 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4155 assert_eq!(cfg.roles.implementers, ["oc"]);
4156 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4157 }
4158
4159 #[test]
4160 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4161 let dir = tempfile::tempdir().unwrap();
4164 let machine = dir.path().join("machine.toml");
4165 let repo = dir.path().join("magi.toml");
4166 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4167 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4168
4169 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4170 assert_eq!(
4171 cfg.verify.gate,
4172 [
4173 "editorconfig-checker".to_owned(),
4174 "cargo make check".to_owned()
4175 ],
4176 "low-priority (machine) command first, high-priority (repo) command after"
4177 );
4178 }
4179
4180 fn load_one(body: &str) -> Result<Config> {
4181 let dir = tempfile::tempdir().unwrap();
4182 let path = dir.path().join("magi.toml");
4183 std::fs::write(&path, body).unwrap();
4184 Config::load_layers(&[path])
4185 }
4186
4187 #[test]
4188 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4189 assert!(Config::default().worktree.setup.is_empty());
4190 let cfg = load_one(
4191 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4192 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4193 )
4194 .unwrap();
4195 assert_eq!(cfg.worktree.setup.len(), 3);
4196 assert!(cfg.worktree.setup[1].optional);
4197 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4198 }
4199
4200 #[test]
4201 fn worktree_setup_rejects_malformed_steps() {
4202 for bad in [
4203 "{ copy = \"a\", run = \"b\" }",
4204 "{ optional = true }",
4205 "{ copy = \"a -> ../b\" }",
4206 "{ copy = \"a -> /abs\" }",
4207 "{ copy = \"a -> .git/config\" }",
4208 "{ run = \"b\", optional = true }",
4209 "{ copy = \"a\", timeout_secs = 3 }",
4210 "{ run = \"b\", bogus = 1 }",
4211 ] {
4212 let body = format!("[worktree]\nsetup = [{bad}]\n");
4213 assert!(load_one(&body).is_err(), "{bad}");
4214 }
4215 }
4216
4217 #[test]
4218 fn worktree_setup_in_two_layers_is_refused() {
4219 let dir = tempfile::tempdir().unwrap();
4220 let machine = dir.path().join("machine.toml");
4221 let repo = dir.path().join("magi.toml");
4222 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4223 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4224 assert!(Config::load_layers(&[machine, repo]).is_err());
4225 }
4226
4227 #[test]
4228 fn starter_toml_documents_worktree_setup() {
4229 let starter = Config::starter_toml();
4230 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4231 let body = starter.replace("# [worktree]", "[worktree]");
4233 let mut out = String::new();
4234 let mut live = false;
4235 for line in body.lines() {
4236 if line == "[worktree]" {
4237 live = true;
4238 } else if live && !line.starts_with("# ") {
4239 live = false;
4240 }
4241 out.push_str(&if live {
4242 line.replacen("# ", "", 1)
4243 } else {
4244 line.to_owned()
4245 });
4246 out.push('\n');
4247 }
4248 let cfg = load_one(&out).expect("uncommented example loads");
4249 assert_eq!(cfg.worktree.setup.len(), 3);
4250 }
4251
4252 #[test]
4253 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4254 let dir = tempfile::tempdir().unwrap();
4255 let machine = dir.path().join("machine.toml");
4256 let repo = dir.path().join("magi.toml");
4257 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4258 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4259
4260 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4261 assert_eq!(
4262 cfg.verify.e2e,
4263 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4264 );
4265 }
4266
4267 #[test]
4268 fn two_layers_declaring_repos_roots_are_both_scanned() {
4269 let dir = tempfile::tempdir().unwrap();
4270 let machine = dir.path().join("machine.toml");
4271 let repo = dir.path().join("magi.toml");
4272 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4273 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4274
4275 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4276 assert_eq!(
4277 cfg.repos.roots,
4278 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4279 );
4280 }
4281
4282 #[test]
4283 fn duplicate_gate_commands_across_layers_both_run() {
4284 let dir = tempfile::tempdir().unwrap();
4287 let machine = dir.path().join("machine.toml");
4288 let repo = dir.path().join("magi.toml");
4289 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4290 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4291
4292 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4293 assert_eq!(
4294 cfg.verify.gate,
4295 ["same-command".to_owned(), "same-command".to_owned()]
4296 );
4297 }
4298
4299 #[test]
4300 fn notify_command_is_still_refused_across_two_layers() {
4301 let dir = tempfile::tempdir().unwrap();
4303 let machine = dir.path().join("machine.toml");
4304 let repo = dir.path().join("magi.toml");
4305 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4306 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4307
4308 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4309 .expect_err("an argv split across layers must not concatenate");
4310 assert_eq!(
4311 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4312 "config-merge"
4313 );
4314 let err = err.to_string();
4315 assert!(err.contains("notify.command"), "{err}");
4316 assert!(err.contains("machine.toml"), "{err}");
4317 assert!(err.contains("magi.toml"), "{err}");
4318 }
4319
4320 #[test]
4321 fn one_layer_declaring_verify_gate_runs_unchanged() {
4322 let dir = tempfile::tempdir().unwrap();
4325 let path = dir.path().join("magi.toml");
4326 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4327
4328 let cfg = Config::load(&path).expect("single layer must still load");
4329 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4330 }
4331
4332 #[test]
4333 fn layered_parse_failures_name_the_failing_input() {
4334 let dir = tempfile::tempdir().unwrap();
4335 let a = dir.path().join("a.toml");
4336 let b = dir.path().join("b.toml");
4337 std::fs::write(&a, "[graph").unwrap();
4338 std::fs::write(&b, "[verify").unwrap();
4339 let paths = [a.clone(), b.clone()];
4340 let first = Config::load_layers(&paths).unwrap_err();
4341 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4342 assert_eq!(first_cause.stage, "config-parse");
4343 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4344 std::fs::write(&a, "").unwrap();
4345 let second = Config::load_layers(&paths).unwrap_err();
4346 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4347 assert_eq!(second_cause.stage, "config-parse");
4348 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4349 assert_ne!(first_cause.target, second_cause.target);
4350 }
4351
4352 #[test]
4353 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4354 let dir = tempfile::tempdir().unwrap();
4355 let machine = dir.path().join("machine.toml");
4356 let repo = dir.path().join("magi.toml");
4357 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4358 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4359 let paths = vec![machine.clone(), repo.clone()];
4360
4361 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4362 let described =
4363 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4364 assert!(described.contains("editorconfig-checker && cargo make check"));
4365 assert!(
4366 described.contains(&machine.display().to_string()),
4367 "{described}"
4368 );
4369 assert!(
4370 described.contains(&repo.display().to_string()),
4371 "{described}"
4372 );
4373
4374 let single = vec![repo.clone()];
4376 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4377 let solo_described =
4378 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4379 assert_eq!(solo_described, "cargo make check");
4380 }
4381
4382 mod remote_layers {
4383 use super::*;
4384
4385 fn git(dir: &Path, args: &[&str]) {
4386 use crate::proc::Quiet as _;
4387 let out = std::process::Command::new("git")
4388 .args(args)
4389 .quiet()
4390 .current_dir(dir)
4391 .output()
4392 .unwrap();
4393 assert!(out.status.success(), "git {args:?}: {out:?}");
4394 }
4395
4396 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4399 let tmp = tempfile::tempdir().unwrap();
4400 let bare = tmp.path().join("o.git");
4401 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4402 let repo = tmp.path().join("repo");
4403 std::fs::create_dir_all(&repo).unwrap();
4404 git(&repo, &["init", "-b", "trunk"]);
4405 git(&repo, &["config", "user.name", "t"]);
4406 git(&repo, &["config", "user.email", "t@example.com"]);
4407 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4408 git(&repo, &["add", "-A"]);
4409 git(&repo, &["commit", "-m", "x"]);
4410 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4411 git(&repo, &["push", "origin", "trunk"]);
4412 git(&repo, &["fetch", "origin"]);
4413 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4414 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4415 (tmp, repo)
4416 }
4417
4418 #[tokio::test]
4419 async fn branch_owner_holds_only_add_literal_true_values() {
4420 for (text, expected) in [
4421 ("[graph]\nland_approval = true\n", true),
4422 ("[graph]\nland_approval = false\n", false),
4423 ("[graph]\nland = true\n", false),
4424 ("[graph\n", false),
4425 ("[graph]\nland_approval = \"yes\"\n", false),
4426 ("[graph]\nland_approval = 1\n", false),
4427 ] {
4428 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4429 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4430 let (holds, _) = branch_owner_holds(&repo, &head).await;
4431 assert_eq!(
4432 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4433 expected
4434 );
4435 assert!(
4436 !holds
4437 .iter()
4438 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4439 );
4440 for base in [false, true] {
4441 let mut cfg = Config::default();
4442 cfg.graph.land_approval = base;
4443 let mut state = crate::run::RunState::new(
4444 repo.clone(),
4445 "trunk".into(),
4446 head.clone(),
4447 "review".into(),
4448 cfg,
4449 );
4450 state.observe_branch_owner_holds(&head).await;
4451 assert!(
4452 state.branch_owner_holds.is_empty(),
4453 "competition candidates are excluded"
4454 );
4455 state.reviewed_commits = Some(Vec::new());
4456 state.observe_branch_owner_holds(&head).await;
4457 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4458 }
4459 }
4460 }
4461
4462 #[tokio::test]
4463 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4464 let (_tmp, repo) = fixture(
4465 "[graph]\nland_approval = true\n",
4466 "[graph]\nland_approval = true\n",
4467 );
4468 git(&repo, &["rm", "magi.toml"]);
4469 std::fs::create_dir(repo.join(".magi")).unwrap();
4470 std::fs::write(
4471 repo.join(".magi/config.toml"),
4472 "[graph]\nhold_contested_merge = true\n",
4473 )
4474 .unwrap();
4475 git(&repo, &["add", "."]);
4476 git(&repo, &["commit", "-m", "nested hold"]);
4477 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4478 let (holds, _) = branch_owner_holds(&repo, &head).await;
4479 assert_eq!(
4480 holds,
4481 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4482 );
4483 let (holds, diagnostics) =
4484 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4485 assert!(holds.is_empty());
4486 assert!(!diagnostics.is_empty());
4487 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4488 assert!(holds.is_empty());
4489 assert!(!diagnostics.is_empty());
4490 for base in [false, true] {
4491 let mut cfg = Config::default();
4492 cfg.graph.land_approval = base;
4493 let mut state = crate::run::RunState::new(
4494 repo.clone(),
4495 "trunk".into(),
4496 head.clone(),
4497 "review".into(),
4498 cfg,
4499 );
4500 state.reviewed_commits = Some(Vec::new());
4501 state.observe_branch_owner_holds(&head).await;
4502 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4503 state
4504 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4505 .await;
4506 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4507 }
4508 }
4509
4510 #[test]
4511 fn reads_the_remote_blob_not_the_working_tree() {
4512 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4513 let (cfg, _) = Config::discover(&repo, None).unwrap();
4514 assert_eq!(cfg.graph.implementers, 2);
4515 }
4516
4517 #[test]
4518 fn detached_head_still_reads_the_remote() {
4519 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4520 git(&repo, &["checkout", "--detach"]);
4521 let (cfg, _) = Config::discover(&repo, None).unwrap();
4522 assert_eq!(cfg.graph.implementers, 2);
4523 }
4524
4525 #[test]
4526 fn a_missing_ref_is_an_error_not_a_fallback() {
4527 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4528 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4529 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4530 assert!(err.contains("origin"), "{err}");
4531 }
4532
4533 #[test]
4534 fn merge_base_in_the_checkout_locates_the_ref() {
4535 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4536 assert!(Config::discover(&repo, None).is_err());
4537 }
4538
4539 #[test]
4540 fn the_magi_dir_layer_is_read_too() {
4541 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4542 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4543 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4544 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4545 git(&repo, &["add", "-A"]);
4546 git(&repo, &["commit", "-m", "y"]);
4547 git(&repo, &["push", "origin", "trunk"]);
4548 git(&repo, &["fetch", "origin"]);
4549 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4550 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4551 assert_eq!(layers.len(), 2);
4552 }
4553
4554 #[test]
4555 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4556 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4557 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4558 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4559 git(&repo, &["add", "-A"]);
4560 git(&repo, &["commit", "-m", "inc"]);
4561 git(&repo, &["push", "origin", "trunk"]);
4562 git(&repo, &["fetch", "origin"]);
4563 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4565 let (cfg, _) = Config::discover(&repo, None).unwrap();
4566 assert_eq!(cfg.graph.implementers, 2);
4567 }
4568
4569 #[test]
4570 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4571 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4572 let m = t.path().join("machine.toml");
4573 std::fs::write(
4574 &m,
4575 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4576 )
4577 .unwrap();
4578 let (remote, base) = {
4579 let probe = probe_merge(&m, &repo).unwrap();
4580 (probe.remote, probe.base)
4581 };
4582 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4583 }
4584
4585 #[test]
4586 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4587 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4588 let m = t.path().join("machine.toml");
4589 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4590 let probe = probe_merge(&m, &repo).unwrap();
4591 assert_eq!(probe.base.as_deref(), Some("repo"));
4592 }
4593
4594 #[test]
4595 fn every_include_form_is_recognised() {
4596 assert!(declares_include("include = [\"a.toml\"]\n"));
4597 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4598 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4599 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4600 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4601 }
4602
4603 #[test]
4604 fn an_explicit_config_is_read_as_named() {
4605 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4606 let own = t.path().join("own.toml");
4607 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4608 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4609 assert_eq!(cfg.graph.implementers, 4);
4610 }
4611
4612 #[test]
4613 fn discover_fetched_fails_when_the_fetch_does() {
4614 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4615 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4616 let rt = tokio::runtime::Builder::new_current_thread()
4617 .enable_all()
4618 .build()
4619 .unwrap();
4620 let err = rt
4621 .block_on(Config::discover_fetched(&repo, None))
4622 .unwrap_err();
4623 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4624 }
4625
4626 #[test]
4627 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4628 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4629 let remote = tmp.path().join("o.git");
4630 let offline = tmp.path().join("offline.git");
4631 std::fs::rename(&remote, &offline).unwrap();
4632 let rt = tokio::runtime::Builder::new_current_thread()
4633 .enable_all()
4634 .build()
4635 .unwrap();
4636 let fetch = rt
4637 .block_on(Config::discover_fetched(&repo, None))
4638 .unwrap_err();
4639 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4640 assert_eq!(fetch_cause.stage, "config-fetch");
4641 assert_eq!(fetch_cause.target, "origin/trunk");
4642
4643 std::fs::rename(&offline, &remote).unwrap();
4644 let parse = rt
4645 .block_on(Config::discover_fetched(&repo, None))
4646 .unwrap_err();
4647 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4648 assert_eq!(parse_cause.stage, "config-parse");
4649 assert!(parse_cause.target.contains("magi.toml"));
4650 assert!(
4651 !parse_cause.target.contains("/magi/config/"),
4652 "cache commit paths are incidental"
4653 );
4654 assert_ne!(fetch_cause.stage, parse_cause.stage);
4655 }
4656
4657 #[test]
4658 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4659 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4662 git(&repo, &["remote", "set-head", "origin", "-d"]);
4663 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4664 git(
4665 &repo,
4666 &["config", "remote.origin.followRemoteHEAD", "never"],
4667 );
4668 let rt = tokio::runtime::Builder::new_current_thread()
4669 .enable_all()
4670 .build()
4671 .unwrap();
4672 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4673 assert_eq!(cfg.graph.implementers, 2);
4674 }
4675
4676 #[test]
4677 fn a_non_git_directory_reads_its_files() {
4678 let dir = tempfile::tempdir().unwrap();
4679 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4680 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4681 assert_eq!(cfg.graph.implementers, 4);
4682 }
4683 }
4684
4685 #[test]
4686 fn github_language_defaults_to_english_and_accepts_japanese() {
4687 let default: Graph = toml::from_str("").unwrap();
4688 assert_eq!(default.github_language, "en");
4689 assert!(default.github_english() && default.language_gate());
4690 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4691 assert!(!ja.github_english() && !ja.language_gate());
4692 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4694 assert!(only_ops.language_gate());
4695 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4696 assert!(!off.language_gate() && off.github_english());
4697 assert!(Config::starter_toml().contains("github_language = \"en\""));
4698 }
4699}